This document explains how to create and configure routes in Flask, return responses, manage application configuration, and structure Flask projects for maintainability. It covers decorators, JSON responses, environment variables and best practices for organizing code.
This document details how to create and configure routes in Flask, return responses, manage configuration, and structure projects for maintainability. It covers decorators, JSON responses, environment variables, and best practices for organizing Flask code.
Routes in Flask define how URLs are handled by the application. Each route is associated with a function that returns a response to the client.
app.py).Flask class and instantiate the app:1from flask import Flask
2app = Flask(__name__)
@app.route decorator:1@app.route('/')
2def hello_world():
3 return '<b>my first Flask application in action!</b>'
1export FLASK_APP=app.py
2export FLASK_ENV=development
3flask run
http://localhost:5000 by default.--app and --debug flags for configuration and development mode.jsonify:1from flask import jsonify
2@app.route('/json')
3def json_example():
4 return jsonify(message='Hello, JSON!')
application/json.Set configuration via environment variables, the app.config object, or external files.
Common options:
ENV: Environment type (development/production)DEBUG: Enables debug modeTESTING: Enables testing modeSECRET_KEY: Signs session cookiesSESSION_COOKIE_NAME: Name of session cookieSERVER_NAME: Host and port bindingJSONIFY: Defaults to application/jsonLoad configuration from a file using app.config.from_file().
Example structure:
1myapp/
2 app.py
3 config.py
4 static/
5 templates/
6 tests/
7 venv/
Flask routes map URLs to functions, enabling flexible response handling. Proper configuration and project structure improve maintainability and scalability of Flask applications.
(1) Routes map URLs to functions that return responses to the client.
(1) Setting FLASK_ENV to ‘development’ enables debug mode and auto-reload.
(3) Returning a string with HTML tags does not produce a JSON response.
(4) Flask supports configuration via environment variables, app.config, and external files.
| Option | Purpose |
|---|---|
| A. DEBUG | 1. Signs the session cookie |
| B. SECRET_KEY | 2. Enables debug mode |
| C. SERVER_NAME | 3. Binds the host and port |
A-2, B-1, C-3.
(1) A well-structured project is easier to maintain and scale.
The @app.route decorator in Flask is used to map a URL to a function that returns a response.
True. The @app.route decorator defines the URL pattern and associates it with a function.