Parts of a Flask Web App

From TRCCompSci - AQA Computer Science
Revision as of 16:51, 10 April 2019 by Admin (talk | contribs) (Handling HTML Forms)
Jump to: navigation, search

@app.route

This defines where a particular path in the url relates too:

@app.route("/")
def hello():
    return "Hello World!"

When the app server is running, visiting the root will produce the message 'Hello World!'. The code below will also display this if you visit '/home' on the app server:

@app.route("/")
@app.route("/home")
def hello():
    return "Hello World!"

Parameters

The example below will just display the message:

@app.route("/")
def hello():
    return "Hello World!"

You can also use parameters:

@app.route("/<name>")
def hello(name):
    return "Hello "+name

Using this method the parameters are passed as strings, and you may need to convert them. In this example the URL '/Wayne' will display the message 'Hello Wayne'.

url_for

If you look at this example:

@app.route("/home")
def home():
    return "test"
 
@app.route("/hello")
def hello():
    return "Hello World!"

it creates 2 paths, one for '/hello' (runs 'def hello()') and one for '/home' (runs 'def home()'). url_for will accept the name of the method (ie def ....) and return the route.

so:

url_for('hello')

will return:

/hello

Handling HTML Forms

You will need to add request to the Flask import:

from flask import Flask, request

The code below is an example of using html form elements:

@app.route('/login', methods=['GET', 'POST'])
def login():
    if request.method == 'POST':
        if (request.form['username']=="wayne") and request.form['password']=="pass":
                return redirect(url_for('home')) # will need to add redirect to the Flask import
    return '''
        <form method="post"><p>
        Username: <input type=text name=username><p>
        Password: <input type=password name=password><p>
        <input type=submit value=Login>
        </form>
        '''

The route must include', methods=['GET','POST']' this will allow it to accept data from an html form. This will use either, get (via the url) or post (via the http header).

Within the method you can check the request method (request.method=='POST'). You can then access data from the form using request.form['...'], the text in the square brackets needs to match the name of the form element from the html.

Using Sessions

Templates