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 + '\r\n'

    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 + '\r\n' + 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', 所以这样肯定是不行的。等待更新。。。

转载于:https://www.cnblogs.com/PrettyTom/p/6741298.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值