What is Flask?
What are we doing?
Requirements
A Basic Flask app
from flask import Flask
app = Flask("My Application")
@app.route("/")
def hello():
return "Hello World!"
if __name__ == "__main__":
app.run()simple.py
Running our app
# Set app in Windows
$ set FLASK_APP=simple.py
# Set app in MacOSX/Linux
$ export FLASK_APP=simple.py
# Run (both)
$ flask runcommand line
result
Running our app
In Chrome
A More Complex Flask app
from flask import Flask
app = Flask("My Application")
@app.route("/user/<username>")
def hello(username):
return "This is " + username + "'s page."
if __name__ == "__main__":
app.run()less_simple.py
Rendering Templates
from flask import Flask, render_template
app = Flask("My Template Application")
@app.route("/user/<username>")
def hello(username):
return render_template('hello.html', username=username)
if __name__ == "__main__":
app.run()templates/hello.html
<!DOCTYPE html>
<html>
<head>
<title>Hello {{username}}</title>
</head>
<body>
<h1>Hello {{username}}</h1>
</body>
</html>template_example.py
Reaching an API
from flask import Flask, render_template
import urllib2, json
app = Flask("My API Application")
API_ROOT = "http://api.icndb.com/"
@app.route("/norris/<category>")
def norris(category):
url = API_ROOT + "jokes/random?limitTo=[" + category + "]"
req = urllib2.urlopen(url)
answer = json.loads(req.read())
return render_template("api_info.html", **answer)
if __name__ == "__main__":
app.run()templates/api_info.html
<!DOCTYPE html>
<html>
<head>
<title>API Data</title>
</head>
<body>
<h5>Joke search: {{type}}</h5>
<p>{{value.joke}}</p>
<small>Categories: {{",".join(value.categories)}}
</body>
</html>api_example.py
Limitations
Next Steps
Get Hacking!