python中werkzeug库用法详解

        Werkzeug 是一个 Python 的 WSGI 工具库,它可以用来构建 Web 应用程序。下面是 Werkzeug 库的一些常见用法:

1、创建一个简单的 Web 应用程序

from werkzeug.wrappers import Request, Response


@Request.application
def application(request):
    return Response('Hello world')


if __name__ == '__main__':
    from werkzeug.serving import run_simple
    run_simple('localhost', 5000, application)

在上面的例子中,使用 @Request.application 装饰器将 application 函数转换为一个 WSGI 应用程序。然后使用 run_simple 函数在本地的 5000 端口运行应用程序。

运行结果:

2、路由和视图函数

 

from werkzeug.wrappers import Request, Response
from werkzeug.routing import Map, Rule


def hello_world(request):
    return Response("Hello world")


url_map = Map([
    Rule('/', endpoint='hello')
])


@Request.application
def application(request):
    urls = url_map.bind_to_environ(request.environ)
    endpoint, args = urls.match()
    if endpoint == 'hello':
        return hello_world(request)
    return Response('Not Found', status=404)


if __name__ == '__main__':
    from werkzeug.serving import run_simple
    run_simple('localhost', 5000, application)

在上面的例子中,我们使用 Map 和 Rule 类来定义 URL 路由规则,然后在 application 函数中根据路由规则执行相应的视图函数。

3、请求和响应对象

from werkzeug.wrappers import Request, Response


@Request.application
def application(request):
    name = request.args.get('name', 'World')
    response = Response(f'Hello, {name}!')
    response.headers['Content-Type'] = 'text/plain'
    return response


if __name__ == '__main__':
    from werkzeug.serving import run_simple

    run_simple('localhost', 5000, application)

在上面的例子中,我们使用 request 对象获取 URL 参数,并使用 response 对象返回一个带有参数的响应。

4、模板引擎

from werkzeug.wrappers import Request, Response
from werkzeug.utils import import_string
from werkzeug.routing import Map, Rule
from werkzeug.exceptions import HTTPException
from jinja2 import Environment, FileSystemLoader


class Application:
    def __init__(self, template_path='templates'):
        self.url_map = Map([
            Rule('/', endpoint='index'),
            Rule('/hello/<name>', endpoint='hello')
        ])
        self.template_env = Environment(loader=FileSystemLoader(template_path))

    def render_template(self, template_name, **context):
        template = self.template_env.get_template(template_name)
        return Response(template.render(**context), content_type='text/html')

    def index(self, request):
        return self.render_template('index.html')

    def hello(self, request, name):
        return self.render_template('hello.html', name=name)

    @Request.application
    def __call__(self, request):
        urls = self.url_map.bind_to_environ(request.environ)
        try:
            endpoint, args = urls.match()
            view = getattr(self, endpoint)
            return view(request, **args)
        except HTTPException as e:
            return e


if __name__ == '__main__':
    from werkzeug.serving import run_simple

    app = Application()
    run_simple('localhost', 5000, app)

在上面的例子中,我们创建了一个 Application 类来管理路由和视图函数,并使用 Jinja2 模板引擎来渲染 HTML 模板。

这只是 Werkzeug 库的一些常见用法,它还提供了许多其他功能,如表单处理、文件上传、cookie 和会话管理等。您可以查阅 Werkzeug 的官方文档来了解更多详细的用法和功能。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值