Tag Archives: REST

Coding with Flask and SQLAlchemy

On my previous post, I’ve been working with Flask,SQLAlchemy, and Gnunicorn for some REST API.

Setting up virtualenv with the following pip requirements.

Flask==0.6.1
Flask-SQLAlchemy==0.11
Jinja2==2.5.5
LEPL==5.0.0
MySQL-python==1.2.3
SQLAlchemy==0.6.6
Werkzeug==0.6.2
distribute==0.6.10
gevent==0.13.4
greenlet==0.3.1
gunicorn==0.12.1
lockfile==0.9.1
wsgiref==0.1.2
yolk==0.4.1

The model.py:

from flask import Flask
from flaskext.sqlalchemy import SQLAlchemy
from sqlalchemy import Table, Column, Integer, String, Date, Float 
import config  

# DB class 
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] =  config.DB_URI
db = SQLAlchemy(app)

# DB classess 
class Player(db.Model):
    __tablename__ = 'player'

    playerid = db.Column('playerid', Integer, primary_key=True)
    username = db.Column('username', String(30), unique=True)
    email = db.Column('email', String(50), unique=True)
    password = db.Column('password', String(100), unique=False)
    avatarid = db.Column('avatarid', Integer,default=1)
    language = db.Column('language', Integer,default=1)
    regdate = db.Column('regdate', Date)
    activation_key = db.Column('activation_key', String(60))
    active = db.Column('active', Integer, default=0)

    def __init__(self, username=None, email=None,password=None):
	    self.username = username
	    self.email = email
	    self.password = password 

    def __repr__(self):
	    return '<player %s %s>' % (self.username, self.email)

Continue reading

Running Flask with Gunicorn

Been playing with Python Flask writing some backend REST API for our game backend.
Trying to work on deploying the API using Gunicorn using gevent

sudo apt-get install libevent-1.4-2
sudo apt-get install libevent-dev

easy_install greenlet
easy_install gevent

My Gunicorn config file:

$ cat gunicorn.py 

import os

def numCPUs():
    if not hasattr(os, "sysconf"):
        raise RuntimeError("No sysconf detected.")
    return os.sysconf("SC_NPROCESSORS_ONLN")

bind = "0.0.0.0:8000"
workers = numCPUs() * 2 + 1
backlog = 2048
#worker_class ="sync"
worker_class =  "gevent" 
debug = True
daemon = True
pidfile ="/tmp/gunicorn.pid"
logfile ="/tmp/gunicorn.log"

Running the Flask Application:

$ gunicorn -c gunicorn.py mp:app 
$ tail /tmp/gunicorn.log
2011-04-19 10:33:40 [1594] [INFO] Starting gunicorn 0.12.1
2011-04-19 10:33:40 [1594] [INFO] Listening at: http://0.0.0.0:8000 (1594)
2011-04-19 10:33:40 [1594] [INFO] Using worker: gevent
2011-04-19 10:33:40 [1595] [INFO] Booting worker with pid: 1595
2011-04-19 10:33:40 [1596] [INFO] Booting worker with pid: 1596
2011-04-19 10:33:40 [1597] [INFO] Booting worker with pid: 1597

Woops.. seems working.
Time to run load testing with ab and siege.