上一篇:WSGI不同路径返回不同内容| 手把手教你入门Python之一百一十四
下一篇:方法的封装 | 手把手教你入门Python之一百一十六
本文来自于千锋教育在阿里云开发者社区学习中心上线课程《Python入门2020最新大课》,主讲人姜伟。
读取文件并返回给浏览器
hello.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
.box {
margin:0 auto;
}
div {
width:1000px;
}
.top {
height:80px;
background-color:red;
margin-bottom:10px;
}
.middle {
height:400px;
}
.left {
width:100px;
height:100%;
background-color:yellow;
float:left;
margin-right:10px;
}
.content {
width:780px;
height:100%;
background-color:pink;
float:left;
margin-right:10px;
}
.right {
width:100px;
height:100%;
background-color:blue;
float:left;
}
.bottom {
height:80px;
background-color:lime;
margin-top:10px;
}
</style>
</head>
<body>
<div class="box">
<div class="top"></div>
<div class="middle">
<div class="left"></div>
<div class="content"></div>
<div class="right"></div>
</div>
<div class="bottom"></div>
</div>
</body>
</html>
info.html:
{username},欢迎回来,你今年{age}岁了,你的性别是{gender}
读取文件:
import json
from wsgiref.simple_server import make_server
def demo_app(environ, start_response):
path = environ['PATH_INFO']
# print(environ.get('QUERY_STRING')) # QUERY_STRING ==> 获取到客户端GET请求方式传递的参数
# POST 请求数据的方式后面再说
status_code = '200 OK'
if path == '/':
response = '欢迎来到我的首页'
elif path == '/test':
response = json.dumps({'name': 'zhangsan', 'age': 18})
elif path == '/demo':
with open('pages/xxxx.txt', 'r', encoding='utf8') as file:
response = file.read()
elif path == '/hello':
with open('pages/hello.html', 'r', encoding='utf8') as file:
response = file.read()
elif path == '/info':
# 查询数据库,获取到用户名
name = 'jack'
with open('pages/info.html', 'r', encoding='utf8') as file:
# '{username}, 欢迎回来'.format(username=name)
# flask django 模板,渲染引擎
response = file.read().format(username=name, age=18, gender='男')
else:
status_code = '404 Not Found'
response = '页面走丢了'
start_response(status_code, [('Content-Type', 'text/html;charset=utf8')])
return [response.encode('utf8')]
if __name__ == '__main__':
httpd = make_server('', 8080, demo_app)
sa = httpd.socket.getsockname()
print("Serving HTTP on", sa[0], "port", sa[1], "...")
httpd.serve_forever()
返回JSON字符串:
返回文件内容:
返回hello.html:
返回info.html:
HTTP服务器优化
import json
from wsgiref.simple_server import make_server
def load_file(file_name, **kwargs):
try:
with open('pages/' + file_name, 'r', encoding='utf8') as file:
content = file.read()
if kwargs: # kwargs = {'username':'zhangsan','age':19,'gender':'male'}
content = content.format(**kwargs)
# {username},欢迎回来,你今年{age}岁了,你的性别是{gender}.format(**kwargs)
return content
except FileNotFoundError:
print('文件未找到')
def demo_app(environ, start_response):
path = environ['PATH_INFO']
status_code = '200 OK'
if path == '/':
response = '欢迎来到我的首页'
elif path == '/test':
response = json.dumps({'name': 'zhangsan', 'age': 18})
elif path == '/demo':
response = load_file('xxxx.txt')
elif path == '/hello':
response = load_file('hello.html')
elif path == '/info':
response = load_file('info.html', username='zhangsan', age=19, gender='male')
else:
status_code = '404 Not Found'
response = '页面走丢了'
start_response(status_code, [('Content-Type', 'text/html;charset=utf8')])
return [response.encode('utf8')]
if __name__ == '__main__':
httpd = make_server('', 8080, demo_app)
sa = httpd.socket.getsockname()
print("Serving HTTP on", sa[0], "port", sa[1], "...")
httpd.serve_forever()