Python & Flask

For Web Development

Conner Ardman | ardmanc@uw.edu

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 use 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 ($seconds < 60) {
					   print "Less than a minute remaining!";
					} else if ($seconds < 3600) {
					   print "One hour remaining!";
					} else {
					   print "Over an hour remaining!";
					}
				

PHP


				if seconds < 60:
				   print("Less than a minute remaining!")
				elif seconds < 3600:
				   print("One hour remaining!")
				else:
				   print("Over an hour remaining!")
				

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

How Flask Works

Flask Template


						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.

Make sure to remove "debug=True" before sharing your project.

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

How Would You Create This In PHP?


 [
   {
	   "age": 21,
	   "name": "Conner,
	   "dogs": ["Bailey", "Roxy"]
   }
 ]
				  

JSON output

How Would You Create This In PHP? (solution)


					$output = [
					    [
					     "age" => 21,
					     "name" => "Conner",
					     "dogs" => ["Bailey", "Roxy"]
					    ]
					];
					header("Content-type: application/json");
					echo json_encode($output);
				  

PHP


 [
   {
	   "age": 21,
	   "name": "Conner,
	   "dogs": ["Bailey", "Roxy"]
   }
 ]
				  

JSON output

JSON With Flask Jsonify


						from flask import Flask, jsonify
						json = [
						  {
						    "age": 21,
						    "name": "Conner",
						    "dogs": ["Bailey", "Roxy"]
						  }
						]
						return jsonify(json)
   				

Python With Flask, Jsonify


				   [
				     {
				  	   "age": 21,
				  	   "name": "Conner,
				  	   "dogs": ["Bailey", "Roxy"]
				     }
				   ]
   				

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

Download The Project Zip

Setting Up Python & Flask

Download Python


                  sudo pip3 install flask
               

Terminal

After downloading python, 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 list 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 the terminal, navigate to your project folder, and run this command:


						python3.7 quotes.py
					

Terminal

Next, copy the url that looks something Like "localhost:8080/" in the terminal.

Example Solution


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

Python


Or this fun one liner with list comprehensions:


				   out = [{"Quote": input[i], "Author": input[i + 1]}
			           for i in range(0, len(input), 2)]
				

Python