我目前正在尝试使用 Python Bottle 创建一个简单的独立应用程序。
我的整个项目位于pytest/
下,其中有dispatch.fcgi
和.htaccess
。
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
:
DirectoryIndex dispatch.fcgi
以下 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/
如何使 URL 统一?我应该使用 .htaccess
文件还是在 Python 代码中处理重新路由?什么被认为是最 Pythonic 或最佳实践?
我正在运行 Python 2.6.6、Bottle 0.11.6、Flup 1.0.2 和 Apache 2.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/
如果有更有效的方法来解决这个问题,请告诉我。
最佳答案
一些想法。希望其中部分或全部会有所帮助。
1)您可以像这样从“/”重定向到“/pytest/dispatch.fcgi”:
@route('/')
def home():
bottle.redirect('/pytest/dispatch.fcgi')
2) 可以使用 ScriptAlias 代替 DirectoryIndex 吗?我发现您处于共享环境中,所以我不确定。我的 Bottle/apache 服务器使用 ScriptAlias(或 WSGIScriptAlias)并且它在那里完美工作;它会让你的代码与 apache 交互的方式更加清晰。
3)如果情况变得更糟,你能黑客般地检测到 foo == '/pytest/dispatch.fcgi' 的情况并采取相应的行动吗? (例如,将其视为空字符串。)
希望这有帮助。请随时通知我们!
关于python - 如何处理 Python Bottle 和 Apache .htaccess 中的 URL 重新路由?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16846517/