Web development with Python, SQLite and

In this session we will consider how to create a web front end for a simple Python database. It will be helpful if you have experience of creating databases in Python already.

This session involves following instructions from a worksheet – not my preferred way of teaching but hopefully you will find it useful anyway! Please work in pairs! You may not complete all the instructions in this short session but you can complete it at home!

To get Python working with web pages we have chosen to use Flask, a web development system, although there are other options. You can choose to host your website on your own server, but to make it easier we are using http://pythonanywhere.com as this allows you to set up a website without having to have your own server.

There are three parts to getting started:

1) Create a Python Anywhere account 2) Use “routes” to link Python files to web pages 3) Start with a simple database and output the records to a web page.

Part 1: Get started with Python Anywhere

In this part you will:

• Create a Python Anywhere account • Check that it works Firstly, go to https://www.pythonanywhere.com/ and choose a beginner account.

Once you have created an account, select the option Web from the top-right of the page.

CAS London Conference 2020 1 Sue Sentance & Alex Parry

Select Add a new web app and click Next.

This will create a website for you at the address: .pythonanywhere.com

At the next screen select Flask.

Then select Python 3.8.

Select Next but make a note of where your web app will be stored – mine is in /home/MrParry/mysite/flask_app.py – or you can change this.

CAS London Conference 2020 2 Sue Sentance & Alex Parry

The next screen has the configuration information – the defaults should be OK.

You can now test that the web app is set up by opening a new tab in your browser and going to .pythonanywhere.com, or by right-clicking and opening the link in a new tab that is after the “Configuration for” text.

You should see “Hello from Flask!”.

Keeping this tab open means that you can switch between editing and viewing your web app easily.

You now have a working web app – all you need to do now is to write what will go on your web pages. This uses a combination of HTML files and Python functions.

Go back to the tab showing the website configuration (keeping the one showing your site open), and click on the Files tab.

You will be taken to a list of files and directories. Click on the mysite directory.

CAS London Conference 2020 3 Sue Sentance & Alex Parry

Right-click and open in a new tab to open flask_app.py which contains the Python code

You will now be able to look inside the file flask_app.py (inside the mysite directory) which shows you where the “Hello from Flask!” message came from.

The line @app.route('/') means that the home page of your website will run the function below

You can edit this string and check that it changes on your web page

IMPORTANT! When you have changed anything in your files you must do three things:

1. Click Save 2. Click the Refresh button on the top right-hand corner of the Python Anywhere window 3. Refresh the tab where your web app is (use F5 or click enter at the end of the URL)

CAS London Conference 2020 4 Sue Sentance & Alex Parry

Part 2: Writing code to interact with a web page

In this part you will:

• Create an HTML file to display a web page • Edit the Flask app in Python to render an HTML file

Firstly, click on Files and then on mysite (unless you renamed this).

Inside mysite is your Python program flask_app.py

Then create two new directories (folders) called templates and static inside the mysite folder. The templates folder will be for the HTML files that are used to view the data, and static will be used to hold CSS files to style your web pages and make them look better.

CAS London Conference 2020 5 Sue Sentance & Alex Parry

Your Python code will all go inside flask_app.py – this is the controller.

Inside the templates folder create a file called index.html (this is your homepage).

Make a simple HTML file to display a welcome message.

This is my first Flask program

Now edit flask_app.py so that it routes to the HTML view you have just defined. You need to import the method render_template from Flask at the top of the page.

Then you should redefine the function underneath @app_route('/') so that it returns the web page you have created 'index.html' using render_template

Remember to save and refresh the Python code (using the two buttons on the top-right hand corner) and then refresh your web app page or open it again. Once that works that’s almost all you need to know to start working with your database via a web interface!

The next step is to start working with a database.

CAS London Conference 2020 6 Sue Sentance & Alex Parry

Part 3: Connecting to the database

In this section you will:

1. Upload a simple database to work with in this application 2. Create another Python function to display the students in the database 3. Create an HTML file to display the students in a web page 4. Link the new page to your homepage, index.html 1) Uploading a database to Python Anywhere You can of course create a table and populate it in Python Anywhere but for simplicity you will use a simple table that I have created and made available to you via the shared area.

