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的入口函数
相关文章推荐
- Python学习 - 编写一个简单的web框架(一)
- Python学习 - 编写一个简单的web框架(二)
- 用Python写一个简单的Web框架
- 用Python写一个简单的Web框架
- Python3 自定义一个简单web框架
- Python之构建一个简单的web.py框架的服务器
- 我的第一个python web开发框架(2)——一个简单的小外包
- 使用Python的Tornado框架实现一个Web端图书展示页面
- [计网] 用python语言开发一个简单的web服务器和客户端
- 简单而直接的Python web 框架:web.py
- 使用Python的Bottle框架写一个简单的服务接口的示例
- android WebView将新浪天气为我所用 ------>仅供娱乐(一个android webview 执行js的简单框架)
- [Link]选择一个 Python Web 框架:Django vs Flask vs Pyramid
- 一个简单的python(tornado + sqlalchemy)web小例子
- 一个简单的SpringMVC框架web程序
- Python简单搭建一个Django框架
- werkzeug实现简单Python web框架(2):添加jinjia2模板支持
- 简单而直接的Python web 框架:web.py
- Django vs Flask vs Pyramid: 如何去选择一个Python Web框架