引言
一个quickstart不能够暴露所有功能的框架他就不算是微框架
特别是某些同步框架写的文档比python文档还复杂,有意义吗。我觉得没有意义,所以我不会去看,那么我就自己写。
下面是Lawliet的Quickstart
安装
pip install lawliet
Hello World
>>>from lawliet.tools import hello
>>>hello('Hello World!')
running ==> http://127.0.0.1:5000/
url映射
Url(['url路径', func, [method方法]]), 多个url映射如下
from lawliet import Url, app
from lawliet.test import hello
def index():
return 'Hello, World!'
Url(
['/', index, ['GET']],
['/hello', hello, ['GET', 'POST']]
)
if __name__ == '__main__':
app.run()
应答方式
返回json
return {'msg': 'success'}
返回str
return 'hello world'
其他数据结构
from lawliet import Response
Response(xml, headers={'Content-type': 'application/xml'})
返回http code
from lawliet import abort
abort(401)
url跳转
from lawliet import redirect
redirect('https://www.python.com/')
注: Response, abort, redirect方法放在try模块,需要把异常Response raise出来
请求参数获取
json参数
def index(request):
get_json = request.json()
form_data参数
def index(request):
get_file = request.file('test_file', use_temp=True)
get_code = request.form('code')
注: use_temp是非必传参数,True缓存到磁盘,False缓存到内存,默认是缓存到内存
注: form跟file操作的同一个二进制流,所以设use_temp为True必须放到第一个使用form方法或者file方法里
url参数
def index(request):
get_name = request.get('name')
header参数
def index(request):
get_origin = request.header('origin')
通用获取方式 or 其他content_type类型的获取方式
def index(request):
content_length = request.environ.get('CONTENT_LENGTH')
content_type = request.environ.get('CONTENT_TYPE')
if content_type == 'application/xml':
output = request.environ.pop('wsgi.input')
data = output.read(self.content_length)
附录
gunicorn启动lawliet
#hello.py
from lawliet import Url, Route
def index():
return 'Hello, World!'
Url(['/', index, ['GET']])
gunicron -w4 -b127.0.0.1:5000 hello:Route
or gunicorn -c gun.conf hello:Route