>  기사  >  백엔드 개발  >  Python을 사용하여 사용자 정의 웹 프레임워크를 개발하는 방법

Python을 사용하여 사용자 정의 웹 프레임워크를 개발하는 방법

WBOY
WBOY앞으로
2023-05-17 10:46:111272검색

사용자 정의 웹 프레임워크 개발

웹 서버로부터 동적 리소스 요청을 수신하고 동적 리소스 요청을 처리하기 위한 서비스를 웹 서버에 제공합니다. 요청한 리소스 경로의 접미사 이름을 기준으로 결정:

요청한 리소스 경로의 접미사 이름이 .html인 경우 동적 리소스 요청이므로 웹 프레임워크 프로그램에서 처리하도록 합니다.

그렇지 않으면 정적 리소스 요청이므로 웹 서버 프로그램에서 처리하도록 하세요.

1. 웹 서버의 기본 프로그램을 개발합니다

1. 클라이언트 HTTP 요청을 수락합니다(하위 계층은 TCP입니다)

# -*- coding: utf-8 -*-
# @File  : My_Web_Server.py
# @author: Flyme awei 
# @email : 1071505897@qq.com
# @Time  : 2022/7/24 21:28


from socket import *
import threading


# 开发自己的Web服务器主类
class MyHttpWebServer(object):

    def __init__(self, port):
        # 创建 HTTP服务的 TCP套接字
        server_socket = socket(AF_INET, SOCK_STREAM)
        # 设置端口号互用,程序退出之后不需要等待,直接释放端口
        server_socket.setsockopt(SOL_SOCKET, SO_REUSEADDR, True)
        # 绑定 ip和 port
        server_socket.bind(('', port))
        # listen使套接字变为了被动连接
        server_socket.listen(128)
        self.server_socket = server_socket

    # 处理请求函数
    @staticmethod  # 静态方法
    def handle_browser_request(new_socket):
        # 接受客户端发来的数据
        recv_data = new_socket.recv(4096)
        # 如果没有数据,那么请求无效,关闭套接字,直接退出
        if len(recv_data) == 0:
            new_socket.close()
            return
            
# 启动服务器,并接受客户端请求
    def start(self):
        # 循环并多线程来接收客户端请求
        while True:
            # accept等待客户端连接
            new_socket, ip_port = self.server_socket.accept()
            print("客户端ip和端口", ip_port)
            # 一个客户端的请求交给一个线程来处理
            sub_thread = threading.Thread(target=MyHttpWebServer.handle_browser_request, args=(new_socket, ))
            # 设置当前线程为守护线程
            sub_thread.setDaemon(True)
            sub_thread.start()  # 启动子线程


# Web 服务器程序的入口
def main():
    web_server = MyHttpWebServer(8080)
    web_server.start()


if __name__ == '__main__':
    main()

2. 요청이 정적 리소스인지 동적 리소스인지 확인합니다

 # 对接收的字节数据进行转换为字符数据
        request_data = recv_data.decode('utf-8')
        print("浏览器请求的数据:", request_data)
        request_array = request_data.split(' ', maxsplit=2)

        # 得到请求路径
        request_path = request_array[1]
        print("请求的路径是:", request_path)
        if request_path == "/":
            # 如果请求路径为根目录,自动设置为:/index.html
            request_path = "/index.html"
        # 判断是否为:.html 结尾
        if request_path.endswith(".html"):
            "动态资源请求"
           pass
        else:
            "静态资源请求"
            pass

정적 리소스를 처리하려면?

Python을 사용하여 사용자 정의 웹 프레임워크를 개발하는 방법

