Setting Up a Flask App and Deploying It Via Google Cloud

In this tutorial, we will walk through the process of creating a basic Flask application, setting up configurations via an .env file, enabling CORS, and deploying the app to Google Cloud Platform (GCP).

0. Requirements

skip this step if you well experienced with python

Install python depending on your windows & MacOS

python install ]

Click the download execution file and follow the steps of wizard.

python installation

Select Add python.exe to PATH

installationprocess

Open your favorite IDE I recommend VScode

python3 -m pip install --user virtualenv

then create your virtual environment. What is virtual environment?
think of it of as a bubble to manage different libraries and versions of libraries it can be useful to run old libraries and ML algorithms in virtual environment that would not be possible to fix in latest version of pyhton.

python -m venv env

in the terminal type in ls to list out all objects in directory

ls

here you can see our “env” environment.

directory

How to enter python virtual environment? on windows

.\env\Scripts\activate

for MacOS

.\env\Bin\activate

env

from here you can pip install any library like “pip install Flask” or “pip install PIL”

1. Setting up Your Flask Application

Install Flask using pip:

pip install Flask

pipinstallFlask

Create Your Flask App:

createfileinvscode

Within this directory, create a file named app.py.

apppy

Write your Flask application code in app.py.

from flask import Flask
app = Flask(__name__)

@app.route('/')
def hello():
    return "Hello World!"

if __name__ == '__main__':
    app.run(debug=True)

pythonapp

You can ctrl+click “http://127.0.0.1:5000” to open the server on the browser up locally

Helloworld

2. Testing Your Flask Application Locally

Run your Flask application locally to ensure it’s working as expected:

run this command in your terminal.

python app.py

3. Configuring Environment Variables

Install python-dotenv:

pip install python-dotenv

Create a .env file:

In the root of your project directory, create a file named .env and add your configurations:

FLASK_DEBUG=1

flaskdebug

4. Setting up CORS

Install Flask-CORS:
pip install Flask-CORS
pip install python-dotenv
pip install gunicorn

update the app.py

import os
from flask import Flask
from dotenv import load_dotenv
from flask_cors import CORS

# Load environment variables from .env file
load_dotenv()

app = Flask(__name__)
CORS(app)  # Enable CORS for all routes and origins

# Configure FLASK_DEBUG from environment variable
app.config['DEBUG'] = os.environ.get('FLASK_DEBUG')

@app.route('/')
def hello():
    return "Hello World!"

if __name__ == '__main__':
    app.run()

5. Preparing for Deployment

Create a requirements.txt file:
pip freeze > requirements.txt
blinker==1.6.2
click==8.1.7
colorama==0.4.6
flask==3.0.0
importlib-metadata==6.8.0
itsdangerous==2.1.2
Jinja2==3.1.2
MarkupSafe==2.1.3
werkzeug==3.0.0
zipp==3.17.0
App Engine Configuration:

Create an app.yaml file for GCP App Engine configuration:

runtime: python39
entrypoint: gunicorn -b :$PORT app:app

6. Deploying to Google Cloud Platform

Set up GCP:

Create a Google Cloud Platform account if you do not have one.

Create a new project in the GCP Console.

You will click the dropdown in the upper left

createnewproject

A modal will appear and you select the “NEW PROJECT”

newproject-step2

which will redirect you to page in which you will write the name your project name.

createstep3

Then you will click “create” button

pythonlectureproject step4

it will be shown in the upper right with creation in process and click and it will take you a dashboard

steps6

Now go to google cloud CLI or SDK to intsall the google SDK it will install version of python.

step7download CLI

you will click the executible for googlecloudsdk

googlesdkstep8

it will ask you stuff like get feedback on its cli you can just click next and ignore it

step9

then terms and services click next

step10

select a harddrive to download

step11

then click install

step12

let installation proceed

step13

then go to the terminal and try

gcloud help

you should see this below

step14

Authenticate with GCP using the SDK.

when you gcloud init it will ask you through authentication steps

gcloud init

run this will initate the gcloudcli to ask you for authentication details and configuration

gcloud init

it will ask for details of which project you defaulted here I have to redo the configuration for the lecture seriers

gcloud_step1

So I select 2 as the option we creates a new configuration file called lecture1 I typed in. So google cloud CLI will use this for my deployment calls in the terminal

gcloud_step2

Now it wants to know which account will use this configuration I chose my email lesliemwubbel@gmail.com

gcloud_step3

After that step you will need to select a project here I select 6 because this the pythonlecture series

gcloud_step4

Create Dockerfile:

Read more here from google

Create dockerfile add this contain inside of it

# Dockerfile
FROM python:3.9.17-bookworm
# Allow statements and log messages to immediately appear in the logs
ENV PYTHONUNBUFFERED True
# Copy local code to the container image.
ENV APP_HOME /back-end
WORKDIR $APP_HOME
COPY . ./

RUN pip install --no-cache-dir --upgrade pip
RUN pip install --no-cache-dir -r requirements.txt

# Run the web service on container startup. Here we use the gunicorn
# webserver, with one worker process and 8 threads.
# For environments with multiple CPU cores, increase the number of workers
# to be equal to the cores available.
# Timeout is set to 0 to disable the timeouts of the workers to allow Cloud Run to handle instance scaling.
CMD exec gunicorn --bind :$PORT --workers 1 --threads 8 --timeout 0 app:app

Create a “.dockerignore” file and add this code to ignore deployment and set up files

Dockerfile
README.md
*.pyc
*.pyo
*.pyd
__pycache__
.pytest_cache
Deploy Your App:

Deploy your app using the gcloud command-line tool.

gcloud run deploy --source .

it will spin up CPU service and it will ask you to name it. I named it lecture.

deploy_step1

Then it will ask to deploy the server in specific region of the word I just chose the east coast or us-east4 because its closer to me.

deploy_step2

it will ask “Allow unauthenticated invocations to [lecture] (y/N)?” I say yes

deploy_step3

after that will go through a seriers of checks and spinning up containers and running your dockerfile

deploy_step4

Here’s a ERROR! well its on purpose because I left important step out on my own to show what error looks and how to find the bugs/logs “pip freeze > requirements.txt”

if you click the hyperlink provided in the terminal this will take you to google cloud to see deploy log and see what specific broke this will help you debug issues or detect problematic libraries breaking the installation.

deploy_step5_error_example

requirements.txt is set of libraries python will follow to install on deployment so its exactly the same as on your local machine.

deploy_step6_error_example

Now it works! it deployed

FINALLYDONE

Access Your App:

Once the deployment is successful, you can access your app via the provided URL.

it generate url like this

https://lecture-7olbxwuy7a-uk.a.run.app/

You should see “Hello World”

You can spin the server down by cli

gcloud run services delete lecture-00005-rij --region=us-east4

or

of coruse the UX is terrible and google makes hard to find what containers you have running so to see that go to this url https://console.cloud.google.com/run

it should load the containers you are running

delete2

7. Monitoring and Managing Your App

Use the GCP Console to monitor the performance of your app, view logs, and manage versions.

API calling

Discover more from lesliemwubbel

Subscribe now to keep reading and get access to the full archive.

Continue reading