> For the complete documentation index, see [llms.txt](https://huang-jason.gitbook.io/python/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://huang-jason.gitbook.io/python/flask.md).

# flask

## 1. Application Factory

1. configuration, registration, and setups
2. return the application

```python
### 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

```python
### 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.&#x20;
2. store data accessed by multiple functions during the request.&#x20;
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.


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://huang-jason.gitbook.io/python/flask.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
