Python is an interpreted, object-oriented, high-level programming language with dynamic semantics. It has high-level built in data structures, combined with dynamic typing and dynamic binding, make it very attractive for Rapid Application Development, as well as for use as a scripting or glue language to connect existing components together.
Python has a number of frameworks, all geared towards their particular brand of application development. In this boot camp we are going to specifically learn flask and FastAPI.
Web Framework
A web framework is an architecture containing tools, libraries, and functionalities suitable to build and maintain massive web projects using a fast and efficient approach.
They are designed to streamline programs and promote code reuse.
To create the server-side of the web application, you need to use a server-side language. Python is home to numerous such frameworks, famous among which are Django, Flask and FastAPI .
FastAPI
From the official documentation, FastAPI is a modern [and] fast (high-performance) web framework for building APIs with Python 3.6+ based on standard Python type hints.
As evident from the name, FastAPI is extremely fast and it owes this to the to out of the box support of the async feature of Python 3.6+. This is why it is recommended to use the latest versions of Python.
A number of tech giants like Microsoft, Uber and Netflix are already using FastAPI to build their applications.
Key features of FastAPI
Fast: It offers very high performance, on par with NodeJS and Go (thanks to Starlette and Pydantic). It is considered to be one of the fastest Python frameworks available.
Fast to code: It increases the speed to develop applications by about 200% to 300%.
Intuitive: It offers great editor support. The developer needs to spend less time debugging the code to verify whether the code syntax is correct or not.
Less bugs: It reduces about 40% of human (developer) induced bugs.
Easy: It is designed to be easy to use and learn. Also, the official documentation is lucid and well structured and thus takes less time to read.
Short: It supports minimize code duplication. It offers multiple features from each parameter declaration. It also has fewer bugs.
Standards-based: It is based on (and fully compatible with) the open standards for APIs, OpenAPI (previously known as Swagger) and JSON schema.
Robust: Get production-ready code with automatic interactive documentation.
Python Virtual Environments.
It is often useful to have one or more Python environments where you can experiment with different combinations of packages without affecting your main installation.
Python supports this through virtual environments. The virtual environment is a copy of an existing version of Python with the option to inherit existing packages.
A virtual environment is also useful when you need to work on a shared system and do not have permission to install packages as you will be able to install them in the virtual environment.
Creating a Python virtual environment.
1). Install the virtualenv package
>>> pip3 install virtualenv
2). Create the virtual environment, for our case called dev.
>>> python3 -m venv dev
or
virtualenv dev
3). Activate the virtual environment
Mac OS / Linux :
>>> source dev/bin/activate
Windows:
>>> dev\Scripts\activate
4). Deactivate the virtual environment.
To deactivate the virtual environment and use your original Python environment, simply type ‘deactivate’.
>>> deactivate
Python virtualenv documentation: https://docs.python.org/3/tutorial/venv.html
Hello World FASTAPI App
from typing import Optional
from fastapi import FastAPI
app = FastAPI()
@app.get("/")
def read_root():
return { "Message": "Hello World" }
Running You Hello World program 🥳 🥳 🥳 :
Make sure you have uvicord installed using the following command:
>>> pip install uvicorn[standard]
Run the server with a prompt to reload everytime you makes some changes:
>>> uvicorn main:app --reload
More FastAPI Resources.
- Working with templates: https://fastapi.tiangolo.com/advanced/templates/
Working with static files:
https://fastapi.tiangolo.com/tutorial/static-files/Deploying FastAPI service on Amazon Web Services:
https://adem.sh/blog/tutorial-fastapi-aws-lambda-serverless
Flask
Python Flask Framework is a lightweight micro-framework based on Werkzeug, Jinja2.
It is called a micro framework because it aims to keep its core functionality small yet typically extensible to cover an array of small and large applications.
Flask Framework depends on two external libraries: The Jinja2 template, Werkzeug WSGI toolkit.
Remember to use the virtual environment , and while inside your virtual environment run the following command:
>> pip install flask
or
>>> pip3 install flask
Hello World Flask Application
from flask import Flask
app = Flask(__name__)
@app.route('/')
def hello_world():
return 'Hello, World!'
if __name__ == "__main__":
app.run(host = ”---”, port = ____, debug = ___)
- Creating Flask App Object.
The Python flask module contains all the classes and functions needed for building a Flask app. The Flask class can be imported to create the main application object. It takes the name of the app as an argument.
# Import Flask class
from flask import Flask
# Create Flask object
app = Flask(__name__)
- Running Flask App.
A Flask app can be run by exporting the FLASK_APP environment variable and running flask run in the terminal.
>>> export FLASK_APP=app.py
>>> flask run
Creating a Route.
Routes in a Flask app can be created by defining a view function and associating a URL with it using the route() decorator. Routes specify how the Flask app handles requests it receives, such as what to display on the webpage at a certain URL.
@app.route('/')
def hello_world():
return 'Hello, World!'
Returning HTML From Route.
In a Flask app, HTML can be returned from a view function to be rendered on a webpage. The HTML can be returned as a string.
@app.route('/')
def hello_world():
return '<h1>Hello, World!</h1>
Variable Rules.
Variable rules allow a Flask app to respond to dynamic URLs. Variable sections of a URL can be indicated by angular brackets and an optional converter: converter:variable_name. These variable parts will then be passed to the view function as arguments.
@app.route('/page/<int:pg_num>')
def content(pg_num):
return f'<h1>Displaying results for page {pg_num}</h1>'
name == "main".
if __name__ == "__main__"
app.run(host = ” --- ”, port = ____, debug = ___)
The conditional check if name == "main" simply checks if the script being executed is app.py.
Say you created a script called utils.py that only contains print(name). If you import utils.py into app.py and run app.py, the print statement from utils.py will output utils, which is the name of the file.
In the case of app.py the name variable will be “main”.
Note:
If you want to install Flask with support for async, use the following command.
pip3 install flask[async]
Then create a view function using async:
@app.route("/embed/<embed_id>")
async def get_embed(embed_id):
data = await async_render_embed(embed_id)
return data
Caveat:
Async support in flask comes as an add-on 🥲.
Top comments (9)
Wow, Just learnt about flask async today +1 to me + infinity to you.
Great piece
Thank you
Thank you for posting this! Great introduction. Useful for us.
Am glad it was helpful to you.
hi
good
Hey too, yeah a good.
Wow, was just looking for something like this to deploy my ML model, thank you so much!
Am glad it was helpful to you 🥳🥳
Yeah sure and so is FastAPI, You actually should try it . If you need help reach out on twitter, twitter.com/HarunMbaabu