web框架的本质及自定义web框架

柔情痞子 提交于 2019-12-05 17:31:45

web框架

简单版回复页面框架

import socket
server = socket.socket()
server.bind(('127.0.0.1',8001))
# 127.0.0.1:8001
server.listen()
while 1:
    conn,addr = server.accept()
    from_brower_msg = conn.recv(1024)
    # print(from_brower_msg)
    path = from_brower_msg.decode('utf-8').split(' ')[1]
    print(path)
    conn.send(b'HTTP/1.1 200 ok\r\n\r\n')
    if path == '/':
        with open('04test.html','rb') as f:
            data = f.read()
    elif path == '/style.css':
        with open('style.css', 'rb') as f:
            data = f.read()
    elif path == '/test.js':
        with open('test.js', 'rb') as f:
            data = f.read()
    elif path == '/1.jpg':
        with open('1.jpg', 'rb') as f:
            data = f.read()
    conn.send(data)
    conn.close()

进阶函数版框架+多线程web框架

import socket
from urls import urlpatterns
from threading import Thread
server = socket.socket()
server.bind(('127.0.0.1',8003))
# 127.0.0.1:8001
server.listen()
while 1:
    conn,addr = server.accept()
    from_brower_msg = conn.recv(1024)
    # print(from_brower_msg)
    path = from_brower_msg.decode('utf-8').split(' ')[1]
    print(path)
    conn.send(b'HTTP/1.1 200 ok\r\n\r\n')
    for url in urlpatterns:
        if path == url[0]:
            # ret = url[1]()
            t = Thread(target=url[1],args=(conn,))
            t.start()
            break
    # else:
    #     t = Thread(target=nofount,args=(conn,))
    #     t.start()
    # if path == '/':
    #     ret = home()
    #     # t = Thread(target=home,)
    #     # t.start()
    #
    # elif path == '/style.css':
    #     ret = css()
    #
    # elif path == '/test.js':
    #     ret = js()
    #
    # elif path == '/1.jpg':
    #     ret = pic()

动态页面的web框架

import socket
from urls import urlpatterns
from threading import Thread

server = socket.socket()

server.bind(('127.0.0.1',8003))
# 127.0.0.1:8001
server.listen()




while 1:

    conn,addr = server.accept()

    from_brower_msg = conn.recv(1024)
    # print(from_brower_msg)
    path = from_brower_msg.decode('utf-8').split(' ')[1]
    print(path)
    conn.send(b'HTTP/1.1 200 ok\r\n\r\n')

    for url in urlpatterns:
        if path == url[0]:
            # ret = url[1]()
            t = Thread(target=url[1],args=(conn,))
            t.start()
            break

不同html页面web框架

import socket
from urls import urlpatterns
from threading import Thread

server = socket.socket()

server.bind(('127.0.0.1',8003))
# 127.0.0.1:8001
server.listen()



while 1:

    conn,addr = server.accept()

    from_brower_msg = conn.recv(1024)
    # print(from_brower_msg)
    path = from_brower_msg.decode('utf-8').split(' ')[1]
    print(path)
    conn.send(b'HTTP/1.1 200 ok\r\n\r\n')

    for url in urlpatterns:
        if path == url[0]:
            # ret = url[1]()
            t = Thread(target=url[1],args=(conn,))
            t.start()
            break

wsgiref模块

from wsgiref.simple_server import make_server

from urls import urlpatterns

def application(environ,start_response):
    # environ  所有请求相关信息
    # start_response --封装响应数据格式

    print('当前请求路径',environ['PATH_INFO'])
    path = environ['PATH_INFO']
    start_response('200 ok',[]) # conn.send(b'HTTP/1.1 200 ok\r\n\r\n')
    for url in urlpatterns:
        if path == url[0]:
            ret = url[1]()

    return [ret]


if __name__ == '__main__':
    h = make_server('127.0.0.1', 8080, application)
    h.serve_forever()



jinja2模块

<!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</title>
</head>
<body>
    <h1>姓名:{{name}}</h1>
    <h1>爱好:</h1>
    <ul>
        {% for hobby in hobby_list %}
        <li>{{hobby}}</li>
        {% endfor %}
    </ul>
</body>
</html>
from wsgiref.simple_server import make_server
from jinja2 import Template


def index():
    with open("index2.html", "r",encoding='utf-8') as f:
        data = f.read()
    template = Template(data)  # 生成模板文件
    ret = template.render({"name": "于谦", "hobby_list": ["烫头", "泡吧"]})  # 把数据填充到模板里面
    return [bytes(ret, encoding="utf8"), ]


# 定义一个url和函数的对应关系
URL_LIST = [
    ("/index/", index),
]

def run_server(environ, start_response):
    start_response('200 OK', [('Content-Type', 'text/html;charset=utf8'), ])  # 设置HTTP响应的状态码和头信息
    url = environ['PATH_INFO']  # 取到用户输入的url
    func = None  # 将要执行的函数
    for i in URL_LIST:
        if i[0] == url:
            func = i[1]  # 去之前定义好的url列表里找url应该执行的函数
            break
    if func:  # 如果能找到要执行的函数
        return func()  # 返回函数的执行结果
    else:
        return [bytes("404没有该页面", encoding="utf8"), ]


if __name__ == '__main__':
    httpd = make_server('', 8000, run_server)
    print("Serving HTTP on port 8000...")
    httpd.serve_forever()
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!