模仿flask框架的核心功能,实现简易的服务器与框架

模仿flask框架的核心部分,写一个简易的框架和服务器,配置好之后能够实现简易的与浏览器交互(只支持post请求),实现数据库的增删改查,并响应给浏览器是没问题的,在之前的文章发过,关于flask框架的核心介绍,这里只提供相应的代码,到后期还会继续优化。

框架代码部分

# 创建字典用来动态添加请求路径的响应信息
dict_url = {}

# 利用装饰器传参来动态添加字典路径的key、value
def set_value(value):
    def set_fun(func):
        dict_url[value] = func
        def call_fun(*args, **kwargs):
            return func(*args, **kwargs)

        return call_fun

    return set_fun

def miniOption(rep_path):
    # 响应行
    response_line = "HTTP/1.1 200 ok\r\n"
    # 响应头
    response_head = ""
    # 空行
    response_empty = "\r\n"
    # try:
    print(rep_path)
    response_body = dict_url[rep_path](rep_path)

    return response_line, response_head, response_empty, response_body
#=====================================================================
# 一下部分写请求链接
# 格式
@set_value("/index.html")
def post(rep_path):
    with open('.'+rep_path, "r") as file:
        read = file.read()
    response_body = read
    return response_body

服务器代码部分

import socket

import re

from res_day_01.ServerHttpMiniWeb import mini_web


class SeverHttp(object):
    def __init__(self):
        # 创建套接字
        self.tcp_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        # 绑定本地信息
        self.tcp_socket.bind(("127.0.0.1", 8080))
        # 设为监听模式
        self.tcp_socket.listen()

    def start(self):
        while True:
            # 接收浏览器请求
            client, addr = self.tcp_socket.accept()
            # 处理浏览器请求
            self.option(client, addr)
            # 套接字不用关闭

    def option(self, client, addr):
        # 接收浏览器请求信息
        recv = client.recv(1024)
        # 判断信息是否为空
        if recv:
            recv = recv.decode("utf-8")
            search = re.search("/\S*", recv)
            # 判断匹配到的结果是否为空
            if search:
                self.rep_path = search.group()
                # 如果是空路径,则跳转到主页
                if self.rep_path == "/":
                    self.rep_path = "/index.html"
            else:
                client.close()
        else:
            client.close()


        print(self.rep_path)
        # 把请求信息分为静态资源(非html文件)和动态资源(html文件)两类,并分别处理
        if self.rep_path.endswith("html"):
            # 向框架内传入值,并接受响应的返回值
            response_line, response_head, response_empty, response_body = mini_web.miniOption(self.rep_path)
            # 响应信息
            response_info = response_line + response_head + response_empty + response_body
            # 向浏览器返回响应信息
            client.send(response_info.encode("utf-8"))
        else:
            # 响应行
            response_line = "HTTP/1.1 200 ok\r\n"
            # 响应头
            response_head = ""
            # 空行
            response_empty = "\r\n"

            try:
                with open("."+self.rep_path,"rb") as file:
                    file_read = file.read()
                response_body = file_read
            except Exception as e:
                print(e)
                response_line = "HTTP/1.1 404 not found\r\n"
                response_body = "this is error page".encode("utf-8")

            # 响应消息
            response_info = response_line.encode("utf-8") + response_head.encode("utf-8") + response_empty.encode("utf-8") + response_body
            # 向浏览器返回响应信息
            client.send(response_info)
        # 关闭套接字
        client.close()

def main():
    severhttp = SeverHttp()
    severhttp.start()


if __name__ == '__main__':
    main()
已标记关键词 清除标记
相关推荐
©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页