如何处理Python瓶和Apache.htaccess中的URL重路由?

2024-05-11 05:12:54 发布

您现在位置:Python中文网/ 问答频道 /正文

我目前正在尝试使用Python瓶子创建一个简单的独立应用程序。在

我的整个项目都在pytest/下,其中我有dispatch.fcgi和{}。在

dispatch.fcgi

#!/usr/bin/python
# -*- coding: utf-8 -*-
import bottle
import os
from bottle import route, run, view

@route('<foo:path>')
@view('index')
def pytest(foo = ''):
    return dict(foo=foo)

APP_ROOT = os.path.abspath(os.path.dirname(__file__))
bottle.TEMPLATE_PATH.append(os.path.join(APP_ROOT, 'templates'))
app = bottle.default_app()

if __name__ == '__main__':
    from flup.server.fcgi import WSGIServer
    WSGIServer(app).run()

.htaccess

^{pr2}$

以下URL为我提供foo的相应值:

url.com/pytest/
> /pytest/

url.com/pytest/dispatch.fcgi
> /pytest/dispatch.fcgi

url.com/pytest/dispatch.fcgi/
> /

url.com/pytest/dispatch.fcgi/foo/bar
> /foo/bar

url.com/pytest/dispatch.fcgi/pytest/
> /pytest/

如何使网址统一?我应该用.htaccess文件还是在Python代码中处理重路由?什么是最具Python式的,或者说是最佳实践?在

我运行的是python2.6.6、bottle0.11.6、flup1.0.2和apache2.2.24。我还想指出,我使用的是共享主机,mod\wsgi是不可能的(如果这有区别的话)。在

编辑

我希望看到的是:

url.com/pytest/
> <redirect to url.com/pytest/dispatch.fcgi>

url.com/pytest/dispatch.fcgi
> <empty string>

url.com/pytest/dispatch.fcgi/
> /

url.com/pytest/dispatch.fcgi/foo/bar
> /foo/bar

url.com/pytest/dispatch.fcgi/pytest/
> /pytest/

如果有更有效的方法来解决这个问题,请告诉我。在


Tags: pathrunfromimportcomappurlbottle
2条回答

瓶子似乎有点混乱,因为它需要一个尾随的斜杠,后跟参数。为此,我将.htaccess文件改为如下所示:

DirectoryIndex dispatch.fcgi/

另一个选择是将所有错误都放回调度脚本中。这可以通过mod_rewrite完成:

^{pr2}$

FallbackResource

FallbackResource /pytest/dispatch.fcgi/

一些想法。希望这些都能有所帮助。在

1)可以执行从“/”到“/pytest”的重定向/调度.fcgi“就像这样:

@route('/')
def home():
    bottle.redirect('/pytest/dispatch.fcgi')

2)是否可以使用ScriptAlias而不是DirectoryIndex?我知道你在一个共享的环境中,所以我不确定。我的bottle/apache服务器使用ScriptAlias(或WSGIScriptAlias),它在那里工作得非常好;它将使您的代码与apache交互的方式更加清晰。在

3)如果更糟的情况发展到最糟的地步,你能不能用黑客的方式检测foo=='/pytest的情况/调度.fcgi“并据此采取行动?(例如,将其视为空字符串。)

希望这有帮助。请随时通知我们!在

相关问题 更多 >