WSGI--python web服务器接口

2020-08-19  本文已影响0人  Cassie测试路

WSGI简介

WSGI:Web Server Gateway Interface是python web服务器网关接口。python程序只需要通过WSGI接口就可以创建一个web服务器,用于建立TCP连接、接收客户端的HTTP请求、解析HTTP请求、然后发送HTTP响应给客户端。这样开发者不用关注底层实现,只需要专注于生成的HTML内容即可。

WSGI接口编程

# wsgi_application.py
# application()函数就是符合WSGI标准的一个HTTP处理函数,它接收两个参数:
# environ:一个包含所有HTTP请求信息的dict对象;
# start_response:一个发送HTTP响应的函数。
# start_response()发送响应头,函数的返回值b'<h1>Hello, web!</h1>'将作为HTTP响应的Body发送给浏览器

def application(environ, start_response):
    start_response("200 OKKK", [('Content-Type', 'text/html')])
    response_body = '<h1>Hello, %s!</h1>' % (environ['PATH_INFO'][1:] or 'web')
    # return [b'<h1>Hello, web!</h1>']
    return [response_body.encode('utf-8')]
# wsgi_server.py
# web服务器接收HTTP请求
from wsgiref.simple_server import make_server
from wsgi_application import application

# 创建一个web服务器,IP地址为空,端口是8000,处理请求的函数是application
httpd = make_server('', 8000, application)
print('Server HTTP on port 8000...')

# 监听请求
httpd.serve_forever()
HTTP请求 Django框架封装的wsgi服务器
上一篇 下一篇

猜你喜欢

热点阅读