• python之web框架(2):了解WSGI接口


    python之web框架(2):了解WSGI接口

    1.什么是wsgi接口:

    • wsgi:Web Service Gateway Interface。它不是模块,而只是一种规范,方便web服务器和各种框架都能契合。
    
    response_body = application(env, start_response)
    
    # response_body是返回值,返回值为web服务器响应数据的body。
    
    # application可执行的函数(或类)
    
    # env是一个字典,需要传入用户的请求数据。
    
    # start_response是一个函数,需要传入2个参数。
    # 参数1.status:响应体的状态,‘200 OK’ 和 ‘404 not found’这类。
    # 参数2.head_list:响应体的头部,是列表,列表中再嵌元组,元组内容是key value的形式。
    
    

    2.动手写个用到wsgi接口的web服务器:

    #!/usr/bin/env python3
    # coding:utf-8
    
    from socket import *
    from multiprocessing import Process
    
    
    def app(env, start_response):
        status = '200 OK'
        head_list = [("name", "wanghui")]
        start_response(status, head_list)
        return '<h1>hello world</h1>'
    
    
    class MyWebServer(object):
        def start_response(self, status, head_list):
            self.response_head = 'HTTP/1.1' + status + '
    '
    
        def deal(self, conn):
            recv_data = conn.recv(1024).decode('gb2312')
            recv_data_head = recv_data.splitlines()[0]
            print('------', recv_data_head)
            request_method, request_path, http_version = recv_data_head.split()
            request_path = request_path.split('?')[0]  # 去掉url中的?和之后的参数
            env = {'request_method':request_method, 'request_path':request_path}
    
            # 这里是wsgi接口调用的地方
            response_body = app(env, self.start_response)
    
            response_data = self.response_head + '
    ' + response_body
            send_data = response_data.encode('utf-8')
            conn.send(send_data)
    
        def __init__(self):
            self.s = socket(AF_INET, SOCK_STREAM)
            self.s.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)
            self.s.bind(('',8000))
            self.s.listen(1023)
    
        def start(self):
            while 1:
                conn, user_info = self.s.accept()
                print(user_info)
                p = Process(target=self.deal, args=(conn,))
                p.start()
                conn.close()  # 进程会复制出一个新的conn,所以这里的conn需要关闭
    
    
    s = MyWebServer()
    s.start()
    
    
    • 这个WebSever的功能实在太low,只能回应一个固定的页面,就是'hello word', 所以这样肯定是不行的。等待更新。。。

  • 相关阅读:
    DRF项目创建流程(1)
    RESTful API规范
    超哥笔记--shell 基本命令(4)
    转:django模板标签{% for %}的使用(含forloop用法)
    自定django登录跳转限制
    jquery Ajax应用
    js重定向跳转页面
    django项目mysql中文编码问题
    python进阶(六) 虚拟环境git clone报错解决办法
    Linux基础(六) Vim之vundle插件
  • 原文地址:https://www.cnblogs.com/PrettyTom/p/6741298.html
Copyright © 2020-2023  润新知