programmerislam.wordpress.com

python programmer

setting up standalone python wsgi server for django app using tornado or fapws or gevent 18 December 2011

Filed under: python — S.M.A.H. @ 01:10
Tags: , ,

ok guys, today i will share with you how to up a standalone python wsgi server for django application using tornado or fapws or gevent server..let say i have a django project called myproject located in /home/project/ and the runserver.py script located in myproject folder

runserver.py for tornado wsgi server

import os, sys
import django.core.handlers.wsgi
from tornado import httpserver, ioloop, wsgi

def runserver():
    app_dir = os.path.abspath(os.path.dirname(__file__))
    sys.path.append(os.path.dirname(app_dir))
    os.environ['DJANGO_SETTINGS_MODULE'] = 'myproject.settings'
    application = django.core.handlers.wsgi.WSGIHandler()

    container = wsgi.WSGIContainer(application)
    server = httpserver.HTTPServer(container)
    server.listen(80)
    try:
        ioloop.IOLoop.instance().start()
    except KeyboardInterrupt:
        sys.exit(0)

if __name__ == '__main__':
    runserver()

then, run the script : python /home/project/myproject/runserver.py

runserver.py for fapws wsgi server

import os, sys
import fapws._evwsgi as evwsgi
from fapws import base
from fapws.contrib import django_handler

def runserver():
    app_dir = os.path.abspath(os.path.dirname(__file__))
    sys.path.append(os.path.dirname(app_dir))
    os.environ['DJANGO_SETTINGS_MODULE'] = 'myproject.settings'

    def application(environ, start_response):
        response = django_handler.handler(environ, start_response)
        return [response]

    evwsgi.start('0.0.0.0', '80')
    evwsgi.set_base_module(base)
    evwsgi.wsgi_cb(('', application))
    evwsgi.set_debug(0)
    try:
        evwsgi.run()
    except KeyboardInterrupt:
        sys.exit(0)

if __name__ == '__main__':
    runserver()

then, run the script : python /home/project/myproject/runserver.py

runserver.py for gevent wsgi server

import os, sys
import django.core.handlers.wsgi
from gevent import wsgi

def runserver():
    app_dir = os.path.abspath(os.path.dirname(__file__))
    sys.path.append(os.path.dirname(app_dir))
    os.environ['DJANGO_SETTINGS_MODULE'] = 'myproject.settings'
    application = django.core.handlers.wsgi.WSGIHandler()

    server = wsgi.WSGIServer(('', 80), application, spawn = None)
    try:
        server.serve_forever()
    except KeyboardInterrupt:
        server.stop()
        sys.exit(0)

if __name__ == '__main__':
    runserver()

then, run the script : python /home/project/myproject/runserver.py

**this three servers gives better performance and low memory usage than apache with mod_wsgi server..
for production use, the script should be run as service