Basic Application Structure
A Complete Application
#Initialization
from flask import Flask
app = Flask(__name__)
#Routes and View Functions
@app.route('/')
def index():
return '<h1>Hello World!</h1>'
@app.route('/user/<name>')
def user(name):
return '<h1>Hello, %s!</h1>' % name
#Server Startup
if __name__ == '__main__':
app.run(debug=True)
python hello.py
The Request-Response Cycle
Create another git branch
git branch ch02
Application and Request Contexts
from flask import request
@app.route('/')
def index():
user_agent = request.headers.get('User-Agent')
return '<p>Your browser is %s</p>' % user_agent
Flask context globals:
current_app
Application context The application instance for the active application.g
Application context An object that the application can use for temporary storage during the handling of a request. This variable is reset with each request.request
Request context The request object, which encapsulates the contents of a HTTP request sent by the client.session
Request context The user session, a dictionary that the application can use to store values that are“remembered” between requests.
>>> from hello import app
>>> from flask import current_app
>>> current_app.name
Traceback (most recent call last):
...
RuntimeError: working outside of application context
>>> app_ctx = app.app_context()
>>> app_ctx.push()
>>> current_app.name
'hello'
>>> app_ctx.pop()
Request Dispatching
(venv) $ python
>>> from hello import app
>>> app.url_map
Map([<Rule '/' (HEAD, OPTIONS, GET) -> index>,
<Rule '/static/<filename>' (HEAD, OPTIONS, GET) -> static>,
<Rule '/user/<name>' (HEAD, OPTIONS, GET) -> user>])
Request Hooks
before_first_request
Register a function to run before the first request ishandled.before_request
Register a function to run before each request.after_request
Register a function to run after each request, if no unhandled exceptions occurred.teardown_request
Register a function to run after each request, even if unhandled exceptions occurred.
Responses
When a view function needs to respond with a different status code, it can add the numeric code as a second return value after the response text. For example, the following view function returns a 400 status code, the code for a bad request error:
@app.route('/')
def index():
return '<h1>Bad Request</h1>', 400
from flask import make_response
@app.route('/')
def index():
response = make_response('<h1>This document carries a cookie!</h1>')
response.set_cookie('answer', '42')
return response
redirect
@app.route('/')
def index():
return redirect('http://www.example.com')
abort
from flask import abort
@app.route('/user/<id>')
def get_user(id):
user = load_user(id)
if not user:
abort(404)
return '<h1>Hello, %s</h1>' % user.name
Flask Extensions
Command-Line Options with Flask-Script
(venv) $ pip install flask-script
from flask.ext.script import Manager
manager = Manager(app)
# ...
if __name__ == '__main__':
manager.run()
(venv) $ python hello.py runserver --help
(venv) $ python hello.py runserver --host 0.0.0.0
* Running on http://0.0.0.0:5000/
* Restarting with reloader