This page is available to give you some helpful hints and reference points when creating and developing Flask projects on your local machine.

If you have questions about Flask, post them to the COMSC StackOverflow with the tag "flask"

If you have questions about the information on this page or feel that it may need to be updated please contact:

starting a new flask project

1. Create a new folder on your local machine

2. Create a new virtual environment returning to your venv

3. Add Source Control ( Cardiff University GitLab )

4. Create a simple server .py file returning to your Flask application

5. Commit Changes to GitLab

Further Advice and Troubleshooting

Deployment to OpenShift

create a python virtual environment for the project ( venv )

In a cmd / terminal, enter:

python3 -m venv myVenv

This action will create a folder "myVenv" (or whatever you have named your venv) in the project folder. You only need to undertake this action once to create the venv for the project.

NB// On your machine you may need to refer to Python as python if the above command raises a message similar to "command not found: python3".

Activate the venv from the cmd. You can do this each time you return to the project.

On Windows, run:

myVenv\Scripts\activate

On Unix or MacOS, run:

source myVenv/bin/activate

To deactivate a virtual environment (for Windows, Unix and MacOS), type:

deactivate

install flask

With the venv active, you need only do this once. If you do this multiple times you will generate a "requirement already satisfied" message.

pip install flask

pip will fetch everything we need and this process will be shown in the cmd / terminal. Wait until this is completed.

Check what packages are available in the venv, you can do this whenever you need to.

pip list

We should see some dependencies relevant to Flask (and anything else you have added to the venv).

benefits of using a virtual environment for a project

To share the packages we have used in a venv for use in another environment, we can create a requirements.txt file.

pip freeze > requirements.txt

video 1

Web Dev Optional Q&A (with demonstration) 23/11/2023

Returning to your Virtual Environment (venv)

When returning to your venv you do not need to recreate it.

Only activate it when necessary from the cmd / terminal by navigating to the project folder, then typing,

On Windows:

myVenv\Scripts\activate

On Unix or MacOS:

source myVenv/bin/activate

To deactivate a virtual environment (for Windows, Unix and MacOS), when you have finished working with the project for the time being, type:

deactivate

add source control (GitLab)

Create a New Project via the GitLab website, make sure this is a presonal project.

In the gitlab interface, give this project an appropriate name (e.g "myFirstAmazingFlaskApp").

Once created, return to work in the Flask project folder you have created on your local machine.

You may want to change your setting to show hidden files, to see the next few steps more easily.

Start your local GitLab project in the cmd / terminal, with:

git init

If you have made hidden files visible you should now see a .git folder.

In our projects, we may have files and folders we do not want to add to Git.

We can tell Git to ignore these files using a .gitignore file, next to our .git folder.

We don't really want our __pycache__/ or venv/ added to Git because these folders take up quite a lot of space and will take a long time to upload and download (and are not necessary for someone else to run the code). Adding a .gitignore file to the project directory deals with this predicament. We write the name of any files we want to remain untracked in the .gitignore file.

create a .txt file named .gitignore and open this with a text editor (NotePad or TextEdit will be fine, or whatever you prefer to use).

NB// you may need to check the file information once created, to change any hidden .txt extension.

Add the folder name for your virtual environment into the .gitignore file

<myVenvName>

Add reference to any __pycache__ folder into the .gitignore file

__pycache__

Add reference to any other folders or files you may want to ignore (e.g. DS_Store for MacOS, .vscode for the its rules for the project, if using this as your IDE).

*.DS_Store .vscode

Add the URL of the GitLab repository (repo) you want to link to. this should be available in the GitLab website after creating a project.

git remote add origin https://git.cardiff.ac.uk/c<yourStudentNumber>/<yourGitLabProjectName>.git

Change the branch you want to work on (if necessary, e.g. from Master to Main).

NB// by default the Cardiff University instance of GitLab creates an initial 'main' branch, but you may find it preferable to refer to a 'master' branch.

Push changes from your local project to chosen repo branch

git push -u origin master

More information about working with Git can be found in these videos:

and here.

Once you have added source control to your project, you do not need to add it again.

A section below describes committing changes from the project, also has some reminders on the steps to follow day-to-day when working on your project once source control with GitLab has been set up.

creating a simple flask app

Create a new server file in this project, e.g. myServer.py

Inside myServer.py (or whatever you have called your server file) enter:

From flask import Flask

(From the flask library we've just installed, we're importing the Flask class) in VS code *Ctrl click on “Flask” allows us the explore the functionality available through the class a little.

app = Flask(__name__)

creates an instance of the Flask class

@app.route("/")
@app.route("/a_little_something")
def do_something():
    return "something"
                

Though not a definition, something really important to remember is, “Routes lead to the execution of code” ( Cooper 2023 ). Our routes bind functions to URLs.

A decorator is, “a function that takes another function as a parameter and returns another function”.

