Nginx+FastCGI+Python

來源:互聯網
上載者:User

網上更多文章是用Django、webpy等架構的前提下,由於我只是用其CGI而不是搞純web開發,所以暫時不打算用這類架構,直接用flup包(其實大多數架構WSGI也是封裝的flup)。

廢話不多說,進入正題,先看下需要的環境和工具:

1、Linux2.6(廢話- -!)

2、Nginx(需包含fastcgi模組)

3、Spawn-fcgi (官方下載:http://redmine.lighttpd.net/projects/spawn-fcgi/wiki)

4、Python

5、flup(官方下載:http://trac.saddi.com/flup)

安裝都是些常規方法,就不一一介紹了

nginx的fastcgi配置照搬php的即可。

先上張簡單畫的原理圖

spawn-fcgi是個工具,用來以fastcgi方式開啟多個WSGIServer進程。

例:

spawn-fcgi -f /data/WSGIServer.py -a 127.0.0.1 -p 5678 -u www -F 5

-f WSGIServer指令碼的決定路徑

-a fastcgi綁定的ip

-p fastcgi綁定的連接埠

-u 已什麼身份運行

-F 要啟動的進程數(很多人以為是-C,其實那是PHP專用的,這裡要用-F)

 

需要編碼的部分就是WSGIServer這裡了,貼個簡單測試代碼

 

#!/usr/bin/env python# -*- coding: utf-8 -*-import flup.server.fcgi as flupsdef application(environ, start_response):    """該函數可以寫成模組import匯入"""    ret = ""    try:        uri = environ['PATH_INFO']        if uri[-1] == "/":            uri = uri[:-1]                    if uri == "":            ret = str(environ)        elif uri == "/sleep":            import time            time.sleep(5)            ret = "sleep: 5 secends"        else:            ret = uri                except Exception, e:            ret = str(e)            status = '200 OK'    response_headers = [('Content-type','text/plain')]    start_response(status, response_headers)    return [ret]if __name__ == "__main__":    #直接用python運行    #flups.WSGIServer(application, multithreaded=True, multiprocess=False, bindAddress=('127.0.0.1', 5678)).run()    #fastcgi方式運行    flups.WSGIServer(application).run()

厄,就到這裡吧~

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.