"静态资源请求"
            # 根据请求路径读取/static 目录中的文件数据,相应给客户端
            response_body = None  # 响应主体
            response_header = None  # 响应头的第一行
            response_first_line = None  # 响应头内容
            response_type = 'test/html'  # 默认响应类型
            try:
                # 读取 static目录中相对应的文件数据,rb模式是一种兼容模式,可以打开图片,也可以打开js
                with open('static'+request_path, 'rb') as f:
                    response_body = f.read()
                if request_path.endswith('.jpg'):
                    response_type = 'image/webp'

                response_first_line = 'HTTP/1.1 200 OK'
                response_header = 'Content-Length:' + str(len(response_body)) + '\r\n' + \
                                  'Content-Type: ' + response_type + '; charset=utf-8\r\n' + \
                                  'Date:' + time.strftime('%Y-%m-%d %H:%M:%S', time.localtime()) + '\r\n' + \
                                  'Server: Flyme awei Server\r\n'

            # 浏览器读取的文件可能不存在
            except Exception as e:
                with open('static/404.html', 'rb') as f:
                    response_body = f.read()  # 响应的主体页面内容
                # 响应头
                response_first_line = 'HTTP/1.1 404 Not Found\r\n'
                response_header = 'Content-Length:'+str(len(response_body))+'\r\n' + \
                                  'Content-Type: text/html; charset=utf-8\r\n' + \
                                  'Date:' + time.strftime('%Y-%m-%d %H:%M:%S', time.localtime()) + '\r\n' + \
                                  'Server: Flyme awei Server\r\n'
            # 最后都会执行的代码
            finally:
                # 组成响应数据发送给(客户端)浏览器
                response = (response_first_line + response_header + '\r\n').encode('utf-8') + response_body
                new_socket.send(response)
                # 关闭套接字
                new_socket.close()

Python을 사용하여 사용자 정의 웹 프레임워크를 개발하는 방법

정적 리소스 요청 확인:

Python을 사용하여 사용자 정의 웹 프레임워크를 개발하는 방법

4. 동적 리소스가 있는 경우 수행할 작업

if request_path.endswith(".html"):
            "动态资源请求"
            # 动态资源的处理交给Web框架来处理,需要把请求参数交给Web框架,可能会有多个参数,采用字典结构
            params = {
                'request_path': request_path
            }
            # Web框架处理动态资源请求后,返回一个响应
            response = MyFramework.handle_request(params)
            new_socket.send(response)
            new_socket.close()

5. 웹 서버 메인 프레임워크 전체 코드 표시:

new_socket.close()

2. 웹 프레임워크의 메인 프로그램을 개발합니다

1. 요청 경로에 따라 해당 데이터에 동적으로 응답합니다

# -*- coding: utf-8 -*-
# @File  : My_Web_Server.py
# @author: Flyme awei 
# @email : 1071505897@qq.com
# @Time  : 2022/7/24 21:28


import sys
import time
from socket import *
import threading
import MyFramework


# 开发自己的Web服务器主类
class MyHttpWebServer(object):

    def __init__(self, port):
        # 创建 HTTP服务的 TCP套接字
        server_socket = socket(AF_INET, SOCK_STREAM)
        # 设置端口号互用,程序退出之后不需要等待,直接释放端口
        server_socket.setsockopt(SOL_SOCKET, SO_REUSEADDR, True)
        # 绑定 ip和 port
        server_socket.bind(('', port))
        # listen使套接字变为了被动连接
        server_socket.listen(128)
        self.server_socket = server_socket

    # 处理请求函数
    @staticmethod  # 静态方法
    def handle_browser_request(new_socket):
        # 接受客户端发来的数据
        recv_data = new_socket.recv(4096)
        # 如果没有数据,那么请求无效,关闭套接字,直接退出
        if len(recv_data) == 0:
            new_socket.close()
            return

        # 对接收的字节数据进行转换为字符数据
        request_data = recv_data.decode('utf-8')
        print("浏览器请求的数据:", request_data)
        request_array = request_data.split(' ', maxsplit=2)

        # 得到请求路径
        request_path = request_array[1]
        print("请求的路径是:", request_path)
        if request_path == "/":
            # 如果请求路径为根目录,自动设置为:/index.html
            request_path = "/index.html"
        # 判断是否为:.html 结尾
        if request_path.endswith(".html"):
            "动态资源请求"
            # 动态资源的处理交给Web框架来处理,需要把请求参数交给Web框架,可能会有多个参数,采用字典结构
            params = {
                'request_path': request_path
            }
            # Web框架处理动态资源请求后,返回一个响应
            response = MyFramework.handle_request(params)
            new_socket.send(response)
            new_socket.close()
        else:
            "静态资源请求"
            # 根据请求路径读取/static 目录中的文件数据,相应给客户端
            response_body = None  # 响应主体
            response_header = None  # 响应头的第一行
            response_first_line = None  # 响应头内容
            response_type = 'test/html'  # 默认响应类型
            try:
                # 读取 static目录中相对应的文件数据,rb模式是一种兼容模式,可以打开图片,也可以打开js
                with open('static'+request_path, 'rb') as f:
                    response_body = f.read()
                if request_path.endswith('.jpg'):
                    response_type = 'image/webp'

                response_first_line = 'HTTP/1.1 200 OK'
                response_header = 'Content-Length:' + str(len(response_body)) + '\r\n' + \
                                  'Content-Type: ' + response_type + '; charset=utf-8\r\n' + \
                                  'Date:' + time.strftime('%Y-%m-%d %H:%M:%S', time.localtime()) + '\r\n' + \
                                  'Server: Flyme awei Server\r\n'

            # 浏览器读取的文件可能不存在
            except Exception as e:
                with open('static/404.html', 'rb') as f:
                    response_body = f.read()  # 响应的主体页面内容
                # 响应头
                response_first_line = 'HTTP/1.1 404 Not Found\r\n'
                response_header = 'Content-Length:'+str(len(response_body))+'\r\n' + \
                                  'Content-Type: text/html; charset=utf-8\r\n' + \
                                  'Date:' + time.strftime('%Y-%m-%d %H:%M:%S', time.localtime()) + '\r\n' + \
                                  'Server: Flyme awei Server\r\n'
            # 最后都会执行的代码
            finally:
                # 组成响应数据发送给(客户端)浏览器
                response = (response_first_line + response_header + '\r\n').encode('utf-8') + response_body
                new_socket.send(response)
                # 关闭套接字
                new_socket.close()

    # 启动服务器,并接受客户端请求
    def start(self):
        # 循环并多线程来接收客户端请求
        while True:
            # accept等待客户端连接
            new_socket, ip_port = self.server_socket.accept()
            print("客户端ip和端口", ip_port)
            # 一个客户端的请求交给一个线程来处理
            sub_thread = threading.Thread(target=MyHttpWebServer.handle_browser_request, args=(new_socket, ))
            # 设置当前线程为守护线程
            sub_thread.setDaemon(True)
            sub_thread.start()  # 启动子线程


