我确信有一个答案,但我似乎无法找到它.另外,重要的是要注意我是Python的新手.
我最近克隆了这个使用python和wsgi https://github.com/hypothesis/via进行路由的repo .
我想要的是在url路径(没有查询字符串)中有一个param:
meow.com/cat_articles/:article_id # i.e. meow.com/cat_articles/677
Run Code Online (Sandbox Code Playgroud)
我怎样才能做到这一点?
作为参考,我的最终目标是将自己的路径添加到此文件:
如何向应用程序添加此类路由取决于该应用程序用于实现 WSGI 的一个或多个库。我看到app.py您链接到的文件正在使用werkzeug(以及static)。
以下是一些关于使用占位符进行路由的有用参考werkzeug:
我几乎没有使用过werkzeug,也不会声称这绝对是最好的方法,但一种选择是通过该文件底部的调用werkzeug添加另一个 WSGI 应用程序。wsgi.DispatcherMiddleware
下面是一些组合在一起的示例代码,可帮助您在app.py共享文件的上下文中开始使用。尝试删除此行之后的所有内容并将其替换为以下代码:
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,
})
Run Code Online (Sandbox Code Playgroud)
使用该代码,路径/cat_articles/plants应返回:
Finally, a cat-centric article about plants
| 归档时间: |
|
| 查看次数: |
466 次 |
| 最近记录: |