Skip to main content

为学习目的而构建的 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 编写单元测试时,您可能需要使用两个内置的固定装置。第一个是appAPI类的一个实例:

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 (4.8 kB 查看哈希)

已上传 source

内置分布

gelatin_mattymar-0.0.2-py3-none-any.whl (5.0 kB 查看哈希

已上传 py3