WSGl协议和web服务器框架

一、WSGI协议概念
  1.WSGI含义:
    WSGI(Web Server Gateway Interface):Web服务器网关接口。
  2.作用:
    可以很好使web框架与Web服务器进行分离。也就是说服务器只管与客户端连接,而具体的逻辑代码由框架来完成!可以达到分工合作的目的

二、定义WSGI接口
  定义WSGI的接口非 使服务能够达到VSGL协议:

# 定义WSGl接口:、
#     1 实现applicattion()函数
def application(environ, start_response):
    start_response('200 OK', [('Content-Type', 'text/html')])
    return "hello gwl"

environ:是从服务器发送到框架的字典类型的数据;

start_response:是在服务器中定义的函数,在框架中进行调用;

第一个参数是HTTP响应状态码;

第二个参数是响应体中的每个字段信息。

服务器实现:

import socket
import re
import miniWebwindow.mini_application
import sys


class sever():
    def __init__(self, post):
        # 1、创建套接字
        self.tcp_seven_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        # 重复利用端口
        self.tcp_seven_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        # 2、绑定端口
        self.tcp_seven_socket.bind(("", post))
        # 3、变为监听套接字
        self.tcp_seven_socket.listen(128)

    def Serving_customers(self,new_ip):
        """为客户端返回数据"""
        # 1、接收浏览器发送过来的请求,即HTTP请求
        # GET / HTTP/1.1
        request = new_ip.recv(1024).decode("utf-8")
        # print(request)
        request_lines = request.splitlines()
        # print("")
        # print(">" * 20)
        print(request_lines)
        # GET / HTTP/1.1
        file_name = ""
        ret = re.match(r"[^/]+(/[^ ]*)", request_lines[0])
        if ret:
            file_name = ret.group(1)
            # print("*" * 50, file_name)
            if file_name == "/":
                file_name = "/index.html"
        if not file_name.endswith(".py"):
            try:
                f = open("./python中文帮助文档" + file_name, "rb")
            except BaseException:
                response = "HTTP/101  404 NOT FOUND\r\n"
                response += "\r\n"
                response += "---file not found"
                new_ip.send(response.encode("utf-8"))
            else:
                html_read = f.read()
                f.close()
                # 2、返回http格式的数据,给浏览器
                # 2. 1、准备发送数据---header
                response = "HTTP/1.1 200 OK\r\n"
                response += "\r\n"
                # 2.2、准备发送数据给浏览器---boy
                # response += "<h1>hhhh</h1>"
                new_ip.send(response.encode("utf-8"))
                new_ip.send(html_read)
        else:
            # body = "gwl %s " % time.ctime()
            # response = header + body

            env = dict()
            env['PATH_INFO'] = file_name
            print(env['PATH_INFO'])
            body = miniWebwindow.mini_application.application(env, self.set_response_header)
            header = "HTTP/1.1 %s\r\n" % self.status
            for tmp in self.headers:
                # print(tmp)
                header += "%s:%s \r\n" % (tmp[0], tmp[1])

            header += "\r\n"

            html = header + body
            print(html)
            new_ip.send(html.encode("utf-8"))

        new_ip.close()

    def set_response_header(self, status, headers):
        self.status = status
        self.headers = headers

    def main(self):

        while True:
            # 等待客户端的链接 accept
            new_ip, new_post = self.tcp_seven_socket.accept()
            # 为这个客户服务
            self.Serving_customers(new_ip)

        self.tcp_seven_socket.close()
if __name__ == '__main__':
    w = sever(7890)
    w.main()


# def run():
#     if len(sys.argv) == 2:
#         try:
#             post = int(sys.argv[1])
#         except Exception as f:
#             print("请按照以下方式运行\npython3 xxx.py 端口号")
#             return
#     else:
#         print("请按照以下方式运行\npython3 xxx.py 端口号")
#         return
#     w = sever(post)
#     w.main()
#
# if __name__ == '__main__':
#     run()

服务器实现WSGL接口程序:

def index():
    return "这是主页"

def login():
    return "这是登入页面"

# 判断请求的页面
URL_FUNC_DICT = {
    "/index.py": index,
    "/login.py": login

}
# 实现WSGL协议的接口
def application(environ, start_response):
    start_response('200 OK', [('content-Type', 'text/html; charset=utf-8'), ('server','miniweb框架v0')])
    file_name = environ['PATH_INFO']

    # if file_name == '/index.py':
    #     return index()
    # elif file_name == '/login.py':
    #     return login()
    # else:
    #     return 'hello gwl 天气真不错'
    func = URL_FUNC_DICT[file_name]
    return func()

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值