Python Web - Flask

Card Puncher Data Processing

About

Flask is web framework to create web application.

The idea of Flask is to build a good foundation for all applications. Everything else is up to you or extensions.

Flask is just not designed for large applications or asynchronous servers. Flask wants to make it quick and easy to write a traditional web application. See Thread local

Flask is just the paste that glues Werkzeug and Jinja2 together.

Architecture

Application

For Flask a web application is:

  • based on WSGI with the werkzeug library
  • that have one central callable object that implements the actual application. (In Flask this is an instance of the Flask class.)

Each Flask application has to:

  • create an instance of the Flask Class itself
  • and pass it the name of:
    • the package (a folder with an init.py file inside)
    • the module (just a .py file).

The name of the module or package helps to locate the application location.

The flask object implements a WSGI application. It acts as a central registry for the view functions, the URL rules, template configuration and much more.

create a Flask instance:

  • for a module
from flask import Flask
app = Flask(__name__)
  • or in the __init__.py file of the package
from flask import Flask
app = Flask(__name__)
  • or in a module in a package
from flask import Flask
app = Flask('yourapplication')
# or
app = Flask(__name__.split('.')[0])

With Python reflection, Flask can then access the package to figure out where the templates and static files are stored (see open_resource()).

You don't need to import an app instance when

Config

The Flask application object store global confi in its config attribute.

  • Set
app.config.from_pyfile(config_filename)
  • Use: look up the name of a template in the config
current_app.config['INDEX_TEMPLATE']

See factory

Project Structure

project structure

By convention, templates and static files are stored in subdirectories within the application’s Python source tree, with the names templates and static respectively.

Features

Context

Flask uses thread local objects (context local objects in fact, they support greenlet contexts as well) for request, session and an extra object you can put your own things on (g) http://flask.pocoo.org/docs/1.0/api/#flask.g

http://flask.pocoo.org/docs/1.0/appcontext/

Typically, an application context will have the same lifetime as a request.

View functions, error handlers, and other functions that run during a request will have access to current_app. If you try to access current_app, or anything that uses it, outside an application context, you’ll get this error message:

def create_app():
    app = Flask(__name__)

    # everything that runs in the block will have access to current_app.
    with app.app_context():
        init_db()

    return app

Thread: The context local proxies depend on context which in Flask is defined as being either a thread, process or greenlet.

Components

Flask itself just bridges to Werkzeug to implement a proper WSGI application and to Jinja2 to handle templating. It also binds to a few common standard library packages such as logging. Everything else is up for extensions.

These distributions will be installed automatically when installing Flask.

  • Werkzeug implements WSGI, the standard Python interface between applications and servers.
  • Jinja is a template language that renders the pages your application serves.
  • MarkupSafe comes with Jinja. It escapes untrusted input when rendering templates to avoid injection attacks.
  • ItsDangerous securely signs data to ensure its integrity. This is used to protect Flask’s session cookie.
  • Click is a framework for writing command line applications. It provides the flask command and allows adding custom management commands.

Optional:

Blueprint

The basic concept of blueprints is that they record operations to execute when registered on an application. Flask associates view functions with blueprints when dispatching requests and generating URLs from one endpoint to another.

Modular Applications

  • Factor an application into a set of blueprints.
  • Register a blueprint multiple times on an application with different URL rules.
  • Provide template filters, static files, templates, and other utilities through blueprints.

A Blueprint object works similarly to a Flask application object, but it is not actually an application. A blueprint does not have to implement applications or view functions. A Blueprint is a set of operations which can be registered on an application, even multiple times. Like for regular applications, blueprints are considered to be contained in a folder.

Blueprint share application config, and can change an application object as necessary with being registered. The downside is that you cannot unregister a blueprint once an application was created without having to destroy the whole application object.

Example:

from flask import Blueprint, render_template, abort
from jinja2 import TemplateNotFound

simple_page = Blueprint('simple_page', __name__, template_folder='templates')

@simple_page.route('/', defaults={'page': 'index'})
@simple_page.route('/<page>')
def show(page):
    try:
        return render_template('pages/%s.html' % page)
    except TemplateNotFound:
        abort(404)
  • Registration
from flask import Flask
from yourapplication.simple_page import simple_page

app = Flask(__name__)
app.register_blueprint(simple_page)

If you check the rules registered on the application, you will find these:

[<Rule '/static/<filename>' (HEAD, OPTIONS, GET) -> static>,
 <Rule '/<page>' (HEAD, OPTIONS, GET) -> simple_page.show>,
 <Rule '/' (HEAD, OPTIONS, GET) -> simple_page.show>]

Management

Init

Factory

http://flask.pocoo.org/docs/1.0/patterns/appfactories/

Flask will automatically detect the application factory (create_app or make_app) in myapp.

The id of the application is the signature of the function.

def create_app(config_filename):
    app = Flask(__name__)
    app.config.from_pyfile(config_filename)

    from yourapplication.model import db
    db.init_app(app)

    from yourapplication.views.admin import admin
    from yourapplication.views.frontend import frontend
    app.register_blueprint(admin)
    app.register_blueprint(frontend)

    return app

Start

export FLASK_APP=hello.py
flask run
# or
python -m flask run
# or 
export FLASK_APP="myapp:create_app('dev')"
flask run

Public Server

If you have the debugger disabled or trust the users on your network, you can make the server publicly available simply by adding –host=0.0.0.0 to the command line:

Reload

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.

Port

export FLASK_RUN_PORT=8000

Development

export FLASK_ENV=development

Debug

Debug Mode

You are in a debug mode if:

  • you have started flask in development mode
  • if the environment variable FLASK_DEBUG is set to 1

http://flask.pocoo.org/docs/1.0/quickstart/#debug-mode

In debug mode, the logger’s level will be set to DEBUG.

Debug Idea

To use the debugger on IDEA, you need to disable the debugger to be able to use the internal debugger. Doc

Example:

  • The run configuration

Flask Idea Nodebug

  • Then start a debug session
wd\env\Scripts\python.exe C:\Users\gerard\.IdeaIC2018.2\config\plugins\python-ce\helpers\pydev\pydevd.py --module --multiproc --qt-support=auto --client 127.0.0.1 --port 10531 --file flask run
pydev debugger: process 26360 is connecting

Connected to pydev debugger (build 182.4505.22)
 * Serving Flask app "chatbot:create_app('dev')"
 * Environment: development
 * Debug mode: off
[2019-01-28 15:34:25,547] INFO in _internal:  * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)

  • Set a breakpoint and hit the page that you want to debug.

Flask Idea Breakpoint

Debugger

More see werkzeug debugger

Logging

http://flask.pocoo.org/docs/dev/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.

https://docs.python.org/3/library/logging.config.html#logging.config.dictConfig

Documentation / Reference





Discover More
Web - (Hot|Live) (Edit|Reload) - Auto File Sync

Live reloading (ie File sync) in the web means that the Browser automatically update/refresh the HTML page when you change files in your project (HTML, CSS, images, ...) Reload the page at interval:...
Web - Framework

This framework provides an http server with at minimal a routing capability and adds above other features such as: templating authentication Framework Description Languages Vertx The reactive...



Share this page:
Follow us:
Task Runner