Our application will start as a simple student database, which is called school.db. and contains one table named Student. Download it from the shared area and inspect is using https://sqliteonline.com/ by selecting File > Open DB and opening the school database.

Once you have opened the database in SQLite Online, you can click on the Student table on the left-hand side to view the field names. You can also type in SQL statements and select Run to execute them, which is a good way of debugging your application.

Data dictionary and sample data for Student table

Field Type Other information

student_id integer Primary Key

student_fname text

student_lname text

student_tg text

CAS London Conference 2020 7 Sue Sentance & Alex Parry

In Python Anywhere, go to Files and upload the database school.db that you have downloaded from the shared area. Do not put into mysite but into the folder level above.

Your database should be at the top level

2) Create another Python function to display the students in the database The next stage is to write a Python function that will select the student details from the database and display them. Go into the mysite folder and open flask_app.py – as you are going to and fro it’s a good idea to open it in a new tab.

Add this line to the top of the Python program to import sqlite3: import sqlite3

Create a new function at the bottom of flask_app.py underneath the previous function. Fill in the function with the correct SQL statement to display the student details:

@app.route('/list') Add the SQL statement to def list_all_students(): select the first name, last name with sqlite3.connect("school.db") as db: try: and tutor group of all students cursor = db.cursor() sql = """ This is the Flask part where

data is sent to your HTML file """ cursor.execute(sql) results = cursor.fetchall() return render_template("student-list.html", students=results) except sqlite3.Error: message = "There was a problem executing the SQL statement" return render_template("student-list.html", error=message)

The @app.route('/list') route on the top line of this code tells us that this function will be called at .pythonanywhere.com/list

Before we can test that this new function works another web page should be created. CAS London Conference 2020 8 Sue Sentance & Alex Parry

3. Create an HTML file to display the students in a web page The next stage is to create a web page to display the names of the students in the table.

This is the output we want on the web page

Create a new file inside the templates folder called student-list.html. We can use a Python Template Engine called Jinja to iterate through the student data in HTML that is returned from Python. You can find out more about Jinja at http://jinja.pocoo.org/ but primarily we will use the statement {% for in %} to iterate through a list.

In student-list.html write the code to display all the student names followed by a dash and their tutor group. Note that programming constructs in Jinja start with {% and end with %} whilst variables in Jinja start with {{ and end in }}

List of students

    {% for row in students %}
  • {{row[0]}} {{row[1]}} - {{row[2]}}
  • {% endfor %}
{{error}}

If the SQL statement executes successfully, cursor.fetchall() will return a 2D list of data which will be passed from the Python function to the Jinja variable students. Then the for loop will be executed, which will output the data from each student row as text.

If there is an SQLite3 error when executing the SQL statement, an error message will be passed from the Python function to the Jinja variable error (this is great for debugging!).

Test this works at .pythonanywhere.com/list (with no file extension at the end of the URL). If you get an Internal Server Error, use the error log under the Web tab of Python Anywhere and scroll to the very bottom to see what went wrong.

Next you will add a link to index.html to the student list web page. CAS London Conference 2020 9 Sue Sentance & Alex Parry

4. Link the new page to the homepage, index.html

We now want to change index.html so that it looks like the webpage on the right.

We will have a heading “School database” and the beginnings of a list – we can add more items to the list later.

To do this, you should add a link inside index.html that points to the route you defined in the Flask app – in this case the app route for the student list page is /list

List students

Inside the student list page, you could then add a “Return to home page” link that routes to the index page, which would start with .

Optional: If you are comfortable with CSS for styling web pages, then you could add a CSS file to your application to improve the look. This goes in the static folder and you should use url_for as in the example code below:

Make sure to also import url_for from Flask in the Python program so it looks like this: from flask import Flask, render_template, url_for

Your index.html file might eventually look like this:

You have now got a web app working with a database and Python!

Having got this far, you can if you wish try to build this all over again so that you will get used to the steps. Students find this useful too. CAS London Conference 2020 10 Sue Sentance & Alex Parry