wsgi介绍与使用

论坛 期权论坛 脚本     
匿名网站用户   2020-12-20 03:31   92   0

介绍

wsgi server

wsgi规定符合wsgi规范的wsgi服务器需要完成以下事情:

  • 接收来自HTTP客户端的request请求
  • 按照wsgi规范调用wsgi应用程序
  • 把处理好的结果返回给客户端

wsgi application

wsgi规定wsgi应用程序是一个callable对象,当有请求过来时,wsgi服务器 会调用这个wsgi应用程序

wsgi 应用程序可以是:

  • 方法
  • 函数
  • 实现了__call__方法的一个类的实例
  • 一个类,用这个类生成实例的过程就相当于调用这个类

接受参数:environ,start_response,exc_info(可选)

返回值:一个iterator对象,这个iterator就是repsonse body

wsgi middleware

中间件是为了是应用程序有额外的行为而存在的。 中间件可以随便决定是否放在程序的前面。否则就布时中间件而是程序的一部分

使用

app.py

def application(environ, start_response):
  start_response('200 OK',  [('Content-Type','text/html')])
  return '<h1> hello {}</h1>'.format(environ["PATH_INFO"][1:] or "World"))

server.py

from wsgiref.simple_server import make_server
from app import application

#创建一个http服务器,ip地址为空,端口:8888,调用函数application
httpd = make_server('',8888, application)
print("HTTP Server starting on port 8888 ...")

# 开始监听http请求
httpd.serve_forever()

启动wsgi server

python server.py

访问地址

http://127.0.0.1:8888/magicops

返回内容

Hello magicops

WSGI参考:https://www.python.org/dev/peps/pep-3333/

wsgiref参考:https://pypi.org/project/wsgiref/

分享到 :
0 人收藏
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

积分:1136255
帖子:227251
精华:0
期权论坛 期权论坛
发布
内容

下载期权论坛手机APP