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

bumbo-testing的Python项目详细描述


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

purposePyPI

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第三方库


热门话题
关于如何将spring mvc重构为普通servlet或jetty处理程序的java建议   java循环和处理数据输入错误   使用java获取更改内容   java试图向一个数组中添加5张不同的“卡”,但它正在添加5张相同的卡   Java函数在Matlab类中变得未定义   多线程Java使用对象作为监视器,那个对象不是太重了吗?   将MySQL日期转换为Java日期:Android   java ResourceBundle在哪里。getBundle(“ResourceFile”,新语言环境(“us”,“us”))查找该文件?   java第一人称摄影机卷   如何在java中交替使用两个字符   addActionListener上下文中的java“this”   几天后,java Grails和Jasig CAS重定向循环   JavaAnt如何在javac中使用exclude、excludesfile?   java如何设置单行RecyclerView上的文本?