轻量级asgi框架
bareasgi的Python项目详细描述
巴雷斯基
轻量级asgi框架(请阅读documentation)
状态
正在工作。
概述
这是一个bareasgi web服务器框架。目标是提供 一个最小的实现,具有其他功能(提供静态文件、cor、会话等) 正在由可选包实现
Web框架提供的某些功能对于给定的应用程序不是必需的,或者与 给定解所需的版本或变量
另请参见:
- bareASGI-cors用于跨源资源共享
- bareASGI-static用于静态文件服务
- bareASGI-jinja2用于Jinja2模板呈现
- bareASGI-graphql-next对于graphql
功能性
框架支持:
- http,
- WebSockets,
- 一种基于路径的路由器的基本方法,
- 中间件。
示例
这些示例使用uvicorn作为asgi服务器。
简单客户端
下面是一个简单的例子,它返回一些文本。
importuvicornfrombareasgiimportApplication,text_writerasyncdefhttp_request_callback(scope,info,matches,content):return200,[(b'content-type',b'text/plain')],text_writer('This is not a test')app=Application()app.http_router.add({'GET'},'/{rest:path}',http_request_callback)uvicorn.run(app,port=9009)
rest服务器
这是一个简单的rest服务器。
importuvicornimportjsonfrombareasgiimportApplication,text_reader,text_writerasyncdefget_info(scope,info,matches,content):text=json.dumps(info)return200,[(b'content-type',b'application/json')],text_writer(text)asyncdefset_info(scope,info,matches,content):text=awaittext_reader(content)data=json.loads(text)info.update(data)return204,None,Noneapp=Application(info={'name':'Michael Caine'})app.http_router.add({'GET'},'/info',get_info)app.http_router.add({'POST'},'/info',set_info)uvicorn.run(app,port=9009)
websockets
websocket示例可以在examples文件夹中找到。这是管理员。
asyncdeftest_callback(scope,info,matches,web_socket):awaitweb_socket.accept()try:whileTrue:text=awaitweb_socket.receive()iftextisNone:breakawaitweb_socket.send('You said: '+text)exceptExceptionaserror:print(error)awaitweb_socket.close()
中间件
下面是一个简单的中间件示例。
importuvicornfrombareasgiimportApplication,text_writerasyncdeffirst_middleware(scope,info,matches,content,handler):info['message']='This is first the middleware. 'response=awaithandler(scope,info,matches,content)returnresponseasyncdefsecond_middleware(scope,info,matches,content,handler):info['message']+='This is the second middleware.'response=awaithandler(scope,info,matches,content)returnresponseasyncdefhttp_request_callback(scope,info,matches,content):return200,[(b'content-type',b'text/plain')],text_writer(info['message'])app=Application(middlewares=[first_middleware,second_middleware])app.http_router.add({'GET'},'/test',http_request_callback)uvicorn.run(app,port=9009)