Flask - BKJackson/BKJackson_Wiki GitHub Wiki

Subpages:

"Flask is an awesome Python web micro-framework" @konukoii

Flask and machine learning

As a template, the step by step flow is as follows:

  • Install Flask
  • Serialise your model (this can be done using Pickle, or JobLib)
  • [optional] Serialise your columns
  • Create a separate [insert name here].py file in the same directory as your serialised model, which will build the web service using Flask
  • Run [insert name here].py file from terminal/command line
  • Go to http address to check if its working
  • Make a http POST call with some data, and receive the prediction back.

A Flask API for serving scikit-learn models, Mar 7, 2016
Deploy a machine learning model with Flask - Feb 1, 2018

Flask HTTPS and SSL Certificates

Running Your Flask Application Over HTTPS - In this article I'm going to present several options for adding encryption to a Flask application, going from an extremely simple one that you can implement in just five seconds, to a robust solution that should give you an A+ rating like my site gets from this exhaustive SSL analysis service.

Flask REST

Postman

Postman - complete API Development Environment for development testing

Flask docs - Pocoo

Flask - pocoo.org Flask docs main page

Patterns for Flask - Lots of patterns for common use cases

Streaming Contents - Sometimes you want to send an enormous amount of data to the client, much more than you want to keep in memory. When you are generating the data on the fly though, how do you send that back to the client without the roundtrip to the filesystem? The answer is by using generators and direct responses.

Flask Extensions - Extensions are extra packages that add functionality to a Flask application. For example, an extension might add support for sending email or connecting to a database. Some extensions add entire new frameworks to help build certain types of applications, like a ReST API.

Modular Flask Applications with Blueprints - Flask uses a concept of blueprints for making application components and supporting common patterns within an application or across applications. Blueprints can greatly simplify how large applications work and provide a central means for Flask extensions to register operations on applications. A Blueprint object works similarly to a Flask application object, but it is not actually an application. Rather it is a blueprint of how to construct or extend an application.

Testing Flask Applications - Something that is untested is broken. Use pytest.

Application Error Handling - Applications fail, servers fail. Sooner or later you will see an exception in production. Even if your code is 100% correct, you will still see exceptions from time to time. Why? Because everything else involved will fail. Here are some situations where perfectly fine code can lead to server errors.

Flask logging - Flask uses standard Python logging. All Flask-related messages are logged under the 'flask' logger namespace. Flask.logger returns the logger named 'flask.app', and can be used to log messages for your application.

Flask configuration handling - Applications need some kind of configuration. There are different settings you might want to change depending on the application environment like toggling the debug mode, setting the secret key, and other such environment-specific things.

Flask Signals - Signals help you decouple applications by sending notifications when actions occur elsewhere in the core framework or another Flask extensions. In short, signals allow certain senders to notify subscribers that something happened.

The big advantage of signals over handlers is that you can safely subscribe to them for just a split second. These temporary subscriptions are helpful for unit testing for example. Say you want to know what templates were rendered as part of a request: signals allow you to do exactly that.

Flask Pluggable Views - Flask 0.7 introduces pluggable views inspired by the generic views from Django which are based on classes instead of functions. The main intention is that you can replace parts of the implementations and this way have customizable pluggable views.

Larger Flask Applications - For larger applications it’s a good idea to use a package instead of a module.

Becoming Big - Scaling your Flask application.

Flask API - This part of the documentation covers all the interfaces of Flask. For parts where Flask depends on external libraries, we document the most important right here and provide links to the canonical documentation.

Design Decisions in Flask - If you are curious why Flask does certain things the way it does and not differently, this section is for you. This should give you an idea about some of the design decisions that may appear arbitrary and surprising at first, especially in direct comparison with other frameworks.

flask.g - Get to know flask.g. flask.g is a namespace object that can store data during an application context.

Flask Security Considerations - Web applications usually face all kinds of security problems and it’s very hard to get everything right. Flask tries to solve a few of these things for you, but there are a couple more you have to take care of yourself.

Flask Deployment Options

While lightweight and easy to use, Flask’s built-in server is not suitable for production as it doesn’t scale well. Some of the options available for properly running Flask in production are documented here.

Make the Flask project installable

You Flask projects should always start with this.

From the Flaskr tutorial docs:
Making your project installable means that you can build a distribution file and install that in another environment, just like you installed Flask in your project’s environment. This makes deploying your project the same as installing any other library, so you’re using all the standard Python tools to manage everything.

Tip: Create a separate virtual environment for each Flask project

Python 3 comes bundled with the venv module to create virtual environments.