# Web 服务器程序的入口
def main():
    web_server = MyHttpWebServer(8080)
    web_server.start()


if __name__ == '__main__':
    main()

2. 요청 경로에 해당 응답 데이터가 없으면 404 페이지가 반환되어야 합니다

Python을 사용하여 사용자 정의 웹 프레임워크를 개발하는 방법3. 템플릿을 사용하여 응답 콘텐츠 표시

1. 템플릿 index.html을 직접 디자인하고, 일부 위치에서 동적 데이터를 사용하여 교체합니다.

# -*- coding: utf-8 -*-
# @File  : MyFramework.py
# @author: Flyme awei 
# @email : 1071505897@qq.com
# @Time  : 2022/7/25 14:05

import time

# 自定义Web框架


# 处理动态资源请求的函数
def handle_request(parm):
    request_path = parm['request_path']

    if request_path == '/index.html':  # 当前请求路径有与之对应的动态响应,当前框架只开发了 index.html的功能
        response = index()
        return response
    else:
        # 没有动态资源的数据,返回404页面
        return page_not_found()


# 当前 index函数,专门处理index.html的请求
def index():
    # 需求,在页面中动态显示当前系统时间
    data = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime())
    response_body = data
    response_first_line = 'HTTP/1.1 200 OK\r\n'
    response_header = 'Content-Length:' + str(len(response_body)) + '\r\n' + \
                      'Content-Type: text/html; charset=utf-8\r\n' + \
                      'Date:' + time.strftime('%Y-%m-%d %H:%M:%S', time.localtime()) + '\r\n' + \
                      'Server: Flyme awei Server\r\n'
    response = (response_first_line + response_header + '\r\n' + response_body).encode('utf-8')
    return response


def page_not_found():
    with open('static/404.html', 'rb') as f:
        response_body = f.read()  # 响应的主体页面内容
    # 响应头
    response_first_line = 'HTTP/1.1 404 Not Found\r\n'
    response_header = 'Content-Length:' + str(len(response_body)) + '\r\n' + \
                      'Content-Type: text/html; charset=utf-8\r\n' + \
                      'Date:' + time.strftime('%Y-%m-%d %H:%M:%S', time.localtime()) + '\r\n' + \
                      'Server: Flyme awei Server\r\n'

    response = (response_first_line + response_header + '\r\n').encode('utf-8') + response_body
    return response

