组件注入、快速路由和非全局(分层)中间件。给你的sanic申请一个繁荣!
sanic-boom的Python项目详细描述
组件注入、快速路由和非全局(分层)中间件。给你的sanic申请一个繁荣!
简而言之
"""Example code taken from https://marshmallow.readthedocs.io/en/3.0/quickstart.html#quickstart """importdatetimeasdtimportinspectimporttypingastfrommarshmallowimportSchema,fields,post_loadfromsanic.exceptionsimportServerErrorfromsanic.responseimporttextfromsanic_boomimportComponent,SanicBoom# --------------------------------------------------------------------------- ## marshmallow related code# --------------------------------------------------------------------------- #classUser(object):def__init__(self,name,email):self.name=nameself.email=emailself.created_at=dt.datetime.now()def__repr__(self):return"<User(name={self.name!r})>".format(self=self)defsay_hi(self):return"hi, my name is {}".format(self.name)classUserSchema(Schema):name=fields.Str()email=fields.Email()created_at=fields.DateTime()@post_loaddefmake_user(self,data):returnUser(**data)# --------------------------------------------------------------------------- ## sanic-boom related code# --------------------------------------------------------------------------- #classJSONBody(t.Generic[t.T_co]):passclassJSONBodyComponent(Component):defresolve(self,param:inspect.Parameter)->bool:ifhasattr(param.annotation,"__origin__"):returnparam.annotation.__origin__==JSONBodyreturnFalseasyncdefget(self,request,param:inspect.Parameter)->object:inferred_type=param.annotation.__args__[0]try:returninferred_type().load(request.json).dataexceptException:raiseServerError("Couldn't convert JSON body to {!s}".format(inferred_type))app=SanicBoom(__name__)app.add_component(JSONBodyComponent)@app.post("/")asyncdefhandler(user:JSONBody[UserSchema]):# notice the handler parametersreturntext(user.say_hi())if__name__=="__main__":app.run(host="0.0.0.0",port=8000,workers=1)
$ curl -v http://localhost:8000/ -d '{"name":"John Doe","email":"john.doe@example.tld"}' * Trying ::1... * TCP_NODELAY set * connect to ::1 port 8000 failed: Connection refused * Trying 127.0.0.1... * TCP_NODELAY set * Connected to localhost (127.0.0.1) port 8000 (#0) > POST / HTTP/1.1 > Host: localhost:8000 > User-Agent: curl/7.61.1 > Accept: */* > Content-Length: 50 > Content-Type: application/x-www-form-urlencoded > * upload completely sent off: 50 out of 50 bytes < HTTP/1.1 200 OK < Connection: keep-alive < Keep-Alive: 5 < Content-Length: 23 < Content-Type: text/plain; charset=utf-8 < * Connection #0 to host localhost left intact hi, my name is John Doe
警告
重要:sanic-boom处于开发的早期阶段!请谨慎使用,并注意某些功能和api可能会在不同版本之间发生变化,直到它们超出alpha。
依赖性
sanic-boom依赖于两个“未知”库(均由sanic-boom的作者创建):
重要
由于xrtr替换了sanic-boom中引擎盖下的sanic默认路由器,因此开发人员阅读其文档(在上面提供的链接中)非常重要。
许可证
sanic-boom是根据MIT许可证发行的自由软件。
变更日志
2018年10月23日v0.1.2
- 在BoomRequest上添加了components属性,因此可以处理任何“剩余”请求属性(如打开的数据库连接)。
2018年10月18日v0.1.1
- 修正了从HTTPMethodView类派生的处理程序未被执行的错误(因为它们的签名实际上是*args, **kwargs)。
2018年10月17日v0.1.0
- pypi上的第一个版本。(可能)不稳定。