Getting Started with Flask on a Raspberry Pi
This post assumes that you have already installed easy_install on your Pi.
First, create a folder for your projects, and one for this example:
> mkdir projects > cd projects > mkdir flask_first > cd flask_first
Next, to keep things clean, create a virtual environment for the python packages used in this example:
> sudo easy_install virtualenv
Once this package is available, create a virtual environment in a folder called
env inside the project folder:
> virtualenv env > mkdir src
After creating the virutal environment, activate it within the shell:
> source env/bin/activate
and with that, you are no longer using system wide packages, so that you don't create weird dependencies between projects. Virtualenv installs PIP in the environment, so use that to install Flask.
> pip install flask
Flask is a really nice micro-framework, that includes enough code to run a simple application without having to install it on a larger web server. For this post I will just use Flask as-is, without depending on another server.
Starting out with the simple "hello world" application from the Flask home page, create a file called hello.py and add the following code, slightly tweaked from the sample.
from flask import Flask app = Flask(__name__) @app.route("/") def hello(): return "Hello From Raspberry Pi Land!" if __name__ == "__main__": app.run()
You can now view your new application simply by using:
> python hello.py
But it will only be available on the raspberry pi itself, because the default server runs on the IP address 127.0.0.1. To fix this, we change the code a tad. Replace the call to
app.run() to include two arguments for the Pi's IP address and the port you want to use:
Now it will be available on the network.
Basically everything you would do on any Unix system to get flask going, is the same on the Pi. Truly fun and amazing for such a small package and smaller price.