Flask is a simple web framework written in Python.
In this article, we’ll look at how to develop simple Python web apps with Flask.
The Request Object
We can get data from the request object.
To get form data, we can write:
from flask import Flask, request app = Flask(__name__) @app.route('/login', methods=['POST', 'GET']) def login(): if request.method == 'POST': if 'username' in request.form and 'password' in request.form: return '%s:%s' % ( request.form['username'], request.form['password'] ) else: return 'Invalid username/password'
We check if
'password' keys are in
request.form has the form data key-value pairs.
If they’re both present when we make the POST request to http://127.0.0.1:5000/login, then we return the
password combined as the response.
Otherwise, we return
‘Invalid username/password’ .
Alternatively, we can write:
from flask import Flask, request app = Flask(__name__) @app.route('/login', methods=['POST', 'GET']) def login(): if request.method == 'POST': username = request.args.get('username', '') password = request.args.get('password', '') if username != '' and password != '': return '%s:%s' % ( username, password ) else: return 'Invalid username/password'
request.args.get to get the value with the given form data key.
The 2nd argument is the default value.
So we can check
password against an empty string instead to see if they have a value or not.
We can accept file uploads with Flask.
For example, we can write:
from flask import Flask, request from werkzeug.utils import secure_filename app = Flask(__name__) @app.route('/upload', methods=['GET', 'POST']) def upload_file(): if request.method == 'POST': f = request.files['the_file'] f.save('./uploads/%s' % (secure_filename(f.filename))) return 'file uploaded'
to add the
We check the
upload_file function for the route.
Then we check if the method of the request is
If it is, then we get the file from
Then we save the file with
f.save and the path to save to.
secure_filename creates an escaped file name.
f.filename has the file name of the file that’s sent with the request.
We can get the cookies from the request with the
For example, we can write:
from flask import Flask, request app = Flask(__name__) @app.route('/') def index(): username = request.cookies.get('username') return username
Then when we add the
Cookie request header with the value
username=foo when we make a GET request to http://127.0.0.1:5000/, then we get the cookie with the key
It should return
username , so that’s what we see in the response body.
Also, we can send cookies with the response.
To do that, we write:
from flask import Flask, make_response, render_template app = Flask(__name__) @app.route('/') def index(): resp = make_response(render_template('index.html')) resp.set_cookie('username', 'the username') return resp
resp.set_cookie with the key and value of the cookie.
Then we return the response.
We can get request data and send cookie responses with Flask.