开发者学堂课程【Python入门 2020年版:方法的封装】学习笔记,与课程紧密联系,让用户快速学习知识。
课程地址:https://developer.aliyun.com/learning/course/639/detail/10485
方法的封装
HTTP服务器优化
1.代码:
import json
from wsgiref.simple_server import make_server
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' :
with open(
‘page/xxxx.txt’,’r’,encoding=’’utf8) as file:
response = file.read()
elif path ==
‘/hello' :
with open(
‘page/hello.html’,’r’,encoding=’’utf8) as file:
response = file.read()
elif path ==
‘/info' :
name=
’jack’
with open(
‘page/info.html’,’r’,encoding=’’utf8) as file:
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()
demo_app
怎么用:
首先它是一个函数,需要两个参数,一个参数接收用户输入过来的所有参数,另一个参数start_response
是个函数。在这个里面,最终我们要做的工作是要写一个响应头,最后返回的内容是浏览器看到的内容,这就是我们的结构。
Path拿到响应的路径,根据不同的路径返回不同的内容,start_response需要一个响应头,然后响应内容。这个代码其实不够好,现在来写一个分装。
2.优化代码
(1)先要写一个加载一个文件的代码,可以看到上面代码中with open的代码还是重复很多的,先写一个load的代码,接下去写就不用写with open...那一大堆了。就是分装了一个函数。
代码:
from wsgiref.simple_server import make_server
def load_file(file_name):
try:
with open(
‘page/’+file_name,’r’,encoding=’utf8’) as file:
content=file.read()
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' :
name=
’jack’
with open(
‘page/info.html’,’r’,encoding=’’utf8) as file:
response =
file.read().format(username=name,age=18,gender=
’男’)
else:
status_code=
’404 Not Found’
esponse
= '页面走丢了’
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()
运行访问/demo和/hello,都能正常显示。
(2)传多个参数的(name,age那段)怎么写:
from wsgiref.simple_server import make_server
def load_file(file_name,**kwargs):
try:
with open(
‘page/’+file_name,’r’,encoding=’utf8’) as file:
content=file.read()
if kwargs:
content=content.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’)
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()
把 xxxx.txt 文件中输入内容“我是 demo 的内容,是读取 xxxx.txt 文件出来的”
运行访问 /demo,/hello,都正常显示
运行访问 /info,也显示内容,但没有填坑。原因是没有传参数,如果传了参数就能填坑了。
(3)传参:
elif path ==
‘/info' :
response=load_file(
‘info.html’,username=’zhangsan’,age=19,gender=’male’)
修改后代码:
from wsgiref.simple_server import make_server
def load_file(file_name,**kwargs):
try:
with open(
‘page/’+file_name,’r’,encoding=’utf8’) as file:
ontent=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()
{username}
,欢迎回来,你今年{age}岁了,你的性别是{gender}.format(username=kwargs[‘username’])
这样写也可以,这是把它一个个拿出来,但是最简单的方法是把字典拆包:
{username}
,欢迎回来,你今年{age}
岁了,你的性别是{gender}.format(**kwargs)
之前讲过 format 语句的使用,如果 info={...}这是一个字典,最简单的方式就是写个**把字典拆包让它一一对应。
老师把代码传到腾讯云服务器上,地址是106.54.81.174,端口是8080,大家可以访问。
但这还有个问题,还得把要访问的文件传到腾讯云上,才能访问,不然都是文件未找到。