标签:running 网络 用户 等等 本质 lan 完成 exec __name__
Web应用程序是一种可以通过Web访问的应用程序,程序的最大好处是用户很容易访问应用程序,用户只需要有浏览器即可,不需要再安装其他软件
应用程序有两种模式C/S、B/S。C/S是客户端/服务器端程序,也就是说这类程序一般独立运行。而B/S就是浏览器端/服务器端应用程序,这类应用程序一般借助IE等浏览器来运行。WEB应用程序一般是B/S模式。Web应用程序首先是“应用程序”,和用标准的程序语言,如C、C++等编写出来的程序没有什么本质上的不同。然而Web应用程序又有自己独特的地方,就是它是基于Web的,而不是采用传统方法运行的。换句话说,它是典型的浏览器/服务器架构的产物。
浏览器/服务器架构(Browser/Server,简称B/S)能够很好地应用在广域网上,成为越来越多的企业的选择。浏览器/服务器架构相对于其他几种应用程序体系结构,有如下3方面的优点:
总结一下,本质上:浏览器是一个socket客户端,服务器是一个socket服务端
import socket
def server_run():
soc = socket.socket()
soc.bind(('127.0.0.1', 8008))
soc.listen(5)
while True:
conn, addr = soc.accept()
recv_data = conn.recv(1024)
print(recv_data)
# 1 直接在send里写,发送给客户端
# conn.send(b'HTTP/1.1 200 OK\r\n\r\n<h1>hello web</h1><img src="https://gss2.bdstatic.com/9fo3dSag_xI4khGkpoWK1HF6hhy/baike/c0%3Dbaike92%2C5%2C5%2C92%2C30/sign=5e3814acf9edab64607f4592965fc4a6/14ce36d3d539b600c0c465d0eb50352ac65cb74b.jpg"></img>')
#2 打开一个html文件,发送给客户端
# with open('index.html','r',encoding='utf-8') as f:
# data=f.read()
# conn.send(('HTTP/1.1 200 OK\r\n\r\n%s'%data).encode('utf-8'))
# 3 动态网页,字符串替换
import time
now=time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
print(now)
with open('index.html','r',encoding='utf-8') as f:
data=f.read()
data=data.replace('@@@',now)
conn.send(('HTTP/1.1 200 OK\r\n\r\n%s'%data).encode('utf-8'))
conn.close()
if __name__ == '__main__':
server_run()
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h2>@@@</h2>
<img src="https://gss2.bdstatic.com/9fo3dSag_xI4khGkpoWK1HF6hhy/baike/c0%3Dbaike92%2C5%2C5%2C92%2C30/sign=5e3814acf9edab64607f4592965fc4a6/14ce36d3d539b600c0c465d0eb50352ac65cb74b.jpg" alt="">
</body>
</html>
'''
a socket服务端
b 根据url不同返回不同的内容
url---视图函数
c 字符串返回给用户
特殊字符替换
Web框架种类:
a b c Tornado
别人的a b c django(a用的wsgiref)
别人a b 别人c flask(c用的jinja2)
另一种分类:
Django和其它
'''
import socket
import pymysql
def index(request):
return '<img src="https://gss2.bdstatic.com/9fo3dSag_xI4khGkpoWK1HF6hhy/baike/c0%3Dbaike92%2C5%2C5%2C92%2C30/sign=5e3814acf9edab64607f4592965fc4a6/14ce36d3d539b600c0c465d0eb50352ac65cb74b.jpg"></img>'
def login(request):
with open('login.html','r',encoding='utf-8') as f :
data=f.read()
return data
def time(request):
import datetime
now=datetime.datetime.now().strftime('%Y-%m-%d %X')
with open('time.html','r',encoding='utf-8') as f :
data=f.read()
data=data.replace('@@time@@',now)
return data
def user_list(request):
# 创建连接
conn = pymysql.connect(host='127.0.0.1', port=3306, user='root', passwd='123456', db='lqz')
cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)
cursor.execute("select id,name,password from user")
user_list = cursor.fetchall()
cursor.close()
conn.close()
tr_list=[]
for row in user_list:
tr='<tr><td>%s</td><td>%s</td><td>%s</td></tr>'%(row['id'],row['name'],row['password'])
tr_list.append(tr)
with open('user_list.html','r',encoding='utf-8') as f:
data=f.read()
data=data.replace('@@body@@',''.join(tr_list))
return data
def user_list_new(request):
# 创建连接
conn = pymysql.connect(host='127.0.0.1', port=3306, user='root', passwd='123456', db='lqz')
cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)
cursor.execute("select id,name,password from user")
user_list = cursor.fetchall()
cursor.close()
conn.close()
with open('user_list_new.html','r',encoding='utf-8') as f:
data=f.read()
from jinja2 import Template
template=Template(data)
response=template.render(user_list=user_list)
# response=template.render({'user_list':user_list})
return response
urls = [
('/index', index),
('/login', login),
('/time', time),
('/user_list', user_list),
('/user_list_new', user_list_new),
]
def run():
soc = socket.socket()
soc.bind(('127.0.0.1', 8006))
soc.listen(5)
while True:
conn, port = soc.accept()
data = conn.recv(1024)
# data=data.decode('utf-8')
print(data)
data = str(data, encoding='utf-8')
request_list = data.split('\r\n\r\n')
head_list = request_list[0].split('\r\n')
method, url, htt = head_list[0].split(' ')
# conn.send(b'hello web')
conn.send(b'HTTP/1.1 200 OK \r\n\r\n')
print(url)
func_name = None
for u in urls:
if url == u[0]:
func_name = u[1]
break
if func_name:
response = func_name(data)
else:
response = '404 not found'
conn.send(response.encode('utf-8'))
conn.close()
if __name__ == '__main__':
run()
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<form action="">
<p>用户名:<input type="text"></p>
<p>密码:<input type="password"></p>
</form>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
@@time@@
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>用户列表</title>
</head>
<body>
<table border="1">
<thead>
<tr>
<th>id</th>
<th>用户名</th>
<th>密码</th>
</tr>
</thead>
<tbody>
@@body@@
</tbody>
</table>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>用户列表</title>
</head>
<body>
<table border="1">
<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>
1.纯手撸web框架
? 1.手动书写socket
? 2.手动处理http格式数据
2.基于wsgiref模块
该模块实现了上面两个手动的过程
根据功能不同拆分成了不同的py文件
urls.py 只放路由与视图函数对应关系
views.py 放视图函数(函数,类)(放的是视图函数(处理业务逻辑的))
? templates 模板文件夹(一堆html文件)
? 拆分完成之后 如果想要添加功能,你仅仅只需要在上面两个地方动手脚就可以了
3.动静态网页
静态网页
数据是写死的 万年不变
动态网页
数据是实时获取的
eg:
1.后端获取当前时间展示到前端
2.后端获取数据库中的数据展示到前端
疑问:
如何将后端获取的数据 传递给html页面
后端获取的数据 传递给html页面 >>>: 模板的渲染
jinja2
pip3 install jinja2
模板语法(极其贴近python后端语法)
< p>{{ user }}
{% for user_dict in user_list %}
< tr>
< td>{{ user_dict.id }}
< td>{{ user_dict.name }}
< td>{{ user_dict.pwd }}
< /tr>
{% endfor %}
<!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>
<!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>
$$time$$
</body>
</html>
<!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>
<p>{{ user }}</p>
<p>{{ user.name }}</p>
<p>{{ user['pwd'] }}</p>
<p>{{ user.get('hobby') }}</p>
</body>
</html>
<!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>
<h1>index页面xxx</h1>
</body>
</html>
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)
current_path = env.get('PATH_INFO')
# if current_path == '/index':
# # 很多业务逻辑代码
# return [b'index']
# elif current_path == '/login':
# return [b'login']
# else:
# return [b'404 error']
# 先定义一个变量名 用来存储后续匹配到的函数名
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() # 启动服务端
from views import *
urls = [
('/index',index),
('/login',login),
('/xxx',xxx),
('/get_time',get_time),
('/get_user',get_user),
('/get_db',get_db),
]
def index(env):
return 'index'
def login(env):
return 'login'
def error(env):
return '404 error'
def xxx(env):
return 'xxx'
from datetime import datetime
def get_time(env):
current_time = datetime.now().strftime('%Y-%m-%d %X')
with open(r'C:\Users\Administrator\Desktop\day56\代码\web框架推导\templates\get_time.html','r',encoding='utf-8') as f:
data = f.read()
data = data.replace('$$time$$',current_time)
return data
from jinja2 import Template
def get_user(env):
d = {'name':'jason','pwd':'123','hobby':['read','running','music']}
with open(r'C:\Users\Administrator\Desktop\day56\代码\web框架推导\templates\get_user.html','r',encoding='utf-8') as f:
data = f.read()
temp = Template(data)
res = temp.render(user=d) # 将字典d传递给前端页面 页面上通过变量名user就能够获取到该字典
return res
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)
res = cursor.fetchall()
print(res)
with open(r'C:\Users\Administrator\Desktop\day56\代码\web框架推导\templates\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
标签:running 网络 用户 等等 本质 lan 完成 exec __name__
原文地址:https://www.cnblogs.com/TMesh-python/p/11730258.html