I719 Fundamentals of Python/lecture4v2

From ICO wiki
Jump to navigationJump to search

Lecture 4

introduction to website development with flask.

NOTE: you do not need to know this material for the test or to know python in general. It is only for showing how to make a website easily.

Task 0

copy and paste the example from flask's homepage http://flask.pocoo.org/

then run it, and go the the url printed in your terminal

Query strings and form data

The form data and query string data are acessible from a special request object. This request object is imported, and only has data when it is used inside of a view function.

the data for query strings and forms is in a dictionary like object.

Task 1

Show the bitcoin price in Euro on a webpage

import requests
from flask import Flask


def get_btc_price():
    r = requests.get('https://api.coindesk.com/v1/bpi/currentprice.json')
    data = r.json()
    price = data['bpi']['EUR']['rate']
    return price


app = Flask(__name__)
app.config['DEBUG'] = True


@app.route("/")
def hello():
    return '{} €'.format(get_btc_price())

if __name__ == "__main__":
    app.run()

HTML Templates

To use an HTML template with the default flask configuration, make a directory 'templates' in the same directory as your flask script. you can then put html template in here.

for a script ./app.py to use a template ./templates/index.html, import render_template from flask: from flask import Flask, render_template

and use the line in your view function return render_template('index.html')

variables in jinja2 templates look like Template:Variable name, and can be substituted in the render_template function

return render_template('index.html', variable_name='value')

Flask uses the Jinja2 templating engine. see their documentation for more information

Task 2

Make a form that asks for name and age, and displays:

'Hi $NAME, you are $AGE years old'

using a post request

app.py

from flask import Flask, render_template, request


app = Flask(__name__)
app.config['DEBUG'] = True

@app.route("/", methods=['POST', 'GET'])
def hello():
    name = request.form.get('name', '')
    age = request.form.get('age', '')
    if name and age:
        return render_template('index.html', name=name, age=age)
    else:
        return render_template('index.html', name=name, age=age), 400

if __name__ == "__main__":
    app.run(port=5000)

templates/index.html

<html>
    <head>
    </head>
    <body>
        <h1>HTML!</h1>
        <p>Hi {{ name }}, you are {{ age }} years old</p>
        <form action="/" method="POST">
            <label>Age
                <input type="text" name="age" />
            </label>
            <label>Name<input type="text" name="name" /></label>
            <button type="submit">submit</button>
        </form>
    </body>
</html>

Task 3

make a post request to your application with requests that submits the name and age

r = requests.post('http://localhost:5000/', data={'name': 'Talvi', 'age': 50})
print(r.text)