从wsgi规范说起

来源:互联网 发布:kmeans算法介绍 编辑:程序博客网 时间:2024/06/10 15:04

说到用python做web开发,就绕不开wsgi协议。wsgi协议在python pep-333中定义的
https://www.python.org/dev/peps/pep-0333/
上面是wsgi规范的官方描述,wsgi的主要作用是定义的python如何跟web服务器进行交互的。作用类似于cgi或fast-cgi的作用。django框架就是一种遵循wsgi协议的框架。
wsgi的具体内容此处不细说。下面主要要实现一个遵循wsgi程序的几个要点。

根据规范是实现了一个wsgi协议的程序必须要给服务器返回一个可调用的对象,既然是一个可调用的对象,比如可以返回一个函数 或者一个实现了call()方法的类对象,在django中就是一个实现了call方法的类对象。而这个方法需要接受两个参数,一个是 environ 参数 environ 参数是一个字典类型的数据结构,主要是当前一次请求的服务器环境参数 以及当前的http请求的协议头部分的内容 比如path_info method cookie 等等
第二个参数是一个回调函数 start_response ,该函数有两个参数,第一个参数表示要返回的http协议状态码,比如当前请求处理成功,则返回200 错误返回400等,第二个参数是返回结果的http的头部要填充的内容,是一个list类型对象。该回调函数必须在返回结果内容之前调用。
最后应用程序返回要发送到客户端的数据,返回的形式必须是一个可迭代的数据,比如一个list对象 或yeld生成器对象

应用举例
在python标准库中 有一个wsgiref 使用该模块可以迅速生成一个遵循wsgi协议的web服务器。
下面是官方示例 实现了一个简单的webserver

from wsgiref.simple_server import make_server# Every WSGI application must have an application object - a callable# object that accepts two arguments. For that purpose, we're going to# use a function (note that you're not limited to a function, you can# use a class for example). The first argument passed to the function# is a dictionary containing CGI-style envrironment variables and the# second variable is the callable object (see PEP 333).def hello_world_app(environ, start_response):    status = '200 OK' # HTTP Status    headers = [('Content-type', 'text/plain')] # HTTP Headers     start_response(status, headers) #在返回结果之前必选先调用start_response这个回调函数 第一个参数是返回的状态吗 第二个参数是返回的header内容    # The returned object is going to be printed        return ["Hello World"]          #此处返回的是一个list对象 因为list是可迭代的 所以满足wsgi规范#函数 hello_world_app 就是规范里面要求的可调用对象httpd = make_server('', 8000, hello_world_app)print "Serving on port 8000..."# Serve until process is killedhttpd.serve_forever()

用django创建项目以后 项目中会有一个wsgi.py文件 通常内容如下

"""WSGI config for tblog project.It exposes the WSGI callable as a module-level variable named ``application``.For more information on this file, seehttps://docs.djangoproject.com/en/1.7/howto/deployment/wsgi/"""import osos.environ.setdefault("DJANGO_SETTINGS_MODULE", "tblog.settings")from django.core.wsgi import get_wsgi_applicationapplication = get_wsgi_application()

代码里面 ‘application ‘就是wsgi协议中需要的可调用对象.

0 0
原创粉丝点击