flask-notes
flask-notes
Flask is a Python web framework, i.e. something that lets you build web apps!
One cool thing you can then do is to make different machines talk to each other —
you can even have things written in different languages talk to each
But first, how does the web work? See HTTP if not already familiar.
HTTP
Stands for Hypertext Transfer Protocol
A standard for how computers should talk to each other through internet
connection, basically
HTTP requests — whenever you want to get information, send message, etc.
GET / HTTP/1.1
Host: www.example.com
User-Agent: Mozilla/5.0
Accept:
text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,*
/*;q=0.8
Accept-Language: en-GB,en;q=0.5
Accept-Encoding: gzip, deflate, br
Connection: keep-alive
Here, we see that this is a GET request to www.example.com to request data at / sent
via Mozilla/5.0 etc...
And here's the response
HTTP/1.1 200 OK
Date: Mon, 23 May 2005 22:38:34 GMT
Content-Type: text/html; charset=UTF-8
Content-Length: 155
Last-Modified: Wed, 08 Jan 2003 23:11:55 GMT
Server: Apache/1.3.3.7 (Unix) (Red-Hat/Linux)
ETag: "3f80f-1b6-3e1cb03b"
Accept-Ranges: bytes
Connection: close
<html>
<head>
<title>An Example Page</title>
</head>
<body>
<p>Hello World, this is a very simple HTML document.</p>
</body>
</html>
We see a status code 200 , date, time, content type, ..., and the data we got back,
which is some html code.
If you open the inspect panel on your browser and go to the Network tab, chances
are you will see http requests flying around.
(You may also see https somewhere. That's http with encryption)
In the example, we saw a GET request, but there are more. We'll briefly go over the
two most common ones:
These requests can have some "payload". There are many places where you can
include data in the request and in many different formats.
app = Flask(__name__)
And this lets you run the app when you run python app.py in terminal
if __name__ == '__main__':
# here, 127.0.0.1 is the IP address for localhost, and port can be though
of the channel at this address?
app.run(host='127.0.0.1', port = 5000)
# If you want your app to be available publically, you change the host to
0.0.0.0. Then people in your local network should be able to access your app
via your computer's IP
# Note that your computer probably doesn't have a public IP, so someone
in, California, for example, won't be able to access your app (unless they go
on CMU VPN(?))
# If you want your app to be made public everywhere, you need a public
IP.
But wait, we just created an app that doesn't "listen" to anything. We need to define
functions so that it handles http requests like the one we saw earlier.
Here's the code for a function that listens at / and responds by sending hello
world.
@app.route("/")
def root_route():
return "Hello, World!"
Flask uses some sort of function decorator. We already said app = Flask(__name__) ,
so app.route("...") is creating a route for the app. And "/" just means root URL.
Flasks makes it so that return sends our response. In this case we're just sending
text.
app = Flask(__name__)
@app.route("/")
def root_route():
return "Hello, World!"
if __name__ == '__main__':
app.run(host='127.0.0.1', port = 5000)
More routes
We can do more than just sending back hello world — we can get data from the
request, do something with it, and send back something fancy!
@app.route('/projects')
def projects():
return 'The project page'
@app.route('/user/<username>')
def user_profile(username):
print(username)
return f'hmm, see console'
We can specify the type. Also we are returning some html here
@app.route('/fact/<int:n>')
def fact_page(n):
return f'<p style="overflow-wrap: anywhere;">{n}! = {fact(n)}</p>'
@app.route('/sayhello/<name>')
def sayhello(name):
return render_template("sayhello.html", name = name)
@app.route("/api")
def api():
return {
"foo": "fooo",
"bar": "barr",
"quote": "hello world",
}
flask run
or
or you can make the app run when you run the python file by writing:
if __name__ == '__main__':
app.run(host='127.0.0.1', port = 5000) # this runs it on local network
# app.run(host='0.0.0.0', port = 5000) # this makes it public
What we need:
/add topic
/promote topic
/reject topic
Some interface to send POST requests
UI design (maybe) (implemented on the stylish-topiclist branch)
Database
Database is a way to store data in a manageable way. By manageable it could mean
structured, scalable, etc.
Technically, you can just use a dictionary to hold data, but notice what happens
when you restart the app—all your data is lost.
One benefit of using a database, therefore, is that you can keep the data no matter
what happens to your python process.
For the sake of this demo, we use TinyDB to keep things simple. You google for
more options.
TinyDB
TinyDB stores data in json format. You can read more about the library on its
website.
Deployment
PythonAnywhere
The demo app is hosted on PythonAnywhere, which is free and simple to use. To
run your Flask app, do these:
Other options
Vercel: supports continuous deployment from git but doesn't allow writing to
disk
VPS: you'll have to set things up on a server, but it's fun