为学习目的而构建的bumbo python web框架。

bumbo的Python项目详细描述


bumbo:python web框架是为了学习而构建的

purposecodecov

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)

欢迎加入QQ群-->: 979659372 Python中文网_新手群

推荐PyPI第三方库


热门话题
java如何将枚举常量声明为空白字符?   java GWT/GXT在服务器上使用对象与在客户端使用对象允许什么?   java会等到方法完成后再调用该方法   Spring Security中使用UserDetails登录的java实现不起作用   使用Google Drive API时,不会显示java上载的文件   java如何使用对象参数对Arraylist中的对象进行排序   java页面上不存在元素   java Eclipse Indigo未命中断点   selenium中的JavaTestNG建议使用哪些注释   java无法从trycatch嵌套for循环中提取字符串   java是响应DROOLS中规则的专用对象   如何在安卓 java中将数字字符串值转换为整数?   调用wsdl URL的Java代码获得了连接超时,但使用SOAP UI调用相同的wsdl URL没有问题   spring集成测试给定/When/Then Java