Web Development with Python, Sqlite and Flask

Web Development with Python, Sqlite and Flask

Web development with Python, SQLite and Flask 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: <username>.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 <your-username>.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. <!doctype html> <html> <body> This is my first Flask program </body> </html> 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 <username>.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 <item> in <list> %} 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 }} <!doctype html> <html> <body> <h1>List of students</h1> <ul> {% for row in students %} <li>{{row[0]}} {{row[1]}} - {{row[2]}}</li> {% endfor %} </ul> {{error}} </body> </html> 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!).

View Full Text

Details

  • File Type
    pdf
  • Upload Time
    -
  • Content Languages
    English
  • Upload User
    Anonymous/Not logged-in
  • File Pages
    10 Page
  • File Size
    -

Download

Channel Download Status
Express Download Enable

Copyright

We respect the copyrights and intellectual property rights of all users. All uploaded documents are either original works of the uploader or authorized works of the rightful owners.

  • Not to be reproduced or distributed without explicit permission.
  • Not used for commercial purposes outside of approved use cases.
  • Not used to infringe on the rights of the original creators.
  • If you believe any content infringes your copyright, please contact us immediately.

Support

For help with questions, suggestions, or problems, please contact us