$ mkdir flaskr
$ cd flaskr
$ python3 -m venv flaskrenv
$ flaskrenv/bin/activate  

# Be sure to install flask in your new environment   
$ pip install Flask  

Flask dotenv environment variables doc

Rather than setting FLASK_APP each time you open a new terminal, you can use Flask’s dotenv support to set environment variables automatically.

If python-dotenv is installed, running the flask command will set environment variables defined in the files .env and .flaskenv. This can be used to avoid having to set FLASK_APP manually every time you open a new terminal, and to set configuration using environment variables similar to how some deployment services work.

Setting Command (Port) Options

Click is configured to load default values for command options from environment variables. The variables use the pattern FLASK_COMMAND_OPTION. For example, to set the port for the run command, instead of flask run --port 8000:

export FLASK_RUN_PORT=8000
flask run
 * Running on http://127.0.0.1:8000/

Example Flask project layout

/home/user/Projects/flask-tutorial
β”œβ”€β”€ flaskr/
β”‚   β”œβ”€β”€ __init__.py
β”‚   β”œβ”€β”€ db.py
β”‚   β”œβ”€β”€ schema.sql
β”‚   β”œβ”€β”€ auth.py
β”‚   β”œβ”€β”€ blog.py
β”‚   β”œβ”€β”€ templates/
β”‚   β”‚   β”œβ”€β”€ base.html
β”‚   β”‚   β”œβ”€β”€ auth/
β”‚   β”‚   β”‚   β”œβ”€β”€ login.html
β”‚   β”‚   β”‚   └── register.html
β”‚   β”‚   └── blog/
β”‚   β”‚       β”œβ”€β”€ create.html
β”‚   β”‚       β”œβ”€β”€ index.html
β”‚   β”‚       └── update.html
β”‚   └── static/
β”‚       └── style.css
β”œβ”€β”€ tests/
β”‚   β”œβ”€β”€ conftest.py
β”‚   β”œβ”€β”€ data.sql
β”‚   β”œβ”€β”€ test_factory.py
β”‚   β”œβ”€β”€ test_db.py
β”‚   β”œβ”€β”€ test_auth.py
β”‚   └── test_blog.py
β”œβ”€β”€ flaskrenv/
β”œβ”€β”€ setup.py
└── MANIFEST.in  

.gitignore for Flask files

If you’re using version control, the following files that are generated while running your project should be ignored. There may be other files based on the editor you use. In general, ignore files that you didn’t write. For example, with .gitignore:

flaskrenv/

*.pyc
__pycache__/

instance/

.pytest_cache/
.coverage
htmlcov/

dist/
build/
*.egg-info/

Setting up a Flask server

$ pip install Flask  
$ touch hello.py
$ open hello.py

from flask import Flask
app = Flask(__name__)

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

$ FLASK_APP=hello.py flask run  
* Running on http://localhost:5000/  

Opening a Flask shell

To explore the data in your application, you can start an interactive Python shell with the shell command. An application context will be active, and the app instance will be imported.

$ flask shell
Python 3.6.2 (default, Jul 20 2017, 03:52:27)
[GCC 7.1.1 20170630] on linux
App: example
Instance: /home/user/Projects/hello/instance
>>>  

Use shell_context_processor() to add other automatic imports.

Shutting down a Flask server

Shutdown The Simple Server - Flask snippets. Note: Use GET not POST
Stackoverflow: How to stop Flask application without using ctrl-c

from flask import request

def shutdown_server():
    func = request.environ.get('werkzeug.server.shutdown')
    if func is None:
        raise RuntimeError('Not running with the Werkzeug Server')
    func()

# SHUTDOWN (without ctrl-c)
@APP.route('/shutdown', methods=['GET'])
def shutdown():
    shutdown_server()
    return 'Server shutting down...'

# --- Usage ---
# Option 1: Go to /shutdown in the web page path (as in, <host>:<port>/shutdown)

# Option 2: In webpage template add a button  
<a href="{{ url_for('shutdown') }}"><button>Shutdown server</button></a>  

Debug Mode

If you enable debug support the server will reload itself on code changes, and it will also provide you with a helpful debugger if things go wrong.

To enable all development features (including debug mode) you can export the FLASK_ENV environment variable and set it to development before running the server:

$ export FLASK_ENV=development
$ flask run

This does the following things:

  • it activates the debugger
  • it activates the automatic reloader
  • it enables the debug mode on the Flask application.

You can also control debug mode separately from the environment by exporting FLASK_DEBUG=1.

Application Setup with SQLite - Flaskr example

