Python & Flask

For Web Development

A CSE154 Exploration Session by Conner Ardman
ardmanc@uw.edu

Attendance

Special thanks to Jeremy Zhang for the attendance app!

https://staff.washington.edu/jkzhang/attendance

Password:
python

Why HTML, CSS and JavaScript?

meme
  • They are specialized languages for the web
    • This means they make web development fairly easy
  • They are standards
    • Most browsers know how to interpret it

...Then Why PHP?

PHP is server side, so we don't need to comply with standards. This means we could really choose any language that we want.

PHP Meme

Then Why Not Use Python Instead?

  • Simpler, easy to read syntax
  • Tons of amazing frameworks (Like Flask!)

Some Quick Python Syntax

Printing


					print "Hello World!";
					echo "Hello World!";
				

PHP


					print "Hello World!"
				

Python

Note: Python does not need semicolons!

Variables


						$my_name = "Name";
						$my_age = 13;
					

PHP


						my_name = "Name"
						my_age = 13
					

Python

In Python we will use the same underscore naming conventions as PHP...
just without the annoying dollar signs

Lists


                  classes = ["CSE 154", "CSE 143"]
                  classes.append("CSE 311")
                  classes[1] # Returns "CSE 143"
                  classes[2] # Returns "CSE 311"
                  len(classes) # Returns 3
						

Python

Lists in Python behave very similarly to JavaScript arrays.

For more information on lists and other data structures in Python
view the official documentation

Comments


					# This is a Comment
					// So is this
					/* And This is a multiline comment */
				

PHP


					# Comments in Python only use the pound sign
				

Python

If Statements


					if ($section !== "AL") {
					   print "You should probably change sections";
					} else if ($section === "AA" || $section === "AB") {
					   print "You wake up really early!";
					} else {
					   print "You are in the right section";
					}
				

PHP


if section != "AL":
   print "You should probably change sections"
elif section == "AA" OR section == "AB":
   print "You wake up really early!"
else:
   print "You are in the right section"
				

Python

For Loops


						for ($i = 0; $i < count($my_arr); $i++) {
						   print $my_arr[$i];
						}
					

PHP


						for element in my_arr:
						   print element
					

Python

Note: There is no traditional for loop in Python. We do however have this for each style loop as well as while loops.

More Ways To Loop


						for element in range(0, 3):
						   print element # Prints 0, 1, 2
					

Python


						x = 0
						while x < 5:
						   print x
						   x += 1 # There is no ++ in Python :(
					

Python

Functions


					function my_function($param1, $param2) {
					   # Do stuff
					}
				

PHP


					def my_function(param1, param2):
					   # Do stuff
				

Python

More Python Resources

Flask

Flask is a micro web framework for Python to create web servers

Documentation

Cloud9 Tutorial

How Flask Works

Flask Template (For Cloud 9)


						from flask import Flask, render_template
						app = Flask(__name__)

						@app.route('/hello')
						def hello_name():
						   return render_template('hello.html')

						if __name__ == '__main__':
						   app.run(host='0.0.0.0', port=8080, debug=True)
					

Python With Flask

Note, returning render_template will run an HTML file located in the "templates" directory.

JSON With Flask Jsonify

Flask comes with built in support for JSON... and it is really easy.

If you want an array, put it in a list with []. If you want an object, use the {} notation (this is actually a dictionary which better maps to a JavaScript object.)
More Information On Python Data Types

JSON With Flask Jsonify


                  from flask import Flask, jsonify
                  json = []
                  first = {}
                  first["age"] = 20
                  first["name"] = "Conner"
                  json.append(first)
                  return jsonify(json)
   				

Python With Flask, Jsonify


               [
                 {
                   "age": 20,
                   "name": "Conner"
                 }
               ]
   				

JSON output

Organizing Code in Flask Apps

  • HTML files are contained in a "templates" directory.
  • JavaScript and CSS files are contained in a "static" directory.

Sadly this results in some pretty ugly script and link tags...


					
					
					

HTML With Flask  

Let's Write Some Code!

We are going to make a Python Flask app to display random quotes and their authors.

Project Setup

Go ahead and download this zip file, unzip it and upload the entire thing to Cloud9. If you use Chrome, you can drag the entire folder in at once.

Download The Project Zip

Setting Up Python & Flask in Cloud 9


                  sudo pip install Flask
               

Terminal

Open a new terminal and copy this command to install Flask!

Get To Know The Project

The project you downloaded has 2 folders, complete and challenge. They contain the same code, but the only difference is that challenge does not have the Python code finished. Feel free to look around the HTML, CSS and JavaScript files to see how everything is working!

Your challenge is to complete the quotes function where it says "YOUR CODE HERE" (line 19).

Challenge - Format JSON

Your challenge is to take the input array of quotes and authors and convert them to JSON in this format.


                  [
                   {
                      "Author": " Jamie Zawinski",
                      "Quote": "Linux is only free if your time has no value. "
                   },
                   {
                      "Author": " wordpress.org",
                      "Quote": "Code is poetry. "
                   }
                 ]
   				

Example JSON Output

Running Your Code On Cloud9

To run a Flask app on Cloud9, right click on the .py file and run it.

Next, click the url that looks something Like "http://0.0.0.0:8080/" in the terminal.

From here, navigate to the file path specified in the Python file.
In this case: /quotes

The final URL you visit should end up being something like: http://WORKSPACENAME.c9users.io:8080/quotes

Example Solution


               out = []
               index = 0
               while index < len(input):
                   obj = {}
                   obj["Quote"] = input[index]
                   obj["Author"] = input[index + 1]
                   out.append(obj)
                   index += 2
               

Python