fromflaskimportFlask,Response,jsonifyfrompaitimportfieldfrompait.app.flaskimportpaitfrompait.exceptionsimportTipExceptiondefapi_exception(exc:Exception)->Response:ifisinstance(exc,TipException):exc=exc.excreturnjsonify({"data":str(exc)})fake_db_dict:dict={"u12345":"so1n"}defget_user_by_token(token:str=field.Header.i())->str:iftokennotinfake_db_dict:raiseRuntimeError(f"Can not found by token:{token}")returnfake_db_dict[token]@pait()defdemo(token:str=field.Depends.i(get_user_by_token))->dict:return{"user":token}app=Flask("demo")app.add_url_rule("/api/demo",view_func=demo,methods=["GET"])app.errorhandler(Exception)(api_exception)if__name__=="__main__":app.run(port=8000)
fromstarlette.applicationsimportStarlettefromstarlette.requestsimportRequestfromstarlette.responsesimportJSONResponsefromstarlette.routingimportRoutefrompaitimportfieldfrompait.app.starletteimportpaitfrompait.exceptionsimportTipExceptionasyncdefapi_exception(request:Request,exc:Exception)->JSONResponse:ifisinstance(exc,TipException):exc=exc.excreturnJSONResponse({"data":str(exc)})fake_db_dict:dict={"u12345":"so1n"}asyncdefget_user_by_token(token:str=field.Header.i())->str:iftokennotinfake_db_dict:raiseRuntimeError(f"Can not found by token:{token}")returnfake_db_dict[token]@pait()asyncdefdemo(token:str=field.Depends.i(get_user_by_token))->JSONResponse:returnJSONResponse({"user":token})app=Starlette(routes=[Route("/api/demo",demo,methods=["GET"])])app.add_exception_handler(Exception,api_exception)if__name__=="__main__":importuvicornuvicorn.run(app)
fromsanicimportHTTPResponse,Request,Sanic,jsonfrompaitimportfieldfrompait.app.sanicimportpaitfrompait.exceptionsimportTipExceptionasyncdefapi_exception(request:Request,exc:Exception)->HTTPResponse:ifisinstance(exc,TipException):exc=exc.excreturnjson({"data":str(exc)})fake_db_dict:dict={"u12345":"so1n"}asyncdefget_user_by_token(token:str=field.Header.i())->str:iftokennotinfake_db_dict:raiseRuntimeError(f"Can not found by token:{token}")returnfake_db_dict[token]@pait()asyncdefdemo(token:str=field.Depends.i(get_user_by_token))->HTTPResponse:returnjson({"user":token})app=Sanic("demo")app.add_route(demo,"/api/demo",methods={"GET"})app.exception(Exception)(api_exception)if__name__=="__main__":importuvicornuvicorn.run(app)
fromtornado.ioloopimportIOLoopfromtornado.webimportApplication,RequestHandlerfrompaitimportfieldfrompait.app.tornadoimportpaitfrompait.exceptionsimportTipExceptionfrompait.openapi.doc_routeimportAddDocRouteclass_Handler(RequestHandler):def_handle_request_exception(self,exc:BaseException)->None:ifisinstance(exc,TipException):exc=exc.excself.write({"data":str(exc)})self.finish()fake_db_dict:dict={"u12345":"so1n"}asyncdefget_user_by_token(token:str=field.Header.i())->str:iftokennotinfake_db_dict:raiseRuntimeError(f"Can not found by token:{token}")returnfake_db_dict[token]classDemoHandler(_Handler):@pait()asyncdefget(self,token:str=field.Depends.i(get_user_by_token))->None:self.write({"user":token})app:Application=Application([(r"/api/demo",DemoHandler)])AddDocRoute(app)if__name__=="__main__":app.listen(8000)IOLoop.instance().start()
在运行代码并调用curl命令可以发现发现这段代码工作一切正常,当token存在时返回用户,不存在则返回抛错信息:
After running the code and calling the curl command, can find that this code works normally.
When the token exists, it returns to the user. If it does not exist, it returns an error message:
curl "http://127.0.0.1:8000/api/demo" --header "token:u12345"{"user":"so1n"}curl "http://127.0.0.1:8000/api/demo" --header "token:u123456"{"data":"Can not found by token:u123456"}
fromflaskimportFlask,Response,jsonifyfrompaitimportfieldfrompait.app.flaskimportpaitfrompait.exceptionsimportTipExceptiondefapi_exception(exc:Exception)->Response:ifisinstance(exc,TipException):exc=exc.excreturnjsonify({"data":str(exc)})fake_db_dict:dict={"u12345":"so1n"}defcheck_token(token:str=field.Header.i())->str:iflen(token)!=6andtoken[0]!="u":raiseRuntimeError("Illegal Token")returntokendefget_user_by_token(token:str=field.Depends.i(check_token))->str:iftokennotinfake_db_dict:raiseRuntimeError(f"Can not found by token:{token}")returnfake_db_dict[token]@pait()defdemo(token:str=field.Depends.i(get_user_by_token))->dict:return{"user":token}app=Flask("demo")app.add_url_rule("/api/demo",view_func=demo,methods=["GET"])app.errorhandler(Exception)(api_exception)if__name__=="__main__":app.run(port=8000)
fromstarlette.applicationsimportStarlettefromstarlette.requestsimportRequestfromstarlette.responsesimportJSONResponsefromstarlette.routingimportRoutefrompaitimportfieldfrompait.app.starletteimportpaitfrompait.exceptionsimportTipExceptionasyncdefapi_exception(request:Request,exc:Exception)->JSONResponse:ifisinstance(exc,TipException):exc=exc.excreturnJSONResponse({"data":str(exc)})fake_db_dict:dict={"u12345":"so1n"}defcheck_token(token:str=field.Header.i())->str:iflen(token)!=6andtoken[0]!="u":raiseRuntimeError("Illegal Token")returntokenasyncdefget_user_by_token(token:str=field.Depends.i(check_token))->str:iftokennotinfake_db_dict:raiseRuntimeError(f"Can not found by token:{token}")returnfake_db_dict[token]@pait()asyncdefdemo(token:str=field.Depends.i(get_user_by_token))->JSONResponse:returnJSONResponse({"user":token})app=Starlette(routes=[Route("/api/demo",demo,methods=["GET"])])app.add_exception_handler(Exception,api_exception)if__name__=="__main__":importuvicornuvicorn.run(app)
fromsanicimportHTTPResponse,Request,Sanic,jsonfrompaitimportfieldfrompait.app.sanicimportpaitfrompait.exceptionsimportTipExceptionasyncdefapi_exception(request:Request,exc:Exception)->HTTPResponse:ifisinstance(exc,TipException):exc=exc.excreturnjson({"data":str(exc)})fake_db_dict:dict={"u12345":"so1n"}defcheck_token(token:str=field.Header.i())->str:iflen(token)!=6andtoken[0]!="u":raiseRuntimeError("Illegal Token")returntokenasyncdefget_user_by_token(token:str=field.Depends.i(check_token))->str:iftokennotinfake_db_dict:raiseRuntimeError(f"Can not found by token:{token}")returnfake_db_dict[token]@pait()asyncdefdemo(token:str=field.Depends.i(get_user_by_token))->HTTPResponse:returnjson({"user":token})app=Sanic("demo")app.add_route(demo,"/api/demo",methods={"GET"})app.exception(Exception)(api_exception)if__name__=="__main__":importuvicornuvicorn.run(app)
fromtornado.ioloopimportIOLoopfromtornado.webimportApplication,RequestHandlerfrompaitimportfieldfrompait.app.tornadoimportpaitfrompait.exceptionsimportTipExceptionfrompait.openapi.doc_routeimportAddDocRouteclass_Handler(RequestHandler):def_handle_request_exception(self,exc:BaseException)->None:ifisinstance(exc,TipException):exc=exc.excself.write({"data":str(exc)})self.finish()fake_db_dict:dict={"u12345":"so1n"}defcheck_token(token:str=field.Header.i())->str:iflen(token)!=6andtoken[0]!="u":raiseRuntimeError("Illegal Token")returntokenasyncdefget_user_by_token(token:str=field.Depends.i(check_token))->str:iftokennotinfake_db_dict:raiseRuntimeError(f"Can not found by token:{token}")returnfake_db_dict[token]classDemoHandler(_Handler):@pait()asyncdefget(self,token:str=field.Depends.i(get_user_by_token))->None:self.write({"user":token})app:Application=Application([(r"/api/demo",DemoHandler)])AddDocRoute(app)if__name__=="__main__":app.listen(8000)IOLoop.instance().start()
curl "http://127.0.0.1:8000/api/demo" --header "token:u12345"{"user":"so1n"}curl "http://127.0.0.1:8000/api/demo" --header "token:u123456"{"data":"Can not found by token:u123456"}curl "http://127.0.0.1:8000/api/demo" --header "token:fu12345"{"data":"Illegal Token"}
fromflaskimportFlask,Response,jsonifyfrompaitimportfieldfrompait.app.flaskimportpaitfrompait.exceptionsimportTipExceptiondefapi_exception(exc:Exception)->Response:ifisinstance(exc,TipException):exc=exc.excreturnjsonify({"data":str(exc)})fake_db_dict:dict={"u12345":"so1n"}classGetUserDepend(object):user_name:str=field.Query.i()def__call__(self,token:str=field.Header.i())->str:iftokennotinfake_db_dict:raiseRuntimeError(f"Can not found by token:{token}")user_name=fake_db_dict[token]ifuser_name!=self.user_name:raiseRuntimeError("The specified user could not be found through the token")returnuser_name@pait()defdemo(token:str=field.Depends.i(GetUserDepend))->dict:return{"user":token}app=Flask("demo")app.add_url_rule("/api/demo",view_func=demo,methods=["GET"])app.errorhandler(Exception)(api_exception)if__name__=="__main__":app.run(port=8000)
fromstarlette.applicationsimportStarlettefromstarlette.requestsimportRequestfromstarlette.responsesimportJSONResponsefromstarlette.routingimportRoutefrompaitimportfieldfrompait.app.starletteimportpaitfrompait.exceptionsimportTipExceptionasyncdefapi_exception(request:Request,exc:Exception)->JSONResponse:ifisinstance(exc,TipException):exc=exc.excreturnJSONResponse({"data":str(exc)})fake_db_dict:dict={"u12345":"so1n"}classGetUserDepend(object):user_name:str=field.Query.i()asyncdef__call__(self,token:str=field.Header.i())->str:iftokennotinfake_db_dict:raiseRuntimeError(f"Can not found by token:{token}")user_name=fake_db_dict[token]ifuser_name!=self.user_name:raiseRuntimeError("The specified user could not be found through the token")returnuser_name@pait()asyncdefdemo(token:str=field.Depends.i(GetUserDepend))->JSONResponse:returnJSONResponse({"user":token})app=Starlette(routes=[Route("/api/demo",demo,methods=["GET"])])app.add_exception_handler(Exception,api_exception)if__name__=="__main__":importuvicornuvicorn.run(app)
fromsanicimportHTTPResponse,Request,Sanic,jsonfrompaitimportfieldfrompait.app.sanicimportpaitfrompait.exceptionsimportTipExceptionasyncdefapi_exception(request:Request,exc:Exception)->HTTPResponse:ifisinstance(exc,TipException):exc=exc.excreturnjson({"data":str(exc)})fake_db_dict:dict={"u12345":"so1n"}classGetUserDepend(object):user_name:str=field.Query.i()asyncdef__call__(self,token:str=field.Header.i())->str:iftokennotinfake_db_dict:raiseRuntimeError(f"Can not found by token:{token}")user_name=fake_db_dict[token]ifuser_name!=self.user_name:raiseRuntimeError("The specified user could not be found through the token")returnuser_name@pait()asyncdefdemo(token:str=field.Depends.i(GetUserDepend))->HTTPResponse:returnjson({"user":token})app=Sanic("demo")app.add_route(demo,"/api/demo",methods={"GET"})app.exception(Exception)(api_exception)if__name__=="__main__":importuvicornuvicorn.run(app)
fromtornado.ioloopimportIOLoopfromtornado.webimportApplication,RequestHandlerfrompaitimportfieldfrompait.app.tornadoimportpaitfrompait.exceptionsimportTipExceptionfrompait.openapi.doc_routeimportAddDocRouteclass_Handler(RequestHandler):def_handle_request_exception(self,exc:BaseException)->None:ifisinstance(exc,TipException):exc=exc.excself.write({"data":str(exc)})self.finish()fake_db_dict:dict={"u12345":"so1n"}classGetUserDepend(object):user_name:str=field.Query.i()asyncdef__call__(self,token:str=field.Header.i())->str:iftokennotinfake_db_dict:raiseRuntimeError(f"Can not found by token:{token}")user_name=fake_db_dict[token]ifuser_name!=self.user_name:raiseRuntimeError("The specified user could not be found through the token")returnuser_nameclassDemoHandler(_Handler):@pait()asyncdefget(self,token:str=field.Depends.i(GetUserDepend))->None:self.write({"user":token})app:Application=Application([(r"/api/demo",DemoHandler)])AddDocRoute(app)if__name__=="__main__":app.listen(8000)IOLoop.instance().start()
该类实例化后,Pait就能正常解析出pait_handler的函数签名是pait_handler(uid: str = field.Query.i(), user_name: str = field.Query.i()) -> Any
而第二段高亮代码中则把Depend参数中的基于函数的Depend替换为基于类的Depend。
在运行代码并执行如下curl命令,可以看到如下输出:
➜ ~ curl "http://127.0.0.1:8000/api/demo" --header "token:u12345" {"data":"Can not found user_name value"} ➜ ~ curl "http://127.0.0.1:8000/api/demo?user_name=so1n" --header "token:u12345" {"user":"so1n"} ➜ ~ curl "http://127.0.0.1:8000/api/demo?user_name=faker" --header "token:u12345" {"data":"The specified user could not be found through the token"}
frompaitimportfieldfrompait.utilimportpartial_wrapperclassGetUserDepend(object):user_name:str=field.Query.i()age:int=field.Query.i()def__init__(self,age_limit:int=18)->None:self.age_limit:int=age_limitdef__call__(self,token:str=field.Header.i())->str:iftokennotinfake_db_dict:raiseRuntimeError(f"Can not found by token:{token}")user_name=fake_db_dict[token]ifuser_name!=self.user_name:raiseRuntimeError("The specified user could not be found through the token")ifself.age<self.age_limit:raiseValueError("Minors cannot access")returnuser_name@pait()defdemo(user_name:str=field.Depends.i(partial_wrapper(GetUserDepend,age_limit=16))):pass@pait()defdemo1(user_name:str=field.Depends.i(GetUserDepend)):pass
fromflaskimportFlask,Response,jsonifyfrompaitimportfieldfrompait.app.flaskimportpaitfrompait.exceptionsimportTipExceptiondefapi_exception(exc:Exception)->Response:ifisinstance(exc,TipException):exc=exc.excreturnjsonify({"data":str(exc)})fake_db_dict:dict={"u12345":"so1n"}defget_user_by_token(token:str=field.Header.i())->str:iftokennotinfake_db_dict:raiseRuntimeError(f"Can not found by token:{token}")returnfake_db_dict[token]@pait(pre_depend_list=[get_user_by_token])defdemo()->dict:return{"msg":"success"}app=Flask("demo")app.add_url_rule("/api/demo",view_func=demo,methods=["GET"])app.errorhandler(Exception)(api_exception)if__name__=="__main__":app.run(port=8000)
fromstarlette.applicationsimportStarlettefromstarlette.requestsimportRequestfromstarlette.responsesimportJSONResponsefromstarlette.routingimportRoutefrompaitimportfieldfrompait.app.starletteimportpaitfrompait.exceptionsimportTipExceptionasyncdefapi_exception(request:Request,exc:Exception)->JSONResponse:ifisinstance(exc,TipException):exc=exc.excreturnJSONResponse({"data":str(exc)})fake_db_dict:dict={"u12345":"so1n"}asyncdefget_user_by_token(token:str=field.Header.i())->str:iftokennotinfake_db_dict:raiseRuntimeError(f"Can not found by token:{token}")returnfake_db_dict[token]@pait(pre_depend_list=[get_user_by_token])asyncdefdemo()->JSONResponse:returnJSONResponse({"msg":"success"})app=Starlette(routes=[Route("/api/demo",demo,methods=["GET"])])app.add_exception_handler(Exception,api_exception)if__name__=="__main__":importuvicornuvicorn.run(app)
fromsanicimportHTTPResponse,Request,Sanic,jsonfrompaitimportfieldfrompait.app.sanicimportpaitfrompait.exceptionsimportTipExceptionasyncdefapi_exception(request:Request,exc:Exception)->HTTPResponse:ifisinstance(exc,TipException):exc=exc.excreturnjson({"data":str(exc)})fake_db_dict:dict={"u12345":"so1n"}asyncdefget_user_by_token(token:str=field.Header.i())->str:iftokennotinfake_db_dict:raiseRuntimeError(f"Can not found by token:{token}")returnfake_db_dict[token]@pait(pre_depend_list=[get_user_by_token])asyncdefdemo(request:Request)->HTTPResponse:returnjson({"msg":"success"})app=Sanic("demo")app.add_route(demo,"/api/demo",methods={"GET"})app.exception(Exception)(api_exception)if__name__=="__main__":importuvicornuvicorn.run(app)
fromtornado.ioloopimportIOLoopfromtornado.webimportApplication,RequestHandlerfrompaitimportfieldfrompait.app.tornadoimportpaitfrompait.exceptionsimportTipExceptionfrompait.openapi.doc_routeimportAddDocRouteclass_Handler(RequestHandler):def_handle_request_exception(self,exc:BaseException)->None:ifisinstance(exc,TipException):exc=exc.excself.write({"data":str(exc)})self.finish()fake_db_dict:dict={"u12345":"so1n"}asyncdefget_user_by_token(token:str=field.Header.i())->str:iftokennotinfake_db_dict:raiseRuntimeError(f"Can not found by token:{token}")returnfake_db_dict[token]classDemoHandler(_Handler):@pait(pre_depend_list=[get_user_by_token])asyncdefget(self)->None:self.write({"msg":"success"})app:Application=Application([(r"/api/demo",DemoHandler)])AddDocRoute(app)if__name__=="__main__":app.listen(8000)IOLoop.instance().start()
运行代码并执行curl命令后,通过如下输出结果可以看到Pre-Depend能够正常工作。:
curl "http://127.0.0.1:8000/api/demo" --header "token:u12345"{"msg":"success"}curl "http://127.0.0.1:8000/api/demo" --header "token:u123456"{"data":"Can not found by token:u123456"}