Dev: Flask Intro 1

Recently, I attended a Python Meetup. The first presenter was Carter Rabasa from Twilio. He gave two short demos of Flask. From the site:

Flask is a microframework for Python based on Werkzeug, Jinja 2 and good intentions.

More specifically, it’s a micro web framework.
The alternative would be Django, a full server side MVC web framework.

This motivated me to run out and buy the book, “Flask Web Development” by Miguel Grinberg. This blog series will follow my experiments between the book, external sources like Carter’s open source code, and anything else I might fancy. My bigger motivation here is to see if Flask can help shrink the code footprint of a standard REST interface. I have done these in C# and while I appreciate the larger frameworks, I often find their a bit overkill for my needs. Particularly with a current trend in business shifting us towards Micro-Services. This slide from the presentation sort of explain what I mean:
Snip20141124_1

First thing first: Running Flask on your dev machine.

Setting up your Virtual Environment on OS X:


sudo easy_install virtualenv
sudo mkdir flask_test
cd flask_test
virtualenv venv
source venv/bin/activate
(venv) pip install flask

That installs VirtualEnv. From the site:

virtualenv is a tool to create isolated Python environments.

Best to keep it clean. As an aside; if you need more than this, you might look to Vagrant.
Then you make a directory, startup a virtual environment, start it, and finally install flask.
You’re now ready to write the obligatory hello world:

Open an text editor (like SublimeText) and let’s put this code in:


from flask import Flask
app = Flask(__name__)

@app.route('/')
def index():
  return '<h1>Heyas world</h1>'

@app.route('/user/<name>')
def user(name):
  return '<h1>Heyas, %s.</h1>' % name

if __name__ == '__main__':
  app.run(debug=True)

Save that as flask01.py.

So what’s happening here:
Importing the Flask library and creating an app. If you’re familiar with Express, it’s similar.
Then you define two routes. First to take handle addresses to the base URL; Second to show dynamic routes.
Then we run the app.

Back in your terminal:


(venv) python flask01.py

That should run your site:
Snip20141124_4

Snip20141124_5

Snip20141124_6

With the debugging you should be able to watch some logging happen of HTTP error codes as you try out your site:
Snip20141124_7

Okay there’s step 1.

Leave a comment


Name*

Email(will not be published)*

Website

Your comment*

Submit Comment

© Copyright Duke Hall - Designed by Pexeto