WSGI(Web Server Gateway Interface, Web服务器网关接口)

Django框架是应用程序,负责业务逻辑,本身没有服务器程序功能。现有有很多优秀的服务器程序 例如 uwsgi、Gunicorn。而Web应用框架和服务器程序进行配合使用就需要遵循一定的规范(就比如图中的桥梁部分)。而这个规范就是WSGI
WSGI(Web Server Gateway Interface, Web服务器网关接口) 就是一种规范,

它定义了使用Python编写的web应用程序与web服务器程序之间的接口格式,实现web应用程序与web服务器程序间的配合

 

WSGI(Web Server Gateway Interface, Web服务器网关接口)

服务器和应用框架都遵循了WSGI协议后,就可以任意组合了更加灵活。

而Python标准库提供的独立WSGI服务器叫wsgiref,Django开发环境用的就是这个模块来做服务器。

简单使用wsgiref模块

import socket, time

# 1.导入模块

from wsgiref.simple_server import make_server





def index2(url):

    with open('index2.html', mode='r', encoding='UTF-8') as f:

        data = f.read()

        data = data.replace('xxooxx', str(time.time()))

        data = bytes(data, encoding='utf-8')

    return data





url_func_lst = [

    ('/index2', index2),

]





def server(environ, start_response):

    """

    :param environ:字典类型,封装了一些内容,其中包括URL请求路径。参数名称任意

    :param start_response: 是一个函数地址,返回响应头。名称任意

    :return:列表类型, 返回响应体内容。

    """

    print('-->>>', environ)

    # 封装响应头信息,服务器程序自动调用

    start_response('200 OK', [('Content-Type', 'text/html;charset=utf-8')])

    # 取到用户输入的url

    url = environ['PATH_INFO']

    func = None

    for url_func in url_func_lst:

        if url_func[0] == url:

            func = url_func[1]

    if func:

        response = func(url)

    else:

        response = b'404 not found...'



    return [response, ]





# 2.使用

if __name__ == '__main__':

    # 设置ip和端口号,以及要调用的函数名称,名称任意。

    httpd = make_server('127.0.0.1', 9999, server)

    print('1111')

    # 永远开启,代替了while 死循环

    httpd.serve_forever()

    print('222')