02 May 2013

I am gonna to deploy a simple web server on my raspberry pi, cause the pi's resource has limitation.
So I use the following lightweight package:
  1. Flask is a microframework for Python
  2. Nginx is a fast and lightweight web server for serving static files. (like image, html, css...etc)
  3. uWSGI:Unfortunately Nginx can't not be used for serving dynamic language. (like php, python.)  Therefore python needs to depend on uWSGI to interact with Nginx.


1. Installation
apt-get install nginx # install nginx
apt-get install uwsgi # instal uwsgi
apt-get install uwsgi-plugin-python # cause uwsgi can support many language so we need to indicate which lanague we want to use.
apt-get install python-flask # install flask


2. Configuration
# config nginx
cd /etc/nginx/sites-available/
vim default

Please paste the following config to your config file.
server {
listen 80; ## listen for ipv4; this line is default and implied
server_name ken;
keepalive_timeout 300;
location / {
include uwsgi_params;
uwsgi_pass unix:///tmp/uwsgi.sock;
uwsgi_param UWSGI_PYHOME /var/www; # your web application's path
uwsgi_param UWSGI_CHDIR /var/www; # your web application's path
uwsgi_param UWSGI_MODULE api; # Main dispatcher ( so we will have api.py )
uwsgi_param UWSGI_CALLABLE app;
}
error_page 404 /404.html;
}



# config uwsgi
cd /etc/uwsgi/apps-available/
vim uwsgi.conf

Please paste the following config to your config file.
[uwsgi]                                                                                                                    
plugins=python ; support python
vhost=true
socket=/tmp/uwsgi.sock
chmod-socket = 666 ; the socket permission
uid=root
gid=root


# make a soft link
ln -s /etc/uwsgi/apps-available/uwsgi.conf /etc/uwsgi/apps-enabled/uwsgi.ini




3. Implement the dispatcher

vim /var/www/api.py   # implement the dispatcher 


api.py
from flask import Flask,jsonify                                                                                            

app = Flask(__name__)

@app.route("/hello")
def hello():
result = {'msg':'Hello World!'}
return jsonify(result)

@app.route("/")
def index():
result = {'msg':'Index!'}
return jsonify(result)

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

# restart service
service nginx restart
service uwsgi restart



4. verify

1. open browser
2. key in your ip
      ex: http:192.169.1.1/
3. your will see
{
"msg": "Index!"
}










blog comments powered by Disqus