2. 교체 방법, 교체할 데이터

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>首页 - 电影列表</title>
    <link href="/css/bootstrap.min.css" rel="stylesheet">
    <script src="/js/jquery-1.12.4.min.js"></script>
    <script src="/js/bootstrap.min.js"></script>
</head>

<body>
<div class="navbar navbar-inverse navbar-static-top ">
        <div class="container">
        <div class="navbar-header">
                <button class="navbar-toggle" data-toggle="collapse" data-target="#mymenu">
                        <span class="icon-bar"></span>
                        <span class="icon-bar"></span>
                        <span class="icon-bar"></span>
                 </button>
                 <a href="#" class="navbar-brand">电影列表</a>
        </div>
        <div class="collapse navbar-collapse" id="mymenu">
                <ul class="nav navbar-nav">
                        <li class="active"><a href="">电影信息</a></li>
                        <li><a href="">个人中心</a></li>
                </ul>
        </div>
        </div>
</div>
<div class="container">

    <div class="container-fluid">

        <table class="table table-hover">
            <tr>
                    <th>序号</th>
                    <th>名称</th>
                    <th>导演</th>
                    <th>上映时间</th>
                    <th>票房</th>
                    <th>电影时长</th>
                    <th>类型</th>
                    <th>备注</th>
                    <th>删除电影</th>
            </tr>
            {%datas%}
        </table>
    </div>
</div>
</body>
</html>
.

Python을 사용하여 사용자 정의 웹 프레임워크를 개발하는 방법4. 프레임워크의 라우팅 목록 기능 개발

1. 향후 새로운 액션 리소스 기능을 개발하려면 다음만 수행하면 됩니다.

a 특수 처리 추가. 기능

2. 라우팅: 요청한 URL 경로와 처리 기능이 직접 매핑됩니다.

3. 라우팅 테이블

