为学习目的而构建的 Gelatin Python Web 框架。
项目描述
Gelatin:为学习目的而构建的 Python Web 框架
Gelatin 是一个 WSGI 框架,可以与 Gunicorn 等任何 WSGI 应用服务器一起使用。
安装
pip install gelatin_mattymar
如何使用它
基本用法:
from jello.api import API
app = API()
@app.route('/home')
def home(request, response):
response.text = 'Hello from the HOME page'
@app.route('/users/{name}')
def greeting(request, response, name):
response.text = f'Hello there, {name}'
# Class-based handler
@app.route('/book')
class BooksResource:
def get(self, req, resp):
resp.text = 'Books Page'
def post(self, req, resp):
resp.text = 'Endpoint to create a book'
# Template handler
def template_handler(req, resp):
resp.body = app.template(
'index.html', context={"name": "Jello", "title": "Awesome framework"}
).encode()
单元测试
编写单元测试的推荐方法是使用pytest。在使用 Bumbo 编写单元测试时,您可能需要使用两个内置的固定装置。第一个是app主API类的一个实例:
def test_route_overlap_throws_exception(app):
@app.route("/")
def home(req, resp):
resp.text = "Welcome Home."
with pytest.raises(AssertionError):
@app.route("/")
def home2(req, resp):
resp.text = "Welcome Home2."
另一种是client您可以使用它来向您的处理程序发送 HTTP 请求。它基于著名的请求,应该很熟悉:
def test_parameterized_route(app, client):
@app.route("/{name}")
def hello(req, resp, name):
resp.text = f"hey {name}"
assert client.get("http://testserver/matthew").text == "hey matthew"
模板
模板的默认文件夹是templates. 您可以在初始化主API()类时更改它:
app = API(templates_dir="templates_dir_name")
然后,您可以像在处理程序中那样使用该文件夹中的 HTML 文件:
@app.route("/show/template")
def handler_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>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>{{title}}</title>
<link href="/static/main.css" rel="stylesheet" type="text/css">
</head>
<body>
<h1>{{body}}</h1>
<p>This is a paragraph</p>
</body>
</html>
中间件
您可以通过从类继承bumbo.middleware.Middleware并覆盖其在每个请求之前和之后调用的两个方法来创建自定义中间件类:
from bumbo.api import API
from bumbo.middleware import Middleware
app = API()
class SimpleCustomMiddleware(Middleware):
def process_request(self, req):
print("Before dispatch", req.url)
def process_response(self, req, res):
print("After dispatch", req.url)
app.add_middleware(SimpleCustomMiddleware)
项目详情
关
gelatin_mattymar -0.0.2.tar.gz 的哈希值
| 算法 | 哈希摘要 | |
|---|---|---|
| SHA256 | e1afb6eeb785d2dfe2834dffca4e76cdbf0104cedddaaab8b901c2ac20d93627 |
|
| MD5 | 8761d9790f6bc81e356cc27f211d293a |
|
| 布莱克2-256 | d80326354282797951e0ce33b54a1b0842e6c7e03362067ddf42e96eeec04aab |
关
gelatin_mattymar -0.0.2-py3-none-any.whl 的哈希值
| 算法 | 哈希摘要 | |
|---|---|---|
| SHA256 | 8846ccf773e4c689b46af59f0c64292ad07d6cbea90adeb447face26ba047a90 |
|
| MD5 | ca714a05c4831512084cc77b67a7193a |
|
| 布莱克2-256 | bba909c4aeaa356344f002d7858d982be28484c17d0d650b85f787190cfb10ad |