Python
  • index
  • Basic - 1
  • Basic - 2
  • SQLAlchemy
  • Decorator
  • @property
  • __dict__
  • pathlib
  • class
  • flask
  • Jupyter Notebook
  • PyQt
  • UD - FLASK - PY Basic
  • UD - FLASK - REST
  • UD - FLASK - vanilla SQL
  • UD - FLASK - SQLAlchemy
  • UD - FLASK - JWT
  • UD - FLASK - Serialization
Powered by GitBook
On this page
  • 1. Application Factory
  • 2. DB
  • Blueprint

Was this helpful?

flask

1. Application Factory

  1. configuration, registration, and setups

  2. return the application

### my_project/__init__.py
import os
from flask import Flask


def create_app(test_config=None):
    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:
        app.config.from_pyfile('config.py', silent=True) # load the instance config, if it exists, when not testing
    else:
        app.config.from_mapping(test_config) # load the test config if passed in

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

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


    from . import db
    db.init_app(app)


    return app

instance_relative_config=True = config files @ instance/

instance_path needs to be created manually

2. DB

### 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(


def init_db():
    db = get_db()

    with current_app.open_resource('schema.sql') as f: # opens a file relative to the flaskr package
        db.executescript(f.read().decode('utf8'))


@click.command('init-db') # defines a command line command
@with_appcontext
def init_db_command():
    """Clear the existing data and create new tables."""
    init_db()
    click.echo('Initialized the database.')


def init_app(app):
    app.teardown_appcontext(close_db) # call when cleaning up after returning the response.
    app.cli.add_command(init_db_command) # adds a new command

g

  1. a special object which is unique for each request.

  2. store data accessed by multiple functions during the request.

  3. connection is reused instead of creating a new connection.

current_app

  1. a special object which is the Flask application handling the request

Blueprint

Blueprint = organize a group of related views and other code.

PreviousclassNextJupyter Notebook

Last updated 5 years ago

Was this helpful?