使用Werkzeug API通过URL发送参数

时间:2018-12-19 17:20:45

标签: python werkzeug

我是Werkzeug的新手,它是从一个简单的案例开始的:一个将提供名称并显示“你好“名称””的URL,

我在macOS 10.14上,安装了要求的所有python库。

python脚本是

from werkzeug.wrappers import Request, Response

@Request.application
def application(environ, start_response):
    request = Request(environ)
    text = 'Hello %s!' % request.args.get('name', 'World')
    response = Response(text, mimetype='text/plain')
    return response(environ, start_response)

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

并贯穿

python shortly_3.py


 * Running on http://localhost:4000/ (Press CTRL+C to quit)
127.0.0.1 - - [19/Dec/2018 11:45:53] "GET / HTTP/1.1" 500 -

URL应当类似于

 http://localhost:4000/

加上名称参数

我尝试过

 http://localhost:4000?name=toto

但收到错误

Error on request:
TypeError: application() takes exactly 2 arguments (1 given)

将参数传递给应用程序的方式看起来不错,并且run_simple命令未显示传递参数的其他方式。

如何通过URL传递name参数?

如果我替换此呼叫

  text = 'Hello %s!' % request.args.get('name')

通过这个

  text = 'Hello %s!' % request.args.get('name', 'World')

以下提取仍然失败,并显示相同的错误

http://localhost:4000?name=toto

1 个答案:

答案 0 :(得分:0)

这是我最终附带的完整脚本(感谢Tomalak向我指出了create_app()函数)

import os
import redis
import urlparse
from werkzeug.wrappers import Request, Response
from werkzeug.routing import Map, Rule
from werkzeug.exceptions import HTTPException, NotFound
from werkzeug.wsgi import SharedDataMiddleware
from werkzeug.utils import redirect
from jinja2 import Environment, FileSystemLoader

class Shortly(object):

    def __init__(self, config):
        self.redis = redis.Redis(config['redis_host'], config['redis_port'])

    def dispatch_request(self, environ, request):
        request = Request(environ)
        text = 'Hello %s!' % request.args.get('name')
        response = Response(text, mimetype='text/plain')
        return response

    def wsgi_app(self, environ, start_response):
        request = Request(environ)
        response = self.dispatch_request(environ,request)
        return response(environ, start_response)

    def __call__(self, environ, start_response):
        return self.wsgi_app(environ, start_response)


def create_app(redis_host='localhost', redis_port=6379, with_static=True):
    app = Shortly({
        'redis_host':       redis_host,
        'redis_port':       redis_port
    })
    if with_static:
        app.wsgi_app = SharedDataMiddleware(app.wsgi_app, {
            '/static':  os.path.join(os.path.dirname(__file__), 'static')
        })
    return app

if __name__ == '__main__':
    from werkzeug.serving import run_simple
    app = create_app()
    run_simple('127.0.0.1', 5000, app, use_debugger=True, use_reloader=True)

在具有以下功能的浏览器中

http://127.0.0.1:5000/?name=toto

给予

Hello toto

如愿