Detailed usage of werkzeug library in python

        Werkzeug is a Python WSGI tool library that can be used to build web applications. Here are some common uses of the Werkzeug library:

1. Create a simple web application

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)

In the above example, the application function is converted to a WSGI application using the @Request.application decorator. Then use the run_simple function to run the application locally on port 5000.

operation result:

2. Routing and view functions

 

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)

In the above example, we use the Map and Rule classes to define the URL routing rules, and then execute the corresponding view functions in the application function according to the routing rules.

3. Request and response objects

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)

In the above example, we use the request object to get the URL parameters and use the response object to return a response with the parameters.

4. Template engine

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)

In the above example, we created an Application class to manage routing and view functions, and used the Jinja2 template engine to render HTML templates.

These are just some of the common uses of the Werkzeug library, which also provides many other features such as form handling, file uploading, cookie and session management, and more. You can refer to Werkzeug's official documentation for more detailed usage and functions.

Guess you like

Origin blog.csdn.net/weixin_44799217/article/details/132030822