为学习目的而构建的bumbo python web框架。
bumbo-testing的Python项目详细描述
bumbo:python web框架是为了学习而构建的
bumbo是一个为学习而构建的python web框架。它是一个wsgi框架,可以与任何wsgi应用服务器(如gunicorn)一起使用。
安装
pip install bumbo
如何使用
基本用法:
frombumbo.apiimportAPIapp=API()@app.route("/home")defhome(request,response):response.text="Hello from the HOME page"@app.route("/hello/{name}")defgreeting(request,response,name):response.text=f"Hello, {name}"@app.route("/book")classBooksResource:defget(self,req,resp):resp.text="Books Page"defpost(self,req,resp):resp.text="Endpoint to create a book"@app.route("/template")deftemplate_handler(req,resp):resp.body=app.template("index.html",context={"name":"Bumbo","title":"Best Framework"}).encode()
单元测试
编写单元测试的推荐方法是使用pytest。有两个内置装置
在用bumbo编写单元测试时可能要使用的。第一个是app
,它是主API
类的实例:
deftest_route_overlap_throws_exception(app):@app.route("/")defhome(req,resp):resp.text="Welcome Home."withpytest.raises(AssertionError):@app.route("/")defhome2(req,resp):resp.text="Welcome Home2."
另一个是client
,您可以使用它向处理程序发送http请求。它以著名的requests为基础,应该很熟悉:
deftest_parameterized_route(app,client):@app.route("/{name}")defhello(req,resp,name):resp.text=f"hey {name}"assertclient.get("http://testserver/matthew").text=="hey matthew"
模板
模板的默认文件夹是templates
。您可以在初始化主API()
类时更改它:
app=API(templates_dir="templates_dir_name")
然后您可以像在处理程序中那样使用该文件夹中的HTML文件:
@app.route("/show/template")defhandler_with_template(req,resp):resp.html=app.template("example.html",context={"title":"Awesome Framework","body":"welcome to the future!"})
静态文件
与模板一样,静态文件的默认文件夹是static
,您可以覆盖它:
app=API(static_dir="static_dir_name")
然后您可以在HTML文件中使用此文件夹中的文件:
<!DOCTYPE html><htmllang="en"><head><metacharset="UTF-8"><title>{{title}}</title><linkhref="/static/main.css"rel="stylesheet"type="text/css"></head><body><h1>{{body}}</h1><p>This is a paragraph</p></body></html>
中间件
通过继承bumbo.middleware.Middleware
类并重写其两个方法,可以创建自定义中间件类
在每个请求之前和之后调用:
frombumbo.apiimportAPIfrombumbo.middlewareimportMiddlewareapp=API()classSimpleCustomMiddleware(Middleware):defprocess_request(self,req):print("Before dispatch",req.url)defprocess_response(self,req,res):print("After dispatch",req.url)app.add_middleware(SimpleCustomMiddleware)