Practice: Flask Fundamentals

« Read the chapter

Q1. Hello route

BeginnerCoding

Create a Flask app with a route / that returns the text Welcome. Use the test client to print the response text.

Goal: Create a basic route.

Q2. Status code

BeginnerCoding

Make a route /ping returning pong and print its status code using the test client.

Goal: Read the response status.

Q3. Dynamic name

BeginnerCoding

Create /hi/<name> that returns Hi, followed by the name. Print the result for Ravi.

Goal: Use dynamic routes.

Q4. Double a number

IntermediateCoding

Create /double/<int:n> returning twice n as text. Print the response for 21.

Goal: Use route converters.

Q5. JSON reply

IntermediateCoding

Create /info returning JSON with keys lang and version (Python, 3). Print the JSON as a dictionary.

Goal: Return JSON.

Q6. Query string

IntermediateCoding

Create /search that reads the q query parameter and returns You searched: followed by it. Request /search?q=flask.

Goal: Read request arguments.

Q7. Template greeting

IntermediateCoding

Use render_template_string to render Hello {{ name }} with name set to Mia and print it.

Goal: Render templates.

Q8. POST only

AdvancedCoding

Create a route /save that accepts only POST and returns saved. Print the status code of a GET request to it.

Goal: Restrict HTTP methods.

Q9. Output: route order

BeginnerOutput

What does this print?

Code
from flask import Flask
app = Flask(__name__)

@app.route("/a")
def a():
    return "A"

c = app.test_client()
print(c.get("/a").status_code, c.get("/b").status_code)

Goal: Predict response codes.

Q10. Output: converter

IntermediateOutput

What does this print?

Code
from flask import Flask
app = Flask(__name__)

@app.route("/n/<int:x>")
def n(x):
    return str(x + 1)

c = app.test_client()
print(c.get("/n/9").get_data(as_text=True))
print(c.get("/n/nine").status_code)

Goal: Understand converters.

Q11. Output: Jinja filter

IntermediateOutput

What does this print?

Code
from jinja2 import Template
t = Template("{{ word|upper }}-{{ n + 1 }}")
print(t.render(word="ok", n=4))

Goal: Use Jinja filters.

Q12. Output: JSON content type

IntermediateOutput

What does this print?

Code
from flask import Flask, jsonify
app = Flask(__name__)

@app.route("/")
def home():
    return jsonify(ok=True)

r = app.test_client().get("/")
print(r.mimetype)

Goal: Inspect response headers.

Q13. Output: dict return

AdvancedOutput

What does this print?

Code
from flask import Flask
app = Flask(__name__)

@app.route("/")
def home():
    return {"a": 1, "b": [2, 3]}

print(app.test_client().get("/").get_json()["b"][1])

Goal: Return dictionaries.

Q14. Output: url_for

AdvancedOutput

What does this print?

Code
from flask import Flask, url_for
app = Flask(__name__)

@app.route("/user/<name>")
def profile(name):
    return name

with app.test_request_context():
    print(url_for("profile", name="sam"))

Goal: Build URLs with url_for.

Q15. Debug: missing methods

IntermediateDebugging

This form route always answers 405 for a POST. Fix it.

Code
from flask import Flask, request
app = Flask(__name__)

@app.route("/send")
def send():
    return "got " + request.form["x"]

print(app.test_client().post("/send", data={"x": "1"}).status_code)

Goal: Fix HTTP method errors.

Q16. Debug: no return value

BeginnerDebugging

This view returns nothing, so Flask raises an error. Fix it.

Code
from flask import Flask
app = Flask(__name__)

@app.route("/")
def home():
    print("home page")

print(app.test_client().get("/").status_code)

Goal: Return a valid response.

Q17. Debug: duplicate function names

AdvancedDebugging

Two routes share one function name, which makes Flask raise an error. Fix it.

Code
from flask import Flask
app = Flask(__name__)

@app.route("/one")
def page():
    return "1"

@app.route("/two")
def page():
    return "2"

print(app.test_client().get("/two").get_data(as_text=True))

Goal: Understand endpoints.

Q18. Why Flask is micro

BeginnerConceptual

Explain in your own words what micro framework means in Flask.

Goal: Describe Flask's design.

Q19. GET versus POST

IntermediateConceptual

Describe when you would use POST instead of GET for a form.

Goal: Choose HTTP methods.

Q20. Redirect after POST

AdvancedApplication

Why do web developers redirect to another page after handling a form post?

Goal: Apply the redirect pattern.