URL Build and Static Files
#!/user/bin/python3
from flask import Flask, url_for
app = Flask(__name__)
@app.route('/')
def index():
return 'index'
@app.route('/login')
def login():
return 'login'
@app.route('/user/<username>')
def profile(username):
return '{}\'s profile'.format(username)
@app.route('/static/<cssname>')
def stytle(cssname):
return 'css'
with app.test_request_context():
print(url_for('index'))
print(url_for('login'))
print(url_for('login', next='/'))
print(url_for('profile', username='Jhon Doe'))
print(url_for('static', filename='style.css'))
'''
python3 **.py
/
/login
/login?next=/
/user/John%20Doe
/static/style.css
'''
HTTP Methods
#!/usr/bin/python3
# By default, a route only answer to GET requests,
from flask import request
@app.route('/login', methods=['GET', 'POST'])
def login():
if request.method = 'POST':
return do_the_login()
else:
return show_the_login_form()
'''
If GET is present, Flask automatically adds support for the HEAD method and handles HEAD requests
'''
Rendering Templates
from flask import render_template
from flask import Flask
app = Flask(__name__)
@app.route('/hello/')
@app.route('/hello/<name>')
def hello(name=None):
return render_template('hello.html', name=name)
Case 1: a module:
/application.py
/templates
/hello.html
Case 2: a package:
/application
/__init__.py
/templates
/hello.html
<!doctype html>
<title>hello from flask</title>
{% if name %}
<h1>hello {{ name }}!</h1>
{% else %}
<h1>hello world!</h1>
{% endif %}
Markup
. If you can trust a variable and you know that it will be safe HTML (for example because it came from a module that converts wiki markup to HTML) you can mark it as safe by using the Markup class or by using the |safe filter in the template. Head over to the Jinja 2
>>> from flask import Markup
>>> Markup('<strong>Hello %s!</strong>') % '<blink>hacker</blink>'
Markup(u'<strong>Hello <blink>hacker</blink>!</strong>')
>>> Markup.escape('<blink>hacker</blink>')
Markup(u'<blink>hacker</blink>')
>>> Markup('<em>Marked up</em> » HTML').striptags()
u'Marked up \xbb HTML'
Accessing Request Data
from flask import request, Flask
app = Flask(__name__)
with app.test_request_context('/hello', method='POST'):
# now you can do something with the request until
# end of the with block such as basic assertions:
assert request.path == '/hello'
assert request.method == 'POST'
# with app.test_request_context():
# assert request.method == "POST"
The Request Object
from flask import request, Flask
app = Flask(__name__)
@app.route('/login', methods=['POST', 'GET'])
def login():
error = None
if request.method == 'POST':
if valid_login(request.form['username'],
request.form['password']):
return log_the_user_in(request.form['username'])
else:
error = 'Invalid username/password'
# the code below is executed if the request method
# was GET or credentials were invalid
return render_template('login.html', error=error)
'''
to access parameters submitted in the URL (?key=value) you can use the args attribute:
searchword = request.args.get('key', '')
'''
File Uploads
from flask import request, Flask
app = Falsk(__name__)
@app.route('/upload', methods=['GET', 'POST'])
def upload_file():
if request.method == 'POST':
f = request.files['the_file']
f.save('/var/www/uploads/upload_file.txt')
...
@app.route('/upload', methods=['GET', 'POST'])
def upload_file():
if request.method == 'POST':
f = request.files['the_file']
f.save('var/www/uploads/'+ secure_filename(f.filename))
...
'''
You can handle uploaded files with Flask easily. Just make sure not to forget to set the enctype="multipart/form-data" attribute on your HTML form, otherwise the browser will not transmit your files at all.
'''
Redirects and Errors
from flask import abort, redirect, url_for, Flask, render_template
app = Flask(__name__)
@app.route('/')
def index():
return redirect(url_for('login'))
@app.route('/login')
def login():
abort(401)
this_is_never_executed()
# f you want to customize the error page, you can use the errorhandler() decorator:
@app.errorhandler(404)
def page_not_found(error):
return render_template('page_not_found.html'), 404
Sessions
from flask import Flask, session, redirect, url_for, escape, request
app = Flask(__name__)
# Set the secret key to some random bytes. Keep this really secret!
app.secret_key = b'_5#y2L"F4Q8z\n\xec]/'
@app.route('/')
def index():
if 'username' in session:
return 'Logged in as %s' % escape(session['username'])
return 'You are not logged in'
@app.route('/login', methods=['GET', 'POST'])
def login():
if request.method == 'POST':
session['username'] = request.form['username']
return redirect(url_for('index'))
return '''
<form method="post">
<p><input type=text name=username>
<p><input type=submit value=Login>
</form>
'''
@app.route('/logout')
def logout():
# remove the username from the session if it's there
session.pop('username', None)
return redirect(url_for('index'))
'''
quickly generate a value for Flask.secret_key (or SECRET_KEY):
$ python -c 'import os; print(os.urandom(16))'
b'_5#y2L"F4Q8z\n\xec]/'
'''
Message Flashing
To flash a message use the flash() method, to get hold of the messages you can use get_flashed_messages() which is also available in the templates.
Check out the Message Flashing for a full example.
Logging
Sometimes you might be in a situation where you deal with data that should be correct, but actually is not. For example you may have some client-side code that sends an HTTP request to the server but it’s obviously malformed. This might be caused by a user tampering with the data, or the client code failing. Most of the time it’s okay to reply with 400 Bad Request in that situation, but sometimes that won’t do and the code has to continue working.
You may still want to log that something fishy happened. This is where loggers come in handy. As of Flask 0.3 a logger is preconfigured for you to use.
Here are some example log calls:
app.logger.debug('A value for debugging')
app.logger.warning('A warning occurred (%d apples)', 42)
app.logger.error('An error occurred')
Hooking in WSGI Middlewares
If you want to add a WSGI middleware to your application you can wrap the internal WSGI application. For example if you want to use one of the middlewares from the Werkzeug package to work around bugs in lighttpd, you can do it like this:
from werkzeug.contrib.fixers import LighttpdCGIRootFix
app.wsgi_app = LighttpdCGIRootFix(app.wsgi_app)
Using Flask Extensions
Extensions are packages that help you accomplish common tasks. For example, Flask-SQLAlchemy provides SQLAlchemy support that makes it simple and easy to use with Flask.
Deploying to a Web Server
Ready to deploy your new Flask app? Go to
Deployment Options`