Django入门前储备
一、简易版本的web框架
import socket
server = socket.socket()
server.bind(('127.0.0.1',8080))
server.listen()
"""
GET / HTTP/1.1\r\n
Host: 127.0.0.1:8080\r\n
Connection: keep-alive\r\n
Upgrade-Insecure-Requests: 1\r\n
User-Agent: Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.92 Safari/537.36\r\n
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8\r\n
Accept-Encoding: gzip, deflate, br\r\n
Accept-Language: zh-CN,zh;q=0.9\r\n
\r\n
"""
while True:
conn, addr = server.accept()
data = conn.recv(1024)
conn.send(b'HTTP/1.1 200 OK\r\n\r\n')
# 先将请求信息转换为字符串
res = data.decode('utf-8')
# 利用字符串切割
target_url = res.split(' ')[1]
# 根据后缀的不同返回不同的内容
if target_url == '/index':
# conn.send(b'index')
with open(r'templates/myhtml.html', 'rb') as f:
data = f.read()
conn.send(data)
elif target_url == '/login':
conn.send(b'login')
else:
conn.send(b'hello world')
conn.close()
二、借助wsgiref模块
server.py
from wsgiref.simple_server import make_server
from urls import urls
from views import *
def run(env,response):
"""
:param env:请求相关的数据
:param response: 响应相关的数据
:return:
"""
# 固定写法 无需考虑
response('200 OK', [])
# print(env) # 是一个请求数据相关的字典 是由wsgiref自动帮我们处理好的
current_url = env.get('PATH_INFO')
# 先定义存储函数的变量名
func = None
# 循环判断匹配关系的
for url in urls: # ('/index',index),(),(),()
# 判断元组第一个元素跟用户输入的路径是否匹配
if url[0] == current_url:
# 将对应的函数复制给func
func = url[1] # func = index
# 一旦匹配成功 应该直接结束循环
break
# 先判断func是否有值
if func:
res = func(env)
else:
res = error(env)
return [res.encode('utf-8')]
# if current_url == '/index':
# return [b'index']
# elif current_url == '/login':
# return [b'login']
# else:
# return [b'404 NOT FOUND']
if __name__ == '__main__':
# 监听本地8080端口 只要有请求来就会自动调用run方法
server = make_server('127.0.0.1',8080,run)
server.serve_forever() # 启动服务端
urls.py
# 只存储对应关系
# 所有url匹配
from views import *
urls = [
('/login',login),
('/index',index),
('/register',register),
('/get_time',get_time),
('/get_user',get_user),
('/get_info',get_info)
]
views.py
# 只存储业务逻辑相关的函数
# 所有业务逻辑代码
def login(env):
return 'login func'
def index(env):
return 'index func'
def error(env):
return '404 页面'
def register(env):
return 'register func'
import time
def get_time(env):
current_time = time.strftime('%Y-%m-%d %X')
with open(r'templates/mytime.html','r',encoding='utf-8') as f:
data = f.read()
# 利用字符串的替换
data = data.replace('asdashdjas',current_time)
return data
from jinja2 import Template
def get_user(env):
userinfo = {
'username':'jason',
'password':123,
'hobby':['read','study','run']
}
with open(r'templates/myuser.html','r',encoding='utf-8') as f:
data = f.read()
tmp = Template(data)
# 可以一次性传N多个
res = tmp.render({"xxx":userinfo,}) # 将userinfo传递给myuser文件 该文件通过user即可访问
return res
import pymysql
# 获取数据库里面的数据展示到前端
def get_info(env):
conn = pymysql.connect(
host = '127.0.0.1',
port = 3306,
user = 'root',
password = '123',
db = 'db666',
charset = 'utf8'
)
cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)
sql = 'select * from userinfo'
cursor.execute(sql)
data = cursor.fetchall() # [{},{},{},{}]
with open(r'templates/myinfo.html','r',encoding='utf8') as f:
data1 = f.read()
temp = Template(data1)
res = temp.render({"user_list":data})
return res
tempates
myhtml.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.4.1/jquery.min.js"></script> </head> <body> <h1>你们好 加油努力学习</h1> </body> </html>
myinfo.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
</head>
<body>
<h1>数据展示</h1>
<table>
<thead>
<tr>
<th>ID</th>
<th>username</th>
<th>password</th>
</tr>
</thead>
<tbody>
<!-- 循环展示-->
{%for d in user_list %}
<tr>
<td>{{d.id}}</td>
<td>{{d.name}}</td>
<td>{{d.password}}</td>
</tr>
{% endfor %}
</tbody>
</table>
</body>
</html>
mytime.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
</head>
<body>
asdashdjas
</body>
</html>
myuser.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
</head>
<body>
{{ user }}
{{ user.username }}
{{ user['password'] }}
{{ user.get('hobby') }}
</body>
</html>