使用wsgiref手撸web框架

模板

前言

要说到应用程序,就不得不提的就是cs架构和BS架构

所谓的cs架构就是client端和server端,就像我们的电脑上的qq,微信等应用程序

bs架构就是浏览器端和server端,我们不需要写客户端了,直接用浏览器接收来自server端的数据,进行解析

手写简易的server端

import socket
soc=socket.socket() #实例化socket
soc.bind(('127.0.0.1',8001)) #绑定ip地址和端口
soc.listen(5)#监听
while True:
    sock,addr=soc.accept()#等待客户端连接
    sock.send(b'HTTP/1.1 200 OK
Content-Type:Text/html

')#发送请求头和请求报文
​
    data=str(sock.recv(1024),encoding='utf-8')#将请求过来的数据解析成字符串
    print(data)
    data=data.split('
')[0].split(' ')#将请求中的第一行提取出来
    if '/index' in data:
        with open('index.html','rb') as f:
            ff=f.read()
​
            print(ff)
        sock.send(ff)#响应请求内容
    else:
        sock.send(b'404')
    sock.close()

 

使用wsgiref手撸web框架

web框架运行文件wsgirefserver.py

# 这是一个web框架的测试模板wsgiref
from wsgiref.simple_server import make_server
​
from urlss import *
​
​
def run(env, response):
    print(env)
    print(response)
    response('200 OK', [('Content-type', 'text/html')])  # 请求报文
    position = env['PATH_INFO']  # 拿到请求体中的路由
    func = None
    for url in urls:
        if url[0] == position:
            func = url[1]
            break
    if func:
        response = func()
    else:
        response = error()
​
    return [response.encode('utf-8'), ]
​
​
if __name__ == '__main__':
    ser = make_server('127.0.0.1', 8001, run)
    ser.serve_forever()
View Code

 

视图views.py

#!/user/bin/env python3
# -*- coding: utf-8 -*-
import time
import datetime
from jinja2 import Template
import sys
import pymysql
​
​
def index():
    with open('templates/index.html', 'r') as f:
        data = f.read()
    return data
​
​
def test():
    with open('templates/test.html', 'r') as f:
        data = f.read()
    tem = Template(data)
    response = tem.render(user={'name': 'andy', 'age': 18})
​
    return response
​
​
def timer():
    ctime = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time()))
    print(ctime)
    with open('templates/time.html', 'r') as f:
        data = f.read()
        data = data.replace('@@time@@', ctime)
    return data
​
​
def error():
    return '404'
​
​
def user():
    conn = pymysql.connect(host='127.0.0.1', port=3306, user='root', password='admin', db='web')
    cur = conn.cursor(pymysql.cursors.DictCursor)
    cur.execute('select * from userinfo')
    user_list = cur.fetchall()
    print(user_list)
​
    with open('templates/user.html', 'r') as f:
        data = f.read()
    tem = Template(data)
    response = tem.render(user_list=user_list)
    return response
​
​
if __name__ == '__main__':
    user()
View Code

路由urlss.py

#!/user/bin/env python3
# -*- coding: utf-8 -*-
from views import *
urls = [
    ('/index', index),
    ('/timer', timer),
    ('/test', test),
    ('/user', user),
​
]
View Code

templates/index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<h3>index</h3>
<h2 style="color: red;">this is red wrod</h2>
<img src="http://106.14.187.174/static/blog/img/rest_framework.jpg" alt="">
</body>
</html>

templates/test.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<h1>{{user.name}}
{{user.age}}</h1></body>
</html>

templates/time.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
@@time@@
</body>
</html>

templates/user.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>title</title>
</head>
<body>
<h1>hello</h1>
<h2>andy table</h2>
<table border="2">
    <thead>
    <tr>
        <th>id</th>
        <th>name</th>
        <th>password</th>
    </tr>
    </thead>
    <tbody>
    {% for user in user_list %}
    <tr>
        <td>{{user.id}}</td>
        <td>{{user.name}}</td>
        <td>{{user.password}}</td>
    </tr>
    {%endfor%}
    </tbody>
</table>
</body>
</html>

 

原文地址:https://www.cnblogs.com/ouyang99-/p/11429608.html