Web Development With Flask

What is Flask?

  • A Python microframework for building web applications
  • Simple, easy to use
  • Can write APIs or process templates
  • Basically, we write server-side code with Python!

What are we doing?

  • This is a hackathon!
  • Our goal is to achieve a starting point for an application
  • After this workshop, you will have
    • A basic understanding of Flask
    • A running Flask application that can be extended
    • Understanding of how to seek help with Flask

 

Requirements

  • Basic Python knowledge
  • No fear of running instructions on the command line
  • Sublime Text or another text editor
  • The desire to learn

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 run
command 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

  • Flask is a microframework, so it is best for small apps
  • We currently don't have users, authentication
  • Database support is possible, but not simple

Next Steps

  • You now have a few working examples
  • Work with these examples to build a more complex app
  • Need inspiration? Find a public API:
    • https://github.com/toddmotto/public-apis
  • Use the Flask documentation!
    • http://flask.pocoo.org/docs/

Get Hacking!

  • This presentation is available on GitHub
    • https://github.com/jamiecounsell/flask-demo
Made with Slides.com