您的位置:首页 > 编程语言 > Python开发

python_web(三)一个简单web后端框架

2018-03-04 14:09 615 查看
#简单的web后端框架
#coding: utf-8

import socket

def log(*args, **kwargs):
print('log', *args, **kwargs)
#日志输出记录函数

def route_index():
header = 'HTTP/1.1 200 OK\r\nContent-Type: text/html\r\n'
body = '<h1>hello world</h1><img src="/doge.gif">'
#应将上式换做自己的图片路径
r = header + '\r\n' + body
return r.encode(encoding='utf-8')
#制作返回给客户端的内容,返回为bytes格式

def page(name):
with open(name, encoding='utf-8') as f:
return f.read()
#打开文件路径为name的html文件,返回值为文件编码后内容

def route_msg():
header = 'HTTP/1.1 200 OK\r\nContent-Type: text/html\r\n'
body = page('html_basic.html')
# 应将上式换做自己的html文件展现
r = header + '\r\n' + body
return r.encode(encoding='utf-8')
#制作返回给客户端的内容(其中含有html文件),返回为bytes格式

def route_image():
with open('doge.gif', 'rb') as f:
header = b'HTTP/1.1 200 OK\r\nContent-Type: image/gif\r\n'
img = header + b'\r\n' + f.read()
return img
#图片的处理函数,读取图片并生成响应返回(读取图片形式为rb,bytes)

def error(code = 404):
e = {
404: b'HTTP/1.1 404 NOT FOUND\r\n\r\n<h1>NOT FOUND</h1>',
}
return e.get(code, b'')
#404错误返回函数

def response_for_path(path):
r = {
'/': route_index,
'/doge.gif': route_image,
'/msg': route_msg,
}
response = r.get(path, error)
return response()
#路由函数,不同地址,出现不同的结果,取不到地址,返回错误函数

def run(host='', port = 3000):
with socket.socket() as s:
s.bind((host, port))
while True:
s.listen(5)
connection, address = s.accept()
request = connection.recv(1024)
log('raw, ', request)
request = request.decode('utf-8')
log('ip and request, {}\n{}'.format(address, request))
try:
path = request.split()[1]
log('path, ', path)
response = response_for_path(path)
connection.sendall(response)
except Exception as e:
log('error', e)
#异常时返回异常信息
connection.close()
#服务器运行函数,运行,连接

def main():
config = dict(
host = '',
port = 3000,
)
run(**config)
#生成配置并运行程序

if __name__ == '__main__':
main()

以上程序中所用到的知识点如下:

日志函数
用法:
def log(*args, **kwargs):
print('log', *args, **kwargs)
#python中一般不用print输出,而用log日志函数

服务器返回HTTP数据的格式
r = header + '\r\n' + body
header部分
#HTTP/1.1 是版本
#200 是状态码
#OK 是状态码的描述
body部分
#body部分为html代码

with...as语句
用法:
with open("文件路径") as f:
data = f.read()
print(data)
相当于
try:
data = f.read()
except:
print("读取文件失败!")
else:
print(data)
finally:
f.close()
# 使用 with 可以保证程序中断的时候正确关闭文件

字典的get()方法
用法:dict.get(key,  default=None)
#参数:key 字典中要查找的键
#返回值:返回指定键的值,如果值不在字典中返回第二个参数

**config
#真正的Python参数传递语法是**
#**config只是一种约定俗成的编程实践
#表示函数接收可变长度的关键字参数字典作为函数的输入

if __name__ == '__main__':
#此部分与c语言的main函数同
#此为python的入口函数
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息