django框架底层

socket

# 你可以将web框架理解成服务端
import socket


server = socket.socket()  # TCP  三次握手四次挥手  osi七层
server.bind(('127.0.0.1',8080))  # IP协议 以太网协议 arp协议...
server.listen(5)  # 池 ...

while True:
    conn, addr = server.accept()
    data = conn.recv(1024)
    # print(data)  # 二进制数据
    data = data.decode('utf-8')  # 字符串
    # 获取字符串中特定的内容       正则  如果字符串有规律也可以考虑用切割
    conn.send(b'HTTP/1.1 200 OK\r\n\r\n')
    current_path = data.split(' ')[1]
    # print(current_path)
    if current_path == '/index':
        # conn.send(b'index heiheihei')
        with open(r'templates/01 myhtml.html', 'rb') as f:
            conn.send(f.read())
    elif current_path == '/login':
        conn.send(b'login')
    else:
        # 你直接忽略favicon.ico
        conn.send(b'hello web')
    conn.close()



wsgiref模块

from wsgiref.simple_server import make_server
from urls import urls
from views import *


def run(env, response):
    """
    :param env:请求相关的所有数据
    :param response:响应相关的所有数据
    :return: 返回给浏览器的数据
    """
    # print(env)  # 大字典  wsgiref模块帮你处理好http格式的数据 封装成了字典让你更加方便的操作
    # 从env中取
    response('200 OK', [])  # 响应首行 响应头
    current_path = env.get('PATH_INFO')
    # if current_path == '/index':
    #     return [b'index']
    # elif current_path == '/login':
    #     return [b'login']
    # return [b'404 error']
    # 定义一个变量 存储匹配到的函数名
    func = None
    for url in urls:  # url (),()
        if current_path == url[0]:
            # 将url对应的函数名赋值给func
            func = url[1]
            break  # 匹配到一个之后 应该立刻结束for循环
    # 判断func是否有值
    if func:
        res = func(env)
    else:
        res = error(env)

    return [res.encode('utf-8')]


if __name__ == '__main__':
    server = make_server('127.0.0.1',8080,run)
    server.serve_forever()  # 启动服务端

urls.py

from views import *

# url与函数的对应关系
urls = [
    ('/index',index),
    ('/login',login),
]

views.py

def index(env):
    return 'index'
def login(env):
    return "login"
def error(env):
    return '404 error'

模板语法之jinja2模块

from jinja2 import Template
def get_dict(env):
    user_dic = {'username':'jason','age':18,'hobby':'read'}
    with open(r'index.html','r',encoding='utf-8') as f:
        data = f.read()
    tmp = Template(data)
    res = tmp.render(user=user_dic)
    return res
pip3 install jinja2
"""模版语法是在后端起作用的"""

# 模版语法(非常贴近python语法)
{{ user }}
{{ user.get('username')}}
{{ user.age }}
{{ user['hobby'] }}

posted @ 2023-03-31 14:44  Bre-eZe  阅读(17)  评论(0)    收藏  举报