Practice: Introduction to Web Development with Python

« Read the chapter

Q1. Get the path

BeginnerCoding

Use urlparse to print the path of https://example.com/blog/post1?id=9.

Goal: Split a URL.

Q2. Read a query string

IntermediateCoding

Use parse_qs to print the query dictionary of the query string sort=price&page=2.

Goal: Parse query strings.

Q3. Name a status code

BeginnerCoding

Use http.HTTPStatus to print the phrase for 404.

Goal: Look up status codes.

Q4. Build JSON

BeginnerCoding

Create a dictionary {"name": "Pen", "price": 10} and print it as JSON text.

Goal: Create JSON.

Q5. Escape a tag

IntermediateCoding

Use html.escape to print the safe version of <b>Hi</b>.

Goal: Escape user text.

Q6. Simple router

IntermediateCoding

Write a function route(path) that returns "Home" for "/", "About" for "/about" and "Not found" otherwise. Print route("/about") and route("/x").

Goal: Build a tiny router.

Q7. URL host

BeginnerOutput

What does this program print?

Code
from urllib.parse import urlparse
print(urlparse("http://localhost:8000/a").netloc)

Goal: Read URL parts.

Q8. Scheme

BeginnerOutput

What does this program print?

Code
from urllib.parse import urlparse
print(urlparse("https://python.org").scheme)

Goal: Read URL parts.

Q9. Status phrases

IntermediateOutput

What does this program print?

Code
from http import HTTPStatus
print(HTTPStatus.OK.value, HTTPStatus.OK.phrase)

Goal: Know status codes.

Q10. JSON round trip

IntermediateOutput

What does this program print?

Code
import json
data = json.loads('{"a": [1, 2], "b": true}')
print(data["a"][1], data["b"])

Goal: Read JSON in Python.

Q11. Escape quotes

AdvancedOutput

What does this program print?

Code
import html
print(html.escape('a & b'))

Goal: Know what escape changes.

Q12. Routing result

AdvancedOutput

What does this program print?

Code
from wsgiref.util import setup_testing_defaults

def call(app, path):
    environ = {"REQUEST_METHOD": "GET", "PATH_INFO": path}
    setup_testing_defaults(environ)
    environ["PATH_INFO"] = path
    seen = {}
    def start_response(status, headers):
        seen["status"] = status
    body = b"".join(app(environ, start_response))
    return seen["status"], body.decode()

def app(environ, start_response):
    path = environ["PATH_INFO"]
    if path == "/":
        start_response("200 OK", [("Content-Type", "text/plain")])
        return [b"Welcome home"]
    start_response("404 Not Found", [("Content-Type", "text/plain")])
    return [b"No such page"]

status, body = call(app, "/")
print(status.split()[0], body)

Goal: Follow a WSGI app.

Q13. Fix wrong JSON method

IntermediateDebugging

This code tries to make JSON text but prints a dictionary-like error. Fix it so it prints {"ok": true}.

Code
import json
print(json.loads({"ok": True}))

Goal: Fix dumps versus loads.

Q14. Fix the query parse

IntermediateDebugging

This code looks for the sort value but gets a list. Fix it to print price.

Code
from urllib.parse import parse_qs
q = parse_qs("sort=price")
print(q["sort"])

Goal: Handle parse_qs output.

Q15. Fix unsafe output

AdvancedDebugging

This code inserts a comment into HTML unescaped. Fix it so that the script tag is made harmless.

Code
comment = "<script>x()</script>"
print("<p>" + comment + "</p>")

Goal: Prevent XSS.

Q16. GET or POST?

BeginnerConceptual

Which method should a login form use, GET or POST, and why?

Goal: Choose HTTP methods.

Q17. Meaning of 5xx

IntermediateConceptual

What does a 5xx status code tell you and who should fix it?

Goal: Understand status groups.

Q18. Greeting page

AdvancedApplication

Write a function page(name) that returns the HTML <h1>Hello, NAME!</h1> with the name escaped. Print page("<Sam>").

Goal: Create safe HTML.

Q19. Product API response

IntermediateApplication

Write a function product_json(pid) that returns JSON text for a product dictionary {"id": pid, "name": "Pen"}. Print product_json(7).

Goal: Write an API-style function.