Server Programming II

INFO 153B/INFO 253B: Backend Web Architecture

Kay Ashaolu

What have we done?

  • We have created a server that can accept HTTP requests, and send HTTP responses back
  • We have full control over what we send back as a response
  • We are using Python in order to fully control the back-end

More about routes

  • Routes connect URL paths to callback functions
    • On the event that a client goes to the "/" path
    • Execute the assigned callback function

Quick note on server applications

  • A server application is continuously running
  • It does this so that it always listens to requests
  • In order to exit a Python Flask web application you must kill the application
  • This is done in Unix by the keyboard combination
    Control + C

Route Example

# webserver.py

from flask import Flask

app = Flask(__name__)

@app.route('/')
def index_page():
  return "<html><head><title>Homepage</title></head>\
    <body><h1>This is the home page!</h1></body></html>"

@app.route('/about')
def about_page():
	return "<html><head><title>About</title></head>\
    <body><h1>This is the about us page!</h1></body></html>"

@app.route('/blog/post-1')
def blog_post():
	return "<html><head><title>Blog 1</title></head>\
    <body><h1>This is the first blog post</h1></body></html>"

What's happening?

  • We have explicitly told our server to respond to three requests in a specific way
  • We return the raw text that we want our client (the browser) to receive
  • Note that we are sending pure html (language browser understands) to the client. The browser takes that text and displays the webpage we see

What about static files?

  • Sometimes we just want to send the user the resource as is
  • Examples include image files, pdf files, media files
  • We need some mechanism for our static files to be sent to the client on request

Flask and Static Files

  • Flask has a mechanism to set a directory to be treated as a static server
  • This is exactly how the server from last week operated, and how your local file system operates
  • When a user goes to a particular path, the file that is there is sent to the client as is
  • This is different with the routes that we have been using so far

Static Example

# webserver.py

from flask import Flask
app = Flask(__name__,static_url_path="/static")

@app.route('/')
def hello_world():

    return """
<html>
<head>
	<title>Homepage</title>
    <link rel='stylesheet' href='/static/style.css' />
</head>
<body>
	<h1>This is the home page!</h1>
    <script type='text/javascript' src='/static/script.js'></script>
</body>
</html>
"""

Static Example

/* static/style.css   */

h1 {
	color: blue;
}

Static Example

// static/script.js

alert("script.js has been loaded!");

Static Example

What's happening here?

  • We have set the path '/static' to run as a static server
  • Any path that starts with '/static' will serve files "as is" from the "static" folder
  • Check it out by going to http://localhost:5050/static/style.css
  • Because of our static server, we can serve our own static files

Let's see another example

from flask import Flask
import json

app = Flask(__name__)

quote_db = {
  'sunday': "Life is about making an impact, not making an income. \
  –Kevin Kruse",
  'monday': "Whatever the mind of man can conceive and believe, it can achieve. \
  –Napoleon Hill",
  'tuesday': "Strive not to be a success, but rather to be of value. \
  –Albert Einstein",
  'wednesday': "You miss 100% of the shots you don’t take. \
  –Wayne Gretzky",
  'thursday': "Every strike brings me closer to the next home run. \
  –Babe Ruth",
  'friday': "We become what we think about. \
  –Earl Nightingale",
  'saturday': "Life is what happens to you while you’re busy making other plans. \
  –John Lennon",
}

@app.route('/quote/<day_of_week>')
def quote_of_the_day(day_of_week):
  response = {"day": day_of_week, "quote": quote_db[day_of_week.lower()]}

  return json.dumps(response)

What is happening?

  • We have created an endpoint that is expecting the "day_of_week" parameter to be passed in the URL
  • Note that the route has this special "<>" syntax. This tells the function underneath to expect info from the url to be passed into its function
  • Note that day_of_week is passed as an input to the function quote_of_the_day. The input is day_of_week passed via the URL and the response is JSON with the quote for that day of the week
  • THIS IS AN API :)

Questions?