Welcome!
- In previous weeks, you have learned numerous programming languages, techniques, and strategies.
- Indeed, this class has been far less of a C class or Python class and far more of a programming class, such that you can go on to follow future trends.
- In these past several weeks, you have learned how to learn about programming.
- Today, we will be moving from HTML and CSS into combining HTML, CSS, SQL, Python, and JavaScript so you can create your own web applications.
- You might consider using the skills you learn this week to create your final project.
http-server
- Up until this point, all HTML you saw was pre-written and static.
- In the past, when you visited a page, the browser downloaded an HTML page, and you were able to view it. These are considered static pages, in that what is programmed in the HTML is exactly what the user sees and downloads client-side to their internet browser.
- Dynamic pages refer to the ability of Python and similar languages to create HTML on-the-fly. Accordingly, you can have web pages that are generated server-side by code based upon the input or behavior of users.
- You have used
http-serverin the past to serve your web pages. Today, we are going to utilize a new server that can parse out a web address and perform actions based on the URL provided. - Further, last week, you saw URLs as follows:
Notice that file.html is an HTML file inside a folder called folder at example.com.
Flask
-
This week, we introduce the ability to engage with routes such as
https://www.example.com/route?key=value, where specific functionality can be generated on the server via the keys and values provided in the URL. -
Flask is a third-party library that allows you to host web applications using the Flask framework, or a micro-framework, within Python.
-
You can run Flask by executing
flask runin your terminal window in cs50.dev. -
To do so, you will need a file called
app.pyand another calledrequirements.txt.app.pycontains code the tells Flask how to run your web application.requirements.txtincludes a list of the libraries that are required for your Flask application to run. -
Here is a sample of
requirements.txt:Notice only
Flaskappears in this file. This is because Flask is required to run the Flask application. -
Here is a very simple Flask application in
app.py:
Notice that the / route simply returns the text hello, world.
- We can also create code that implements HTML:
Notice that rather than returning simple text, this provides HTML.
- Improving our application, we can also serve HTML based upon templates by creating a folder called
templatesand creating a file calledindex.htmlwith the following code within that folder:
- Then, in the same folder that the
templatesfolder appears, create a file calledapp.pyand add the following code:
Notice that this code defines app as the Flask application. Then, it defines the / route of app as returning the contents of index.html with the argument of name. By default, the request.args.get function will look for the name being provided by the user. If no name is provided, it will default to world. @app.route is otherwise known as a decorator.
- You can run this web application by typing
flask runin the terminal window. If Flask does not run, ensure that your syntax is correct in each of the files above. Further, if Flask will not run, make sure your files are organized as follows:
- Once you get it running, you will be prompted to click a link. Once you navigate to that webpage, try adding
?name=[Your Name]to the base URL in your browser’s URL bar.
Forms
- Improving upon our program, we know that most users will not type arguments into the address bar. Instead, programmers rely upon users to fill out forms on web pages. Accordingly, we can modify
index.htmlas follows:
Notice that a form is now created that takes the user’s name and then passes it off to a route called /greet. autocomplete is turned off. Further, a placeholder with the text name is included.
- Further, we can change
app.pyas follows:
Notice that the default path will display a form for the user to input their name. The /greet route will pass the name to that web page.
- To finalize this implementation, you will need another template for
greet.htmlin thetemplatesfolder as follows:
Notice that this route will now render the greeting to the user, followed by their name.
Templates
- Both of our web pages,
index.htmlandgreet.html, have much of the same data. Wouldn’t it be nice to allow the body to be unique but copy the same layout from page to page? - First, create a new template called
layout.htmland write code as follows:
Notice that the {% block body %}{% endblock %} allows for the insertion of other code from other HTML files.
- Then, modify your
index.htmlas follows:
Notice that the line {% extends "layout.html" %} tells the server where to get the layout of this page. Then, the {% block body %}{% endblock %} tells what code to be inserted into layout.html.
- Finally, change
greet.htmlas follows:
Notice how this code is shorter and more compact.
Request Methods
- You can imagine scenarios where it is not safe to utilize
get, as usernames and passwords would show up in the URL. - We can utilize the method
postto help with this problem by modifyingapp.pyas follows:
Notice that POST is added to the /greet route, and that we use request.form.get rather than request.args.get.
- This tells the server to look deeper into the virtual envelope and not reveal the items in
postin the URL. - Still, this code can be advanced further by utilizing a single route for both
getandpost. To do this, modifyapp.pyas follows:
Notice that both get and post are done in a single routing. However, request.method is utilized to properly route based on the type of routing requested by the user.
- Accordingly, you can modify your
index.htmlas follows:
Notice that the form action is changed.
- Still, there is a bug in this code. With our new implementation, when someone types in no name into the form,
Hello,is displayed without a name. We can improve our code by editingapp.pyas follows:
Notice that name=request.form.get("name")) is changed.
- Finally, change
greet.htmlas follows:
Notice how hello, {{ name }} is changed to allow for a default output when no name is identified.
- As we’ve been changing many files, you may wish to compare your final code with our final code.
Frosh IMs
-
Frosh IMs or froshims is a web application that allows students to register for intramural sports.
-
Close all your
hellorelated windows and create a folder by typingmkdir froshimsin the terminal window. Then, typecd froshimsto browse to this folder. Within, create a directory called templates by typingmkdir templates. -
Next, in the
froshimsfolder, typecode requirements.txtand code as follows:As before, Flask is required to run a Flask application.
-
Finally, type
code app.pyand write code as follows:
Notice that a failure option is provided, such that a failure message will be displayed to the user if the name or sport field is not properly filled out.
- Next, create a file in the
templatesfolder calledindex.htmlby typingcode templates/index.htmland write code as follows:
- Next, create a file called
layout.htmlby typingcode templates/layout.htmland write code as follows:
- Fourth, create a file in templates called
success.htmlas follows:
- Finally, create a file in templates called
failure.htmlas follows:
- Execute
flask runand check out the application at this stage. - You can imagine how we might want to see the various registration options using radio buttons. We can improve
index.htmlas follows:
Notice how type has been changed to radio.
- Again, executing
flask runyou can see how the interface has now changed. - You can imagine how we might want to accept the registration of many different registrants. We can improve
app.pyas follows:
Notice that a dictionary called REGISTRANTS is used to log the sport selected by REGISTRANTS[name]. Also, notice that registrants=REGISTRANTS passes the dictionary on to this template.
- Additionally, we can implement
error.html:
- Further, create a new template called
registrants.htmlas follows:
Notice that {% for name in registrants %}...{% endfor %} will iterate through each of the registrants. Very powerful to be able to iterate on a dynamic web page!
- Finally, create a folder called
staticin the same folder asapp.py. There, upload the following file of a cat. - Execute
flask runand play with the application. - You now have a web application! However, there are some security flaws! Because everything is held in memory, an adversary could change the HTML and hack the website. Further, this data will not persist if the server is shut down. Could there be some way we could have our data persist even when the server restarts?
Flask and SQL
-
Just as we have seen how Python can interface with a SQL database, we can combine the power of Flask, Python, and SQL to create a web application where data will persist!
-
To implement this, you will need to take a number of steps.
-
First, download the following SQL database into your
froshimsfolder. -
Execute in the terminal
sqlite3 froshims.dband type.schemato see the contents of the database file. Further typeSELECT * FROM registrants;to learn about the contents. You’ll notice that there are currently no registrations in the file. -
Next, modify
requirements.txtas follows: -
Modify
index.htmlas follows:
- Modify
layout.htmlas follows:
- Ensure
error.htmlappears as follows:
- Modify
registrants.htmlto appear as follows:
Notice that a hidden value registrant.id is included such that it’s possible to use this id later in app.py
- Finally, modify
app.pyas follows:
Notice that the cs50 library is utilized. A route is included for register for the post method. This route will take the name and sport taken from the registration form and execute a SQL query to add the name and the sport to the registrants table. The deregister routes to a SQL query that will grab the user’s id and utilize that information to deregister this individual.
- You can execute
flask runand examine the result. - If you want to download our implementation of
froshimsyou can do so here. - You can read more about Flask in the Flask documentation.
Cookies and Session
app.pyis considered a controller. A view is considered what the users see. A model is how data is stored and manipulated. Together, this is referred to as MVC (model, view, controller).- While the prior implementation of
froshimsis useful from an administrative standpoint, where a back-office administrator could add and remove individuals from the database, one can imagine how this code is not safe to implement on a public server. - For one, bad actors could make decisions on behalf of other users by hitting the deregister button – effectively deleting their recorded answer from the server.
- Web services like Google use login credentials to ensure users only have access to the right data.
- We can actually implement this itself using cookies. Cookies are small pieces of data that are stored in your browser such that your browser can communicate with the server and effectively say, “I’m an authorized user that has already logged in.” This authorization through this cookie is called a session.
- Cookies may be stored as follows:
Here, a session id is stored with a particular value representing that session.
-
In the simplest form, we can implement this by creating a folder called
loginand then adding the following files. -
First, create a file called
requirements.txtthat reads as follows:Notice that in addition to
Flask, we also includeFlask-Session, which is required to support login sessions. -
Second, in a
templatesfolder, create a file calledlayout.htmlthat appears as follows:
Notice this provides a very simple layout with a title and a body.
- Third, create a file in the
templatesfolder calledindex.htmlthat appears as follows:
Notice that this file looks to see if session["name"] exists (elaborated further in app.py below). If it does, it will display a welcome message. If not, it will recommend you browse to a page to log in.
- Fourth, create a file called
login.htmland add the following code:
Notice this is the layout of a basic login page.
- Finally, create a file called
app.pyand write code as follows:
Notice the modified imports at the top of the file, including session, which will allow you to support sessions. Most importantly, notice how session["name"] is used in the login and logout routes. The login route will assign the login name provided and assign it to session["name"]. However, in the logout route, the logging out is implemented by clearing the value of session.
-
The
sessionabstraction allows you to ensure only a specific user has access to specific data and features in our application. It allows you to ensure that no one acts on behalf of another user, for good or bad! -
If you wish, you can download our implementation of
login. -
You can read more about sessions in the Flask documentation.
-
Moving on to a final example of utilizing Flask’s ability to enable a session.
-
We examined the following code for
storeinapp.py. The following code was shown:
Notice that cart is implemented using a list. Items can be added to this list using the Add to Cart buttons in books.html. When clicking such a button, the post method is invoked, where the id of the item is appended to the cart. When viewing the cart, invoking the get method, SQL is executed to display a list of the books in the cart.
- We also saw the contents of
books.html:
Notice how this creates the ability to Add to Cart for each book using for book in books.
- You can see the rest of the files that power this
flaskimplementation in the source code.
Shows
- We looked at a pre-designed program called
shows, inapp.py:
Notice how the search route allows for a way by which to search for a show. This search looks for titles LIKE the one provided by the user.
- We also examined
index.html:
- You can see the rest of the files of this implementation in the source code.
APIs
- An application program interface or API is a series of specifications that allow you to interface with another service. For example, we could utilize IMDB’s API to interface with their database. We might even integrate APIs for handling specific types of data downloadable from a server.
- Improving upon
shows, looking at an improvement ofapp.py, we saw the following:
Notice that the search route executes a SQL query.
- Looking at
search.html, you’ll notice that it is very simple:
Notice that it provides a bulleted list.
- Finally, looking at
index.html, notice that AJAX code is utilized to power the search:
Notice an event listener is utilized to dynamically query the server to provide a list that matches the title provided. This will locate the ul tag in the HTML and modify the web page accordingly to include the list of the matches.
- You can read more in the AJAX documentation.
JSON
- JavaScript Object Notation or JSON is a text file of dictionaries with keys and values. This is a raw, computer-friendly way to get lots of data.
- JSON is a very useful way of getting back data from the server.
- You can see this in action in the
index.htmlwe examined together:
While the above may be somewhat cryptic, it provides a starting point for you to research JSON on your own to see how it can be implemented in your own web applications.
- Further, we examined
app.pyto see how the JSON response is obtained:
Notice how jsonify is used to convert the result into a readable format acceptable by contemporary web applications.
- You can read more in the JSON documentation.
- In summary, you now have the ability to complete your own web applications using Python, Flask, HTML, and SQL.
Summing Up
In this lesson, you learned how to utilize Python, SQL, and Flask to create web applications. Specifically, we discussed…
- Flask
- Forms
- Templates
- Request Methods
- Flask and SQL
- Cookies and Session
- APIs
- JSON