如何用uwsgi+nginx启动一个纯手撸的wsgi程序

最近看了一下wsgi的规范,发现其实简单的实现web程序其实不用框架也是非常简单的,框架的底层也是用的wsgi的规范进行编写的。

看一段非常搓的代码

[root@localhost webpy]# pwd
/data/webpy
[root@localhost webpy]# cat hello.py
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
import re
import sys
reload(sys)
sys.setdefaultencoding( "utf-8" )

def root(environ):
    outdata = {
        "msg":"root",
        "status":200,
    }
    return outdata

def hello(environ):
    outdata = {
        "msg":"hello",
        "status":200,
    }
    return outdata

urls=[
    ("/",root),
    ("/hello/",hello)
]



def application(environ, start_response):
    method = environ['REQUEST_METHOD']
    path = environ['PATH_INFO']

    print "当前请求:",path

    for pattern, name in urls:
        m = re.match('^' + pattern + '$', path)
        print "本次匹配:",pattern
        if m:
            print "匹配成功:",m.group()
            view = name(environ)
            start_response('%s OK'%view['status'], [('Content-Type', 'text/html')])
            return view['msg']

    start_response('404 OK', [('Content-Type', 'text/html')])
    return "404"

application

然后配置下uwsgi

[root@localhost webpy]# cat /etc/uwsgi/uwsgiconfig.ini
[uwsgi]
socket = 127.0.0.1:8100
#app目录
base = /data/webpy/
pythonpath = %(base)
pidfile = /run/uwsgi/run.pid
memory-report = true
master = true
processes = 4
threads = 2
#入口脚本
wsgi-file = %(base)hello.py
#实例名称
callable = application
daemonize=/var/log/uwsgi.log

配置完成后启动uwsgi程序

[root@localhost webpy]# uwsgi /etc/uwsgi/uwsgiconfig.ini
[root@localhost webpy]# ps -ef|grep uwsgi
root      6970     1  0 May28 ?        00:00:24 uwsgi /etc/uwsgi/uwsgiconfig.ini
root      6971  6970  0 May28 ?        00:00:00 uwsgi /etc/uwsgi/uwsgiconfig.ini
root      6972  6970  0 May28 ?        00:00:00 uwsgi /etc/uwsgi/uwsgiconfig.ini
root      6973  6970  0 May28 ?        00:00:00 uwsgi /etc/uwsgi/uwsgiconfig.ini
root      6974  6970  0 May28 ?        00:00:00 uwsgi /etc/uwsgi/uwsgiconfig.ini
root     12427 11572  0 23:55 pts/0    00:00:00 grep --color=auto uwsgi

配置完成uwsgi程序后,需要配置nginx与uwsgi做对接

nginx 配置相对简单,就只给location的配置片段吧
        location / {
        include        uwsgi_params;
            uwsgi_pass     127.0.0.1:8100;
            root   html;
            index  index.html index.htm;
        }

配置完成后启动下nginx就ok啦,然后访问吧

如何用uwsgi+nginx启动一个纯手撸的wsgi程序_第1张图片
root
如何用uwsgi+nginx启动一个纯手撸的wsgi程序_第2张图片
hello

你可能感兴趣的:(如何用uwsgi+nginx启动一个纯手撸的wsgi程序)