table of Contents
Django basis before play
HTTP protocol (Hyper Text Protocol)
Four characteristics
Over TCP / IP based application layer acting
Based on a request response
The request is sent, in response to
no status
Does not save the user state, even once forgot to give
not connected
eg:one night love
Data Format
Request format
The first line of the request (request method, protocol version, etc.)
Request header (lot K: V key-value pairs)
\r\n
Request header (real time data send post request only if the request does not get there)
Response format
The first line of response
Response header
\r\n
Response Body
The response status code
Represent some particular digital data
1xx: the server has received your data is being processed you can submit additional data
2xx: Success response server (200 requests the successful)
3xx: Redirection
4xx: Request error (404 403 to request resources do not exist to refuse access)
5xx :( internal server error (500))
Request method
get request
To others towards data
post request
Submit data (eg: user login) to others
Pure hand-line and web frameworks
- Manually writing socket
- Manual data processing format http
Simple c / s connection
#服务端
import socket
server = socket.socket()
server.bind(('127.0.0.1', 8081))
server.listen(5)
while True:
conn,addr = server.accept()
data = conn.recv(1024)
conn.send(b'HTTP/1.1 200 OK\r\n\r\n')
print(data)
conn.send(b'hello baby')
conn.close()
Frame slightly more complex web
What client request, what returns, eg: the client sends http://127.0.0.1:8081/index
the server back to the clientindex
import socket
server = socket.socket()
server.bind(('127.0.0.1', 8081))
server.listen(5)
while True:
conn,addr = server.accept()
conn.send(b'HTTP/1.1 200 OK\r\n\r\n')
data = conn.recv(1024)
print(data)
data = data.decode('utf8')
current_path = data.split('\r\n')[0].split(' ')[1]
print(current_path)
if current_path == '/index':
conn.send(b'index')
#服务端还可以打开html文件,将文件中的东西显示给客户端
# with open(r'index.html', 'rb') as f:
# conn.send(f.read())
else:
conn.send(b'404 error')
conn.close()
Based wsgiref
If I do not want to write the code above and socket connection inside the index and other content, the client sends 100 different requests, I am not expert roll up 100 times ah! It is also too tired, so we use the wsgiref module, to help us operate more simple and convenient, we can put the necessary code wsgiref.py is written in the corresponding file, following are the files to be put s things.
urls.py routing function and object-relational view views.py put the view function (the business logic) Templates Templates folder (a bunch of html files)
wsgiref.py file
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',[])
current_path = env.get('PATH_INFO') #env里面有 很多数据,我们筛选有用的数据就行
# 先定义一个变量名 用来存储后续匹配到的函数名
func = None
# for循环 匹配后缀
for url in urls:
if current_path == url[0]:
func = url[1] # 一旦匹配成功 就将匹配到的函数名赋值给func变量
break # 主动结束匹配
# 判断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)
# 实时监听该地址 只要有客户端来连接 统一交给run函数去处理
server.serve_forever() # 启动服务端,永远等着客户端来连接
urls.py
from views import *
urls = [
('/index',index), #第二个是函数,如果匹配成功,就去views.py中去找相应的函数去运行
('/login',login),
('/xxx',xxx),
]
views.py
from urls import urls
def index(env):
return 'index'
def login(env):
return 'login'
def error(env):
return '404 error'
def xxx(env):
return 'xxx'
Client gets access to the server through the dictionary
Here we need to use a modulejinja2
We need to go download this modulefrom jinja2 import Template
Specific knowledge jinja2
, please click on the link https://www.cnblogs.com/yanjiayi098-001/p/11701150.html
wsgiref.py file
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',[])
current_path = env.get('PATH_INFO') #env里面有 很多数据,我们筛选有用的数据就行
# 先定义一个变量名 用来存储后续匹配到的函数名
func = None
# for循环 匹配后缀
for url in urls:
if current_path == url[0]:
func = url[1] # 一旦匹配成功 就将匹配到的函数名赋值给func变量
break # 主动结束匹配
# 判断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)
# 实时监听该地址 只要有客户端来连接 统一交给run函数去处理
server.serve_forever() # 启动服务端,永远等着客户端来连接
urls.py
urls = [
('/get_user',get_user), #第二个是函数,如果匹配成功,就去views.py中去找相应的函数去运行
]
views.py
def get_user(env):
d = {'name':'jason','pwd':'123','hobby':['read','running','music']}
with open(r'get_user.html','r',encoding='utf-8') as f:
data = f.read()
temp = Template(data) #将data数据传给这个temp,做处理
res = temp.render(user=d) # 将字典d传递给前端页面 页面上通过变量名user就能够获取到该字典
return res
get_user.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
#jinja2模块,可以对字典 进行以下取值,同时这是jinja变量取值 {{ }}的语法
<p>{{ user }}</p>
<p>{{ user.name }}</p>
<p>{{ user['pwd'] }}</p>
<p>{{ user.get('hobby') }}</p>
</body>
</html>
Static and dynamic page
Static page: writing is a dead page
On the back-end data by changing to a reaction to the browser page: Dynamic page
eg:. 1 shows the back end to the front end to get the current time
2. Data acquisition backend database and display to the front end
The client gets the current time by accessing the server
So if the user accesses the server, the client page will display the current time, so how to do it?
We should know that the page is to use html, if the time to write in HTML, then by encoding format, he is no longer time, then how will the time displayed on the pages?
Practice: We want first to write modules on the basis of wsgiref in html string of specific characters in a string html and get these back end of time in exchange, specifically to see the code
wsgiref.py file
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',[])
current_path = env.get('PATH_INFO') #env里面有 很多数据,我们筛选有用的数据就行
# 先定义一个变量名 用来存储后续匹配到的函数名
func = None
# for循环 匹配后缀
for url in urls:
if current_path == url[0]:
func = url[1] # 一旦匹配成功 就将匹配到的函数名赋值给func变量
break # 主动结束匹配
# 判断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)
# 实时监听该地址 只要有客户端来连接 统一交给run函数去处理
server.serve_forever() # 启动服务端,永远等着客户端来连接
urls.py
from views import *
urls = [
('/get_time',get_time), #第二个是函数,如果匹配成功,就去views.py中去找相应的函数去运行
]
views.py
from urls import *
from datetime import datetime
def get_time():
current_time = datetime.now().strftime('%Y-%m-%d %X')
with open(r'get_time.html','r',encoding='utf-8') as f: #这是一串字符串
data= f.read()
data = data.replace('$$time$$',current_time)
return data
get_time.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
$$time$$
</body>
</html>
Client gets the data by accessing the database server
Now get database data and methods to obtain almost like a dictionary, but we need to build a database, the database through a link, go inside to get the value of the database
wsgiref.py file
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',[])
current_path = env.get('PATH_INFO') #env里面有 很多数据,我们筛选有用的数据就行
# 先定义一个变量名 用来存储后续匹配到的函数名
func = None
# for循环 匹配后缀
for url in urls:
if current_path == url[0]:
func = url[1] # 一旦匹配成功 就将匹配到的函数名赋值给func变量
break # 主动结束匹配
# 判断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)
# 实时监听该地址 只要有客户端来连接 统一交给run函数去处理
server.serve_forever() # 启动服务端,永远等着客户端来连接
urls.py
urls = [
('/get_db',get_db), #第二个是函数,如果匹配成功,就去views.py中去找相应的函数去运行
]
views.py
import pymysql
def get_db(env):
conn = pymysql.connect(
host = '127.0.0.1',
port = 3306,
user = 'root',
password = 'root',
database = 'day56',
charset = 'utf8',
autocommit = True
)
cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)
sql = "select * from userinfo"
cursor.execute(sql) #提交sql语句,这个出发的是执行的对象并不是一个值
res = cursor.fetchall()
print(res)
with open(r'get_db.html','r',encoding='utf-8') as f:
data = f.read()
temp = Template(data)
ret = temp.render(user_list = res) # 将字典d传递给前端页面 页面上通过变量名user就能够获取到该字典
return ret
get_db.html
Here we used the bootstrap to build a page, which is a typical dynamic page
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src="https://cdn.bootcss.com/jquery/3.4.1/jquery.min.js"></script>
<link href="https://cdn.bootcss.com/twitter-bootstrap/3.3.1/css/bootstrap.min.css" rel="stylesheet">
<script src="https://cdn.bootcss.com/twitter-bootstrap/3.3.1/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
<div class="row">
<div class="col-md-8 col-md-offset-2">
<h1 class="text-center">用户列表</h1>
<table class="table table-bordered table-striped table-hover">
<thead>
<tr>
<th>id</th>
<th>name</th>
<th>pwd</th>
</tr>
</thead>
<tbody>
{% for user_dict in user_list %}
<tr>
<td>{{ user_dict.id }}</td>
<td>{{ user_dict.name }}</td>
<td>{{ user_dict.pwd }}</td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
</div>
</div>
</body>
</html>
three major python web framework
A: socket Part
B: corresponding relationship between the routing and view function
C: Template grammar
Django | Flask | Tornado |
---|---|---|
Large and comes with features similar to a particularly large aircraft carriers sometimes too heavy |
Small but comes with features similar to particularly low Ranger particularly to third module, if the third-party modules flask over django can all add up more dependent on third party modules |
Asynchronous non-blocking regressed to develop a game server |
A use of someone else's wsgiref B wrote it myself C to write their own |
A use of someone else's werkzeug (based wsgiref) B wrote it myself C with others jinja2 |
Three full write your own |