By having app.route as decorator, the function index is registered for the routes "/" and "a_little_something" so that when that route is requested, the function “do_something” is called and its result is returned back to the client (web server).

In this case, simply the string "something".

To run the server, we enter the following command into the cmd / terminal:

flask --app myServer run

NB// You should replace myServer with the name of the server .py file you have chosen

The terminal should display a URL you can navigate to in your chosen browser (Chrome or Firefox recommended).

To stop your flask application running, press CTRL + C

More information about getting started with Flask can be found, here.

video 2

Web Dev Optional Q&A (with demonstration) 30/11/2023

Returning to you Flask application

Once you have added Flask to your virtual environment, you do not need to pip install it again.

When working with your project, after activating the virtual environment , you only need to use the commands to run your application again

flask --app myServer run

and stop the flask server from running, by pressing CTRL + C

Commit Changes to GitLab

Once you have made changes to your project locally, you should push them to your remote repository (repo).

We can check for changes by typing in the cmd / terminal:

git status

This should output any tracked and staged changes.

We can add changes we want to make, ready to be staged and then pushed using:

git add <aFileName>

or, if we are happy to add everything

git add .

use git status here to see changes

We can commit changes with a message ready to be pushed, with:

git commit -m "<my message text here>"

//NB using git status now will generate a message: Your branch is ahead of 'origin/master' by 1 commit. nothing to commit, working tree clean

Then push the changes from your local project to the required branch

git push -u origin <branchName>

In your web browser if you reload your gitlab project page, you should see an updated status of just now

If you in the cmd / terminal locally,

git status

You should see output similar to: Your branch is up to date with 'origin/master'. no changes added to commit

further advice and troubleshooting

When using the command flask run (or similar) if we generate internal server error in the cmd / terminal, we should check the last few lines of the error message.

When working in a virtual environment you'll see lots of errors from the venv folder. Ignore these. Look for an error from within a file you're working in, Python error messages are quite friendly. The last lines of the error message should tell you the file and location within the file that the error message is generated from.

deployment to OpenShift

With thanks to Ian Cooper and Matthew Moore.

To access Cardiff Universities OpenShift cluster control console , you need to activate the Cardiff University VPN

OpenShift is a containerization platform that facilitates the deployment, management, and scaling ofcontainerized applications such as our Flask application. Containers provide a consistent and isolatedenvironment so that multiple containers can be running on a single computer (or Virtual Machine)yet they have high level of security between them. The containers can also be easily replicated if youwish to duplicate the computing power of your application (assuming it is an appropriate application).

deployment pre-requisites for the Flask project

OpenShift deployment uses venv (not pipenv) so will require arequirements.txt file in the root directory of the folder. It will needat least Flask and Gunicorn listed as dependencies, plus any other installs your project requires.

pip install gunicorn

NB// if you have already created a requirements.txt file at an earlier step, over-write this with, pip freeze > requirements.txt

The deployment should run your flask application on a Python WSGI HTTP Server for UNIX calledGunicorn. Gunicorn isconfigured to load up a wsgi.py file in the route directory. This is the file that calls the flask application. You will need to add this file. You should replace the server file name with your Flask application file.

from <myServerFileName> import app as application

The deployment is achieved by loading all the code from the repository in to a “Container”. The container has a base set of software in it defined by us when we chose a Python environment (ratherthan a java environment - this is the builder image). The python image is prebuilt for us. Given that we want a database file in the project, the easiest way to get it there is via the clone from the repo, this means adding the ???.db file to git.

NB// This is not really the best way to do this, but for now it will do.

Accessing GitLab from OpenShift

Project access tokens can act as a password to limited parts of your gitlab account they allow accessvia the GitLab API and command line interface. They have a limited valid duration. Using the projectAccess tokens with OpenShift allows your OpenShift project access to your git project.

To obtain a Project Access Token from git:

This token will eventually be added the deployment project on OpenShift, but first we need to create one.

creating a project in OpenShift

Login to OpenShift and select the +Add tab and there will be a Project dropdown. Select "Create Project" . Give it a name and description, etc.

In the new project, select "Import from Git" , and start to configure the project.

The Git URL is the HTTPS clone address.

topology

At this point, the project will start to build. If you click on topology on the left menu you should see info on your build including the URL to the route of your server. By default this will navigate to the route ("/")

NB// if you see instructions to build and deploy using SSH keys, this is a depreciated feature as of winter 2023 that will never work.

video 3

Web Dev Optional Tutorial (with OpenShift deployment demonstration) 14/12/2023

Web Dev Optional Tutorial (code example - Cardiff University GitLab) 14/12/2023

Web Dev Optional Tutorial (deployment example - Cardiff University OpenShift) 14/12/2023

Once the application is successfully built, you can review any terminal / cmd output you might expect to see when using your application on your local machine through "Topology" > "Resources" > Pods > "View Logs" . This can be quite helpful when troubleshooting.