Morris Mulitu
Posted on August 11, 2021
If you want to build a web app in Python then it is highly likely that you will use a framework!. A framework "is a code library that makes a developer's life easier when building reliable, scalable, and maintainable web applications" Flask is such a framework in Python.
Flask is relatively a new framework. It has however taken the python web development world by storm. It has become quite popular. It is offering alot of extensibility, flexibility and clean code possibilities.
Why Flask?
Flask is thought to be more pythonic than Django due to the fact that the equivalent Flask web application is more explicit. Ideally, it is also easier to get started with for beginners.
Hello, World! with Flask
from flask import Flask
app = Flask(__name__)
@app.route('/')
def hello_world():
return 'Hello, World!'
if __name__ == '__main__':
app.run()
Install the Flask library. This code will show "Hello, World!" on localhost port 5000 if you run it.
Flask startup!
You can install the Flask package from PPI
(Python Package Index)
First make a directory eg, flask_todo and then have the flask package installed. Also install flask-sqlalchemy to facilitate a simpler SQL database connection.
It is best to work in a virtual environment.
Do enter the following commands;
$ mkdir flask_todo
$ cd flask_todo
$ pipenv install --python 3.6
$ pipenv shell
(flask-someHash) $ pipenv install flask flask-sqlalchemy
Just in case you want to make if a Git repo, do run git init here.This will be the project's root. Just incase you intend to codebase to different machines you can have all the setup files in this directory.
The best way to move it is to turn the codebase into an installable Python distribution. While at the root of the project create a setup.py and a directory todo to hold the source code.
An example of the setup.py is as below;
from setuptools import setup, find_packages
requires = [
'flask',
'flask-sqlalchemy',
'psycopg2',
]
setup(
name='flask_todo',
version='0.0',
description='A To-Do List built with Flask',
author='<Your actual name here>',
author_email='<Your actual e-mail address here>',
keywords='web flask',
packages=find_packages(),
include_package_data=True,
install_requires=requires
)
With this you will have all the needed packages in the requires list.Additionally, you'll also have everything you need to set up and install the package in site-packages.
In the todo directory, create init.py and app.py files.The init.py file allows you to import from todo as if it was an installed package. The app.py file will be the application's root. Just in case you are using pipenv you can find your virtual environment with pipenv --venv and set up that environment variable in your environment's active script.
export FLASK_APP=$VIRTUAL_ENV/../todo/app.py
export DEBUG='True'
A little code!
from flask import Flask
app = Flask(__name__)
@app.route('/')
def hello_world():
"""Print 'Hello, world!' as the response body."""
return 'Hello, world!'
This is a basic Flask application.app is an instance of Flask taking in the name of the script file.
app.route specifies the routes used to access the application.Any view you specify must be decorated by app.route to be a functional part of the application.In this example, when the app is running and accessed at http://domainname/, the user will receive "Hello, World!" as a response.
Connecting the database in Flask
The flask-sqlalchemy package connects a SQL database to a Flask application.You need the database URL to connect to a SQL database.You can use Postgres database.The intermediary to talk to the Postgres database is the psycopg2 package.Include it in the list of required packages in setup.py. The flask-sqlalchemy will recognize Postgres from the database URL. Flask will need the database URL to be part of its central configuration through the SQLALCHEMY_DATABASE_URI attribute.
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'postgres://localhost:5432/flask_todo'
db = SQLAlchemy(app)
You can make use of environment variables to make things easier.They ensures that, no matter what machine the code is on, it will always point tp the right stuff if that stuff is configured in the running environment.
In the same place you declared FLASK_APP, declare a DATABASE_URL pointing to the location of your Postgres database. Development tends to work locally, so just point to your local database.
Your application has a database connection! Awesome
Do enjoy!
Posted on August 11, 2021
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.