MCS 260 Fall 2021
Emily Dumas
Flask is a Python web framework. It lets you build APIs and web sites with Python.
Competitors include:
Using pip
to install, if the interpreter name is python3
:
python3 -m pip install flask
Confirm installation by testing import in the REPL:
>>> import flask
>>>
If Flask is not installed, this will produce an error.
Flask uses a lot of decorators, a Python feature we haven't covered yet.
Basically, on a line immediately before a function definition, you put a command beginning with @
, e.g.
@decname
def f(x,y,z):
Here, decname
needs to be replaced with the name of a decorator, which is a certain kind of higher-order function. It modifies the behavior of f
.
We might write a function that returns a string:
We might write a function that returns a string:
A Flask decorator lets us link it directly to a URL:
A Flask decorator lets us link it directly to a URL:
Build API so that
/
returns
"Hello World"
.
Build API so that
/element/random
returns a JSON object with info about a randomly-selected chemical element.
Build API that checks whether a given word is a palindrome, so
/palindrome/test?word=banana
would return False
in JSON.
localhost
or IP address 127.0.0.1
is used to refer to the same host you're making a request from.http://domain.com:1234/rest/of/URL/
means to use port 1234 instead of the default (which is 80 for HTTP).app
is a flask.Flask
object, the decorator @app.route("/path/part/of/URL/")
makes a function into a URL handler.flask.jsonify
converts a Python value into a suitable return value from a URL handler.