A Flask application is an instance of the Flask class. Everything about the application, such as configuration and URLs, will be registered with this class.

The most straightforward way to create a Flask application is to create a global Flask instance directly at the top of your code.

Instead of creating a Flask instance globally, you will create it inside a function (the top-level init.py file). This function is known as the application factory. Any configuration, registration, and other setup the application needs will happen inside the function, then the application will be returned.

The init.py serves double duty: it will contain the application factory, and it tells Python that the flaskr directory should be treated as a package.

flaskr/__init__.py:

import os

from flask import Flask

# Note: Overwrite SECRET_KEY='dev' with a random value when deploying.  
def create_app(test_config=None):
    # create and configure the app
    app = Flask(__name__, instance_relative_config=True)
    app.config.from_mapping(
        SECRET_KEY='dev',   
        DATABASE=os.path.join(app.instance_path, 'flaskr.sqlite'),
    )

    if test_config is None:
        # load the instance config, if it exists, when not testing
        app.config.from_pyfile('config.py', silent=True)
    else:
        # load the test config if passed in
        app.config.from_mapping(test_config)

    # ensure the instance folder exists
    try:
        os.makedirs(app.instance_path)
    except OSError:
        pass

    # a simple page that says hello
    @app.route('/hello')
    def hello():
        return 'Hello, World!'

    return app

How to generate good secret keys

A secret key should be as random as possible. Your operating system has ways to generate pretty random data based on a cryptographic random generator. Use the following command to quickly generate a value for Flask.secret_key (or SECRET_KEY):

$ python -c 'import os; print(os.urandom(16))'
b'_5#y2L"F4Q8z\n\xec]/'

File uploads with Flask

File uploads - Flask docs
You can handle uploaded files with Flask easily. Just make sure not to forget to set the enctype="multipart/form-data" attribute on your HTML form, otherwise the browser will not transmit your files at all.

Uploaded files are stored in memory or at a temporary location on the filesystem. You can access those files by looking at the files attribute on the request object.

from flask import request

@app.route('/upload', methods=['GET', 'POST'])
def upload_file():
    if request.method == 'POST':
        f = request.files['the_file']
        f.save('/var/www/uploads/uploaded_file.txt')

If you want to use the filename of the client to store the file on the server, pass it through the secure_filename() function.

from flask import request
from werkzeug.utils import secure_filename

@app.route('/upload', methods=['GET', 'POST'])
def upload_file():
    if request.method == 'POST':
        f = request.files['the_file']
        f.save('/var/www/uploads/' + secure_filename(f.filename))

For more details see the Uploading Files patterns section in the Flask docs.

See also, Flask-Uploads functions.

If you need to upload huge files, you may want to look into another solution like rsync.

Define and Access an SQLite Database with Flask

The application will use a SQLite database to store users and posts. Python comes with built-in support for SQLite in the sqlite3 module. docs

flaskr/db.py:

import sqlite3

import click
from flask import current_app, g
from flask.cli import with_appcontext


def get_db():
    if 'db' not in g:
        g.db = sqlite3.connect(
            current_app.config['DATABASE'],
            detect_types=sqlite3.PARSE_DECLTYPES
        )
        g.db.row_factory = sqlite3.Row

    return g.db


def close_db(e=None):
    db = g.pop('db', None)

    if db is not None:
        db.close()

Running a Flask development server docs

Starting with Flask 0.11 there are multiple built-in ways to run a development server. The best one is the flask command line utility but you can also continue using the Flask.run() method.

The flask command line script (Command Line Interface) is strongly recommended for development because it provides a superior reload experience due to how it loads the application.

$ export FLASK_APP=my_application
$ export FLASK_ENV=development
$ flask run  

This enables the development environment, including the interactive debugger and reloader, and then starts the server on http://localhost:5000/.

Test coverage - Yeah, tests!

You should test as you develop.

Writing unit tests for your application lets you check that the code you wrote works the way you expect. Flask provides a test client that simulates requests to the application and returns the response data. docs

Use pytest and coverage to test and measure your code.

pip install pytest coverage  

To measure the code coverage of your tests, use the coverage command to run pytest.

coverage run -m pytest

An HTML report allows you to see which lines were covered in each file:
coverage html
This generates files in the htmlcov directory. Open htmlcov/index.html in your browser to see the report.

Deploy Flaskr to Production

This part of the tutorial assumes you have a server that you want to deploy your application to. It gives an overview of how to create the distribution file and install it. docs

Tutorials

⚠️ **GitHub.com Fallback** ⚠️