### Initial Project Directory Setup
Source: https://github.com/pallets/flask/blob/main/docs/tutorial/layout.md
Commands to create the main project directory and navigate into it, preparing for Flask installation.
```none
$ mkdir flask-tutorial
$ cd flask-tutorial
```
--------------------------------
### Initialize and Configure a Flask Application
Source: https://github.com/pallets/flask/blob/main/docs/lifecycle.md
Create a Flask instance and set up initial configuration and routes. All setup must be finished before the server starts handling requests.
```python
from flask import Flask
app = Flask(__name__)
app.config.from_mapping(
SECRET_KEY="dev",
)
app.config.from_prefixed_env()
@app.route("/")
def index():
return "Hello, World!"
```
--------------------------------
### Example Flask Server Output
Source: https://github.com/pallets/flask/blob/main/docs/tutorial/factory.md
This output confirms the Flask development server has started, indicating debug mode is active and providing the local URL to access the application.
```text
* Serving Flask app "flaskr"
* Debug mode: on
* Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
* Restarting with stat
* Debugger is active!
* Debugger PIN: nnn-nnn-nnn
```
--------------------------------
### Install pytest and coverage
Source: https://github.com/pallets/flask/blob/main/docs/tutorial/tests.md
Install the necessary testing and coverage tools using pip.
```none
$ pip install pytest coverage
```
--------------------------------
### Install Flask Package
Source: https://github.com/pallets/flask/blob/main/docs/installation.md
Install the Flask library into the currently activated virtual environment using pip.
```sh
$ pip install Flask
```
--------------------------------
### Install Flask from Source and Flaskr (Main Branch)
Source: https://github.com/pallets/flask/blob/main/examples/tutorial/README.rst
Installs Flask from its parent directory (source) and then Flaskr, typically used when working with the main development branch of Flask.
```bash
$ pip install -e ../..
$ pip install -e .
```
--------------------------------
### Install uWSGI and pyuwsgi
Source: https://github.com/pallets/flask/blob/main/docs/deploying/uwsgi.md
Install the pyuwsgi package for precompiled wheels or the uwsgi package for full SSL support. This process involves creating a virtual environment and installing the application before the server.
```bash
$ cd hello-app
$ python -m venv .venv
$ . .venv/bin/activate
$ pip install . # install your application
$ pip install pyuwsgi
# Alternative for SSL support
$ pip install uwsgi
# Or install pyuwsgi from source
$ pip install --no-binary pyuwsgi pyuwsgi
```
--------------------------------
### Install pytest
Source: https://github.com/pallets/flask/blob/main/docs/testing.md
Command to install the pytest testing framework for Flask application testing.
```bash
$ pip install pytest
```
--------------------------------
### Build and Install Flask Distribution Wheel
Source: https://github.com/pallets/flask/blob/main/docs/tutorial/deploy.md
Commands to package the Flask application into a wheel file using the build tool and install it into a production environment's virtual machine.
```bash
$ pip install build
$ python -m build --wheel
# After copying to server:
$ pip install flaskr-1.0.0-py3-none-any.whl
```
--------------------------------
### Install mod_wsgi and Application
Source: https://github.com/pallets/flask/blob/main/docs/deploying/mod_wsgi.md
Commands to create a virtual environment, install the Flask application, and install the mod_wsgi package. Requires a compiler and Apache development headers.
```bash
$ cd hello-app
$ python -m venv .venv
$ . .venv/bin/activate
$ pip install . # install your application
$ pip install mod_wsgi
```
--------------------------------
### Initialize Database and Run Flaskr Application
Source: https://github.com/pallets/flask/blob/main/examples/tutorial/README.rst
Initializes the Flaskr database and starts the development server with debugging enabled, making the application accessible locally.
```bash
$ flask --app flaskr init-db
$ flask --app flaskr run --debug
```
--------------------------------
### Install Sentry SDK for Flask
Source: https://github.com/pallets/flask/blob/main/docs/errorhandling.md
Install the Sentry SDK with the required Flask dependencies using pip.
```text
$ pip install sentry-sdk[flask]
```
--------------------------------
### Clone and Checkout Flaskr Repository
Source: https://github.com/pallets/flask/blob/main/examples/tutorial/README.rst
Clones the Flask repository and checks out a specific tagged version of the tutorial example, then navigates into the example directory.
```bash
# clone the repository
$ git clone https://github.com/pallets/flask
$ cd flask
# checkout the correct version
$ git tag # shows the tagged versions
$ git checkout latest-tag-found-above
$ cd examples/tutorial
```
--------------------------------
### Install Test Dependencies and Run Pytest
Source: https://github.com/pallets/flask/blob/main/examples/tutorial/README.rst
Installs the necessary testing dependencies for Flaskr and then executes all tests using the pytest framework.
```bash
$ pip install '.[test]'
$ pytest
```
--------------------------------
### Initialize SQLAlchemy engine and session for manual ORM
Source: https://github.com/pallets/flask/blob/main/docs/patterns/sqlalchemy.md
Setup for the database.py module. Defines the engine, metadata, and a scoped session for manual mapping.
```python
from sqlalchemy import create_engine, MetaData
from sqlalchemy.orm import scoped_session, sessionmaker
engine = create_engine('sqlite:////tmp/test.db')
metadata = MetaData()
db_session = scoped_session(sessionmaker(autocommit=False,
autoflush=False,
bind=engine))
def init_db():
metadata.create_all(bind=engine)
```
--------------------------------
### Setup SQLAlchemy engine for SQL abstraction layer
Source: https://github.com/pallets/flask/blob/main/docs/patterns/sqlalchemy.md
Initializes the engine and metadata for direct SQL usage without full ORM mapping.
```python
from sqlalchemy import create_engine, MetaData, Table
engine = create_engine('sqlite:////tmp/test.db')
metadata = MetaData(bind=engine)
```
--------------------------------
### Load Instantiated Flask Configuration Object
Source: https://github.com/pallets/flask/blob/main/docs/config.md
This example shows how to load a configuration class instance, which is necessary when the configuration class contains properties that need to be evaluated.
```python
from configmodule import ProductionConfig
app.config.from_object(ProductionConfig())
```
```python
# Alternatively, import via string:
from werkzeug.utils import import_string
cfg = import_string('configmodule.ProductionConfig')()
app.config.from_object(cfg)
```
--------------------------------
### Install and run custom Flask script
Source: https://github.com/pallets/flask/blob/main/docs/cli.md
Install the application in editable mode to make the custom script available. The script can then be invoked directly without the --app flag.
```text
$ pip install -e .
$ wiki run
```
--------------------------------
### Run Flask Development Server
Source: https://github.com/pallets/flask/blob/main/docs/cli.md
Starts the Flask development server for a specified application. This command replaces the `Flask.run()` method in most cases.
```bash
$ flask --app hello run
```
--------------------------------
### Install gevent and dependencies
Source: https://github.com/pallets/flask/blob/main/docs/deploying/gevent.md
Steps to set up a virtual environment and install gevent along with the Flask application. Requires greenlet version 1.0 or higher.
```bash
$ cd hello-app
$ python -m venv .venv
$ . .venv/bin/activate
$ pip install . # install your application
$ pip install gevent
```
--------------------------------
### Start Flask Development Server
Source: https://github.com/pallets/flask/wiki/Large-app-how-to
Execution command to launch the Flask development server using a custom runner script. This starts the application on the default local host with the reloader enabled for development.
```bash
. env/bin/activate
python run.py
```
--------------------------------
### Create Virtual Environment
Source: https://github.com/pallets/flask/blob/main/docs/installation.md
Create a project directory and initialize a virtual environment named '.venv' within it. This isolates project dependencies from the system Python installation.
```text
$ mkdir myproject
$ cd myproject
$ python3 -m venv .venv
```
```text
> mkdir myproject
> cd myproject
> py -3 -m venv .venv
```
--------------------------------
### Flask Extension with Application Factory Pattern
Source: https://github.com/pallets/flask/blob/main/docs/extensiondev.md
Example showing how to use an extension instance independently of the application, allowing other modules to import and use the extension before the app is created.
```python
hello = HelloExtension()
def create_app():
app = Flask(__name__)
hello.init_app(app)
return app
```
--------------------------------
### Define Class-Based Flask Configurations with Inheritance
Source: https://github.com/pallets/flask/blob/main/docs/config.md
This example shows how to define multiple configurations (e.g., Production, Development, Testing) using Python classes and inheritance for different environments.
```python
class Config(object):
TESTING = False
class ProductionConfig(Config):
DATABASE_URI = 'mysql://user@localhost/foo'
class DevelopmentConfig(Config):
DATABASE_URI = "sqlite:////tmp/foo.db"
class TestingConfig(Config):
DATABASE_URI = 'sqlite:///:memory:'
TESTING = True
```
--------------------------------
### Serve Flask Application with Waitress
Source: https://github.com/pallets/flask/blob/main/docs/tutorial/deploy.md
Installation and execution commands for Waitress, a production-grade WSGI server that supports both Windows and Linux.
```bash
$ pip install waitress
$ waitress-serve --call 'flaskr:create_app'
```
--------------------------------
### Initialize Production Database
Source: https://github.com/pallets/flask/blob/main/docs/tutorial/deploy.md
Command to initialize the database structure on the production server. This is required when the application is installed in a new environment.
```bash
$ flask --app flaskr init-db
```
--------------------------------
### Initialize Database Schema in Python Console
Source: https://github.com/pallets/flask/blob/main/docs/patterns/sqlalchemy.md
Calls the init_db function to create tables based on defined models. This is typically run once during setup.
```pycon
>>> from yourapplication.database import init_db
>>> init_db()
```
--------------------------------
### Load configuration from module and instance file
Source: https://github.com/pallets/flask/blob/main/docs/config.md
Load default settings from a module, then override with configuration from a file in the instance folder if it exists. Use `silent=True` to suppress errors if the instance config file is missing.
```Python
app = Flask(__name__, instance_relative_config=True)
app.config.from_object('yourapplication.default_settings')
app.config.from_pyfile('application.cfg', silent=True)
```
--------------------------------
### Flask File Upload Application Setup
Source: https://github.com/pallets/flask/blob/main/docs/patterns/fileuploads.md
Initialize Flask app with upload folder configuration and allowed file extensions. Required imports include Flask, secure_filename from werkzeug, and os for path handling.
```python
import os
from flask import Flask, flash, request, redirect, url_for
from werkzeug.utils import secure_filename
UPLOAD_FOLDER = '/path/to/the/uploads'
ALLOWED_EXTENSIONS = {'txt', 'pdf', 'png', 'jpg', 'jpeg', 'gif'}
app = Flask(__name__)
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
```
--------------------------------
### Run a Flask application using the CLI
Source: https://github.com/pallets/flask/blob/main/docs/quickstart.md
Use the flask command with the --app option to specify the application entry point and start the development server. This command launches a simple server suitable for testing.
```text
$ flask --app hello run
* Serving Flask app 'hello'
* Running on http://127.0.0.1:5000 (Press CTRL+C to quit)
```
--------------------------------
### Implement Blog Index View
Source: https://github.com/pallets/flask/blob/main/docs/tutorial/blog.md
Fetches all blog posts from the database using a JOIN to include author names and renders the index template.
```python
@bp.route('/')
def index():
db = get_db()
posts = db.execute(
'SELECT p.id, title, body, created, author_id, username'
' FROM post p JOIN user u ON p.author_id = u.id'
' ORDER BY created DESC'
).fetchall()
return render_template('blog/index.html', posts=posts)
```
--------------------------------
### Install Flask-MongoEngine
Source: https://github.com/pallets/flask/blob/main/docs/patterns/mongoengine.md
Command to install the Flask-MongoEngine package via pip
```bash
pip install flask-mongoengine
```
--------------------------------
### Configure Logging with dictConfig
Source: https://github.com/pallets/flask/blob/main/docs/logging.md
Set up logging configuration early in application startup using dictConfig to define formatters, handlers, and log levels. This example creates a configuration similar to Flask's default but applies it to all logs.
```python
from logging.config import dictConfig
dictConfig({
'version': 1,
'formatters': {'default': {
'format': '[%(asctime)s] %(levelname)s in %(module)s: %(message)s',
}},
'handlers': {'wsgi': {
'class': 'logging.StreamHandler',
'stream': 'ext://flask.logging.wsgi_errors_stream',
'formatter': 'default'
}},
'root': {
'level': 'INFO',
'handlers': ['wsgi']
}
})
app = Flask(__name__)
```
--------------------------------
### Create a minimal Flask 'Hello, World!' application
Source: https://github.com/pallets/flask/blob/main/docs/quickstart.md
This snippet defines a basic Flask application that responds with 'Hello, World!' to requests at the root URL. It imports the Flask class, creates an app instance, and uses the @app.route decorator to map the URL to a function.
```python
from flask import Flask
app = Flask(__name__)
@app.route("/")
def hello_world():
return "
Hello, World!
"
```
--------------------------------
### Define the Blog Blueprint
Source: https://github.com/pallets/flask/blob/main/docs/tutorial/blog.md
Initializes the blog blueprint and imports necessary utilities for authentication and database access.
```python
from flask import (
Blueprint, flash, g, redirect, render_template, request, url_for
)
from werkzeug.exceptions import abort
from flaskr.auth import login_required
from flaskr.db import get_db
bp = Blueprint('blog', __name__)
```
--------------------------------
### Retrieve Celery task results from a Flask route in Python
Source: https://github.com/pallets/flask/blob/main/docs/patterns/celery.md
This snippet demonstrates how to create a Flask GET endpoint to fetch the status and result of a previously started Celery task. It uses `celery.result.AsyncResult` to query the task's state, indicating if it's ready, successful, and providing its return value or error if completed. This pattern prevents Flask request workers from being blocked while waiting for long-running tasks.
```python
from celery.result import AsyncResult
@app.get("/result/")
def task_result(id: str) -> dict[str, object]:
result = AsyncResult(id)
return {
"ready": result.ready(),
"successful": result.successful(),
"value": result.result if result.ready() else None
}
```
--------------------------------
### Execute Flask Database Initialization Command
Source: https://github.com/pallets/flask/blob/main/docs/tutorial/database.md
Run this command in your terminal to initialize the database, which will create the `flaskr.sqlite` file in your project's instance folder.
```none
$ flask --app flaskr init-db
Initialized the database.
```
--------------------------------
### Test Flask Application Configuration and Hello Route
Source: https://github.com/pallets/flask/blob/main/docs/tutorial/tests.md
Tests the `create_app` factory for configuration handling and verifies the 'hello' route returns the expected response using the test client.
```python
from flaskr import create_app
def test_config():
assert not create_app().testing
assert create_app({'TESTING': True}).testing
def test_hello(client):
response = client.get('/hello')
assert response.data == b'Hello, World!'
```
--------------------------------
### Install Flaskr in Editable Mode
Source: https://github.com/pallets/flask/blob/main/examples/tutorial/README.rst
Installs the Flaskr application in editable mode within the active virtual environment, allowing for local development changes to be reflected immediately.
```bash
$ pip install -e .
```
--------------------------------
### Install Celery Package
Source: https://github.com/pallets/flask/blob/main/docs/patterns/celery.md
Installs the Celery package from PyPI using pip. This is the first step required before integrating Celery with Flask applications.
```bash
pip install celery
```
--------------------------------
### Full Flask Project Directory Structure
Source: https://github.com/pallets/flask/blob/main/docs/tutorial/layout.md
Illustrates the recommended directory layout for a larger Flask application, including the `flaskr` package, `templates`, `static`, `tests`, and configuration files.
```none
/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
├── .venv/
└── pyproject.toml
```
--------------------------------
### Jinja2 URL Generation for JavaScript Examples
Source: https://github.com/pallets/flask/blob/main/examples/javascript/js_example/templates/base.html
These Jinja2 expressions generate URLs for different JavaScript examples (Fetch, XHR, jQuery) by calling the 'index' endpoint with a 'js' argument.
```jinja2
{{ url_for('index', js='fetch') }}
```
```jinja2
{{ url_for('index', js='xhr') }}
```
```jinja2
{{ url_for('index', js='jquery') }}
```
--------------------------------
### Loading Configuration from Python Files
Source: https://github.com/pallets/flask/blob/main/docs/config.md
Demonstrates how to load Flask configuration from Python modules and environment variables. This pattern allows for separate configuration management across different deployment environments.
```APIDOC
## Configuration Method: Loading from Python Files
### Description
Configuration becomes more useful if you can store it in a separate file, ideally located outside the actual application package. You can deploy your application, then separately configure it for the specific deployment.
### Pattern
```python
app = Flask(__name__)
app.config.from_object('yourapplication.default_settings')
app.config.from_envvar('YOURAPPLICATION_SETTINGS')
```
### Process
1. First loads configuration from the `yourapplication.default_settings` module
2. Overrides values with contents of the file pointed to by `YOURAPPLICATION_SETTINGS` environment variable
### Setting Environment Variables
**Bash:**
```bash
export YOURAPPLICATION_SETTINGS=/path/to/settings.cfg
flask run
```
**Fish:**
```fish
set -x YOURAPPLICATION_SETTINGS /path/to/settings.cfg
flask run
```
**CMD:**
```cmd
set YOURAPPLICATION_SETTINGS=\path\to\settings.cfg
flask run
```
**PowerShell:**
```powershell
$env:YOURAPPLICATION_SETTINGS = "\path\to\settings.cfg"
flask run
```
### Configuration File Format
Configuration files are actual Python files. Only values in uppercase are stored in the config object.
### Example Configuration File
```python
# Example configuration
SECRET_KEY = '192b9bdd22ab9ed4d12e236c78afcb9a393ec15f71bbf5dc987d54727823bcbf'
```
### Important Notes
- Load configuration very early so extensions can access it during startup
- Use uppercase letters for config keys
- See Config object documentation for additional loading methods
```
--------------------------------
### Templating Decorator Usage Examples
Source: https://github.com/pallets/flask/blob/main/docs/patterns/viewdecorators.md
These examples demonstrate how to use the `templated` decorator to simplify template rendering. The decorator automatically renders a template using a dictionary returned by the view function.
```default
@app.route('/')
def index():
return render_template('index.html', value=42)
```
```default
@app.route('/')
@templated('index.html')
def index():
return dict(value=42)
```
```default
@app.route('/')
@templated()
def index():
return dict(value=42)
```
--------------------------------
### Initialize Database and Register CLI Command
Source: https://github.com/pallets/flask/blob/main/docs/tutorial/database.md
Loads and executes the SQL schema file to initialize the database, registers a click CLI command for database initialization, and sets up a custom converter for timestamp values. The init_db() function reads schema.sql relative to the Flask package.
```python
def init_db():
db = get_db()
with current_app.open_resource('schema.sql') as f:
db.executescript(f.read().decode('utf8'))
@click.command('init-db')
def init_db_command():
"""Clear the existing data and create new tables."""
init_db()
click.echo('Initialized the database.')
sqlite3.register_converter(
"timestamp", lambda v: datetime.fromisoformat(v.decode())
)
```
--------------------------------
### Start mod_wsgi-express Server
Source: https://github.com/pallets/flask/blob/main/docs/deploying/mod_wsgi.md
Command to start the mod_wsgi-express server pointing to the WSGI script. The --processes option specifies the number of worker processes to run.
```bash
$ mod_wsgi-express start-server wsgi.py --processes 4
```
--------------------------------
### pyproject.toml configuration for Flask package
Source: https://github.com/pallets/flask/blob/main/docs/patterns/packages.md
Configuration file for a Flask application package. Place this file next to the inner application folder and install with pip install -e . to make the application importable.
```toml
[project]
name = "yourapplication"
dependencies = [
"flask",
]
[build-system]
requires = ["flit_core<4"]
build-backend = "flit_core.buildapi"
```
--------------------------------
### Fetch GET request with JSON response
Source: https://github.com/pallets/flask/blob/main/docs/patterns/javascript.md
Retrieve JSON data using fetch with default GET method and parse the response. The room_url is generated server-side using Flask's url_for.
```javascript
const room_url = {{ url_for("room_detail", id=room.id)|tojson }}
fetch(room_url)
.then(response => response.json())
.then(data => {
// data is a parsed JSON object
})
```
--------------------------------
### Make HTTP GET request with test client
Source: https://github.com/pallets/flask/blob/main/docs/testing.md
Use the test client to make a GET request to a route and assert on the response data. The response object has properties like data (bytes) and text (string in Werkzeug 2.1+).
```python
def test_request_example(client):
response = client.get("/posts")
assert b"Hello, World!
" in response.data
```
--------------------------------
### Initialize Flask Application with SQLAlchemy and Blueprints
Source: https://github.com/pallets/flask/wiki/Large-app-how-to
This script configures the main Flask app instance, initializes SQLAlchemy, and registers blueprints for modular routing. It includes a utility function to securely load a secret key from the instance folder and defines a custom 404 error handler.
```python
import os
import sys
from flask import Flask, render_template
from flask.ext.sqlalchemy import SQLAlchemy
app = Flask(__name__)
app.config.from_object('config')
db = SQLAlchemy(app)
def install_secret_key(app, filename='secret_key'):
"""Configure the SECRET_KEY from a file\n in the instance directory.\n\n If the file does not exist, print instructions\n to create it from a shell with a random key,\n then exit.\n """
filename = os.path.join(app.instance_path, filename)
try:
app.config['SECRET_KEY'] = open(filename, 'rb').read()
except IOError:
print('Error: No secret key. Create it with:')
full_path = os.path.dirname(filename)
if not os.path.isdir(full_path):
print('mkdir -p {filename}'.format(filename=full_path))
print('head -c 24 /dev/urandom > {filename}'.format(filename=filename))
sys.exit(1)
if not app.config['DEBUG']:
install_secret_key(app)
@app.errorhandler(404)
def not_found(error):
return render_template('404.html'), 404
from app.users.views import mod as usersModule
app.register_blueprint(usersModule)
```
--------------------------------
### Check for missing python-dotenv
Source: https://github.com/pallets/flask/blob/main/docs/cli.md
Flask displays this message when .env files are present but python-dotenv is not installed.
```bash
$ flask run
* Tip: There are .env files present. Do "pip install python-dotenv" to use them.
```
--------------------------------
### Create a Basic Flask Application
Source: https://github.com/pallets/flask/blob/main/README.md
This Python script initializes a Flask application instance and defines a route for the root URL. When accessed, the server responds with a simple 'Hello, World!' string.
```python
# save this as app.py
from flask import Flask
app = Flask(__name__)
@app.route("/")
def hello():
return "Hello, World!"
```
--------------------------------
### Flask CLI command with custom group
Source: https://github.com/pallets/flask/blob/main/docs/cli.md
Example invocation when a custom group name is specified for blueprint commands.
```text
$ flask other create alice
```
--------------------------------
### Flask CLI command without group nesting
Source: https://github.com/pallets/flask/blob/main/docs/cli.md
Example invocation when blueprint commands are merged directly to the application level.
```text
$ flask create alice
```
--------------------------------
### Define configuration values in a Python file
Source: https://github.com/pallets/flask/blob/main/docs/config.md
Example of a configuration file where only uppercase variables are stored in the Flask config object.
```python
# Example configuration
SECRET_KEY = '192b9bdd22ab9ed4d12e236c78afcb9a393ec15f71bbf5dc987d54727823bcbf'
```
--------------------------------
### Run Flask application factory with keyword arguments
Source: https://github.com/pallets/flask/blob/main/docs/patterns/appfactories.md
This command-line example demonstrates how to pass keyword arguments to an application factory function directly from the command line. This allows for dynamic configuration or behavior modification of the Flask application during startup.
```text
$ flask --app 'hello:create_app(local_auth=True)' run
```
--------------------------------
### Activate Virtual Environment
Source: https://github.com/pallets/flask/blob/main/docs/installation.md
Activate the previously created virtual environment to ensure all subsequent package installations are isolated to the current project.
```text
$ . .venv/bin/activate
```
```text
> .venv\Scripts\activate
```
--------------------------------
### Create and Activate Virtual Environment (Linux/macOS)
Source: https://github.com/pallets/flask/blob/main/examples/tutorial/README.rst
Creates a Python virtual environment named '.venv' and activates it on Unix-like operating systems.
```bash
$ python3 -m venv .venv
$ . .venv/bin/activate
```
--------------------------------
### Flask CLI command with blueprint group
Source: https://github.com/pallets/flask/blob/main/docs/cli.md
Example invocation of a blueprint CLI command. The command is nested under the blueprint group name.
```text
$ flask students create alice
```
--------------------------------
### GET /stories/
Source: https://github.com/pallets/flask/blob/main/docs/views.md
Retrieve a list of all stories. This endpoint uses the GroupAPI class to fetch all story records from the database and return them as JSON.
```APIDOC
## GET /stories/
### Description
List all stories in the system.
### Method
GET
### Endpoint
/stories/
### Response
#### Success Response (200)
- **items** (array) - Array of story objects
- **id** (integer) - Story ID
- **title** (string) - Story title
- **content** (string) - Story content
#### Response Example
[
{
"id": 1,
"title": "First Story",
"content": "Once upon a time..."
},
{
"id": 2,
"title": "Second Story",
"content": "In a galaxy far away..."
}
]
```
--------------------------------
### Initialize and Configure a Flask Extension
Source: https://github.com/pallets/flask/blob/main/docs/extensions.md
Extensions generally pull configuration from app.config and are initialized by passing the application instance to the init_app method.
```python
from flask_foo import Foo
foo = Foo()
app = Flask(__name__)
app.config.update(
FOO_BAR='baz',
FOO_SPAM='eggs',
)
foo.init_app(app)
```
--------------------------------
### Run the Flask Development Server
Source: https://github.com/pallets/flask/blob/main/README.md
Use the Flask command-line interface to start the built-in development server. This allows you to test the application locally on the default port 5000.
```bash
flask run
```
--------------------------------
### GET /users/
Source: https://github.com/pallets/flask/blob/main/docs/views.md
Retrieve a list of all users. This endpoint uses the GroupAPI class to fetch all user records from the database and return them as JSON.
```APIDOC
## GET /users/
### Description
List all users in the system.
### Method
GET
### Endpoint
/users/
### Response
#### Success Response (200)
- **items** (array) - Array of user objects
- **id** (integer) - User ID
- **name** (string) - User name
- **email** (string) - User email
#### Response Example
[
{
"id": 1,
"name": "John Doe",
"email": "john@example.com"
},
{
"id": 2,
"name": "Jane Smith",
"email": "jane@example.com"
}
]
```
--------------------------------
### Calling context processor functions in Jinja templates
Source: https://github.com/pallets/flask/blob/main/docs/templating.md
Example of how to invoke a function that has been made available via a context processor within a template.
```jinja
{{ format_price(0.33) }}
```
--------------------------------
### Set Basic Flask Configuration Environment Variables
Source: https://github.com/pallets/flask/blob/main/docs/config.md
Examples of setting simple Flask configuration environment variables in different shells before running the Flask application. Flask's `from_prefixed_env()` will load these.
```text
$ export FLASK_SECRET_KEY="5f352379324c22463451387a0aec5d2f"
$ export FLASK_MAIL_ENABLED=false
$ flask run
* Running on http://127.0.0.1:5000/
```
```text
$ set -x FLASK_SECRET_KEY "5f352379324c22463451387a0aec5d2f"
$ set -x FLASK_MAIL_ENABLED false
$ flask run
* Running on http://127.0.0.1:5000/
```
```text
> set FLASK_SECRET_KEY="5f352379324c22463451387a0aec5d2f"
> set FLASK_MAIL_ENABLED=false
> flask run
* Running on http://127.0.0.1:5000/
```
```text
> $env:FLASK_SECRET_KEY = "5f352379324c22463451387a0aec5d2f"
> $env:FLASK_MAIL_ENABLED = "false"
> flask run
* Running on http://127.0.0.1:5000/
```