요청 경로처리 함수index 함수user_info 함수주의: 사용자 동적 자원 요청은 해당 처리 기능을 찾기 위해 라우팅 테이블을 탐색하여 완료됩니다. 5. 데코레이터를 사용하여 경로 추가
/index.html
/user_info.html
response_body = response_body.replace(&#39;{%datas%}&#39;, data)

1. 매개변수가 있는 데코레이터 사용

# 定义路由表
route_list = {
    (&#39;/index.html&#39;, index),
    (&#39;/user_info.html&#39;, user_info)
}


for path, func in route_list:
    if request_path == path:
        return func()
    else:
        # 没有动态资源的数据,返回404页面
        return page_not_found()

2. 처리 기능을 기반으로 경로를 추가하는 기능 추가

# -*- coding: utf-8 -*-
# @File  : My_Web_Server.py
# @author: Flyme awei 
# @email : 1071505897@qq.com
# @Time  : 2022/7/24 21:28


# 定义路由表
route_list = []
# route_list = {
# (&#39;/index.html&#39;, index),
# (&#39;/user_info.html&#39;, user_info)
# }


# 定义一个带参数的装饰器
def route(request_path):  # 参数就是URL请求
    def add_route(func):
        # 添加路由表
        route_list.append((request_path, func))

        @wraps(func)
        def invoke(*args, **kwargs):
            # 调用指定的处理函数,并返回结果
            return func()
        return invoke
    return add_route


# 处理动态资源请求的函数
def handle_request(parm):
    request_path = parm[&#39;request_path&#39;]

    # if request_path == &#39;/index.html&#39;:  # 当前请求路径有与之对应的动态响应,当前框架只开发了 index.html的功能
    #     response = index()
    #     return response
    # elif request_path == &#39;/user_info.html&#39;:  # 个人中心的功能
    #     return user_info()
    # else:
    #     # 没有动态资源的数据,返回404页面
    #     return page_not_found()
    for path, func in route_list:
        if request_path == path:
            return func()
        else:
            # 没有动态资源的数据,返回404页面
            return page_not_found()

요약: 매개변수가 있는 데코레이터를 사용하면 라우터가 자동으로 경로를 추가할 수 있습니다. 라우팅 테이블.

6. 영화 목록 페이지 개발 사례

1. 쿼리 데이터

Python을 사용하여 사용자 정의 웹 프레임워크를 개발하는 방법my_web.py

@route(&#39;/user_info.html&#39;)

MyFramework.py

# -*- coding: utf-8 -*-
# @File  : My_Web_Server.py
# @author: Flyme awei 
# @email : 1071505897@qq.com
# @Time  : 2022/7/24 21:28


import socket
import sys
import threading
import time
import MyFramework


# 开发自己的Web服务器主类
class MyHttpWebServer(object):

    def __init__(self, port):
        # 创建HTTP服务器的套接字
        server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        # 设置端口号复用,程序退出之后不需要等待几分钟,直接释放端口
        server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, True)
        server_socket.bind((&#39;&#39;, port))
        server_socket.listen(128)
        self.server_socket = server_socket

    # 处理浏览器请求的函数
    @staticmethod
    def handle_browser_request(new_socket):
        # 接受客户端发送过来的数据
        recv_data = new_socket.recv(4096)
        # 如果没有收到数据,那么请求无效,关闭套接字,直接退出
        if len(recv_data) == 0:
            new_socket.close()
            return

        # 对接受的字节数据,转换成字符
        request_data = recv_data.decode(&#39;utf-8&#39;)
        print("浏览器请求的数据:", request_data)
        request_array = request_data.split(&#39; &#39;, maxsplit=2)
        # 得到请求路径
        request_path = request_array[1]
        print(&#39;请求路径是:&#39;, request_path)

        if request_path == &#39;/&#39;:  # 如果请求路径为跟目录,自动设置为/index.html
            request_path = &#39;/index.html&#39;

        # 根据请求路径来判断是否是动态资源还是静态资源
        if request_path.endswith(&#39;.html&#39;):
            &#39;&#39;&#39;动态资源的请求&#39;&#39;&#39;
            # 动态资源的处理交给Web框架来处理,需要把请求参数传给Web框架,可能会有多个参数,所有采用字典机构
            params = {
                &#39;request_path&#39;: request_path,
            }
            # Web框架处理动态资源请求之后,返回一个响应
            response = MyFramework.handle_request(params)
            new_socket.send(response)
            new_socket.close()


        else:
            &#39;&#39;&#39;静态资源的请求&#39;&#39;&#39;
            response_body = None  # 响应主体
            response_header = None  # 响应头
            response_first_line = None  # 响应头的第一行
            # 其实就是:根据请求路径读取/static目录中静态的文件数据,响应给客户端
            try:
                # 读取static目录中对应的文件数据,rb模式:是一种兼容模式,可以打开图片,也可以打开js
                with open(&#39;static&#39; + request_path, &#39;rb&#39;) as f:
                    response_body = f.read()
                if request_path.endswith(&#39;.jpg&#39;):
                    response_type = &#39;image/webp&#39;
                response_first_line = &#39;HTTP/1.1 200 OK&#39;
                response_header = &#39;Server: Laoxiao_Server\r\n&#39;

            except Exception as e:  # 浏览器想读取的文件可能不存在
                with open(&#39;static/404.html&#39;, &#39;rb&#39;) as f:
                    response_body = f.read()  # 响应的主体页面内容(字节)
                # 响应头 (字符数据)
                response_first_line = &#39;HTTP/1.1 404 Not Found\r\n&#39;
                response_header = &#39;Server: Laoxiao_Server\r\n&#39;
            finally:
                # 组成响应数据,发送给客户端(浏览器)
                response = (response_first_line + response_header + &#39;\r\n&#39;).encode(&#39;utf-8&#39;) + response_body
                new_socket.send(response)
                new_socket.close()  # 关闭套接字

    # 启动服务器,并且接受客户端的请求
    def start(self):
        # 循环并且多线程来接受客户端的请求
        while True:
            new_socket, ip_port = self.server_socket.accept()
            print("客户端的ip和端口", ip_port)
            # 一个客户端请求交给一个线程来处理
            sub_thread = threading.Thread(target=MyHttpWebServer.handle_browser_request, args=(new_socket,))
            sub_thread.setDaemon(True)  # 设置当前线程为守护线程
            sub_thread.start()  # 子线程要启动


# web服务器程序的入口
def main():
    web_server = MyHttpWebServer(8080)
    web_server.start()


if __name__ == &#39;__main__&#39;:
    main()

2.

위 내용은 Python을 사용하여 사용자 정의 웹 프레임워크를 개발하는 방법의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
이 기사는 yisu.com에서 복제됩니다. 침해가 있는 경우 admin@php.cn으로 문의하시기 바랍니다. 삭제