Categories
Flask

Python Web Development with Flask — Request and Response

Spread the love

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 'username' and 'password' keys are in request.form .

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 username and 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'

We call request.args.get to get the value with the given form data key.

The 2nd argument is the default value.

So we can check username and password against an empty string instead to see if they have a value or not.

File Uploads

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 upload route.

We check the upload_file function for the route.

Then we check if the method of the request is 'POST' .

If it is, then we get the file from request.files .

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.

Cookies

We can get the cookies from the request with the request.cookies.get method.

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 username with request.cookies.get .

It should return 'foo' for 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

We call resp.set_cookie with the key and value of the cookie.

Then we return the response.

Conclusion

We can get request data and send cookie responses with Flask.

Leave a Reply

Your email address will not be published. Required fields are marked *