gpt4 book ai didi

python - 如何使用 wsgi 在 URL 路径中包含变量? (不是查询字符串)

转载 作者:太空狗 更新时间:2023-10-29 21:44:59 24 4
gpt4 key购买 nike

我确信对此有答案,但我似乎找不到。另外,请务必注意,我是 Python 的新手。

我最近克隆了这个使用 python 和 wsgi 的 repo https://github.com/hypothesis/via用于路由。

我想要的是在 url 路径中有一个参数(没有查询字符串):

meow.com/cat_articles/:article_id # i.e. meow.com/cat_articles/677

我怎样才能做到这一点?

作为引用,我的最终目标是将我自己的路径添加到此文件:

https://github.com/hypothesis/via/blob/master/via/app.py

最佳答案

如何将这样的路由添加到应用程序取决于该应用程序使用哪个或哪些库来实现 WSGI。我看到您链接到的 app.py 文件正在使用 werkzeug(以及 static)。

这里有一些在 werkzeug 中使用占位符进行路由的有用引用:

我几乎没有使用过 werkzeug 并且不会声称这绝对是最好的方法,但是一个选择是通过 werkzeug 添加另一个 WSGI 应用程序到 wsgi.DispatcherMiddleware 在该文件的底部调用。

这里有一些拼凑的示例代码,可让您在您共享的 app.py 文件的上下文中开始。尝试删除 this line 之后的所有内容并用此代码替换它:

from werkzeug.routing import Map, Rule
from werkzeug.exceptions import HTTPException

my_url_map = Map([
# Note that this rule builds on the `/cat_articles` prefix used in the `DispatcherMiddleware` call further down
Rule('/<article_id>', endpoint='get_cat_article')
])

def cat_app(environ, start_response):
urls = my_url_map.bind_to_environ(environ)
try:
endpoint, args = urls.match()
except HTTPException, e:
return e(environ, start_response)

if endpoint == 'get_cat_article':
# Note that werkzeug also provides objects for building responses: http://werkzeug.pocoo.org/docs/0.14/wrappers
start_response('200 OK', [('Content-Type', 'text/plain')])
return ['Finally, a cat-centric article about {0}'.format(args['article_id'])]
else:
start_response('404 Not Found', [('Content-Type', 'text/plain')])
return ['Nothing is here...']


application = RequestHeaderSanitiser(app)
application = ResponseHeaderSanitiser(application)
application = Blocker(application)
application = UserAgentDecorator(application, 'Hypothesis-Via')
application = wsgi.DispatcherMiddleware(application, {
'/cat_articles': cat_app,
'/favicon.ico': static.Cling('static/favicon.ico'),
'/robots.txt': static.Cling('static/robots.txt'),
'/static': static.Cling('static/'),
'/static/__pywb': static.Cling(resource_filename('pywb', 'static/')),
'/static/__shared/viewer/web/viewer.html': redirect_old_viewer,
'/h': redirect_strip_matched_path,
})

使用该代码,路径 /cat_articles/plants 应该返回:

最后是一篇以猫为中心的关于植物的文章

关于python - 如何使用 wsgi 在 URL 路径中包含变量? (不是查询字符串),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51777367/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com