python - 如何处理 Python Bottle 和 Apache .htaccess 中的 URL 重新路由?

标签 python apache .htaccess bottle fastcgi

我目前正在尝试使用 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/

相关文章:

python - 如何从一张图像制作蒙版,然后将其转移到另一张图像?

python - 剪辑二维列表直到内容形成一个矩形(Python)

python - 尽管已安装并配置了 python 路径,但 wsgi + apache 中出现 ModuleNotFoundError

java - 对 WordExtractor 的引用不明确

perl - 在 mod_perl 中基于 body 生成 Etag

Python - 从文件加载 JSON 不起作用

python - Disco 的 "Could not parse worker event:"错误是什么意思?

.htaccess - htaccess 将带有查询字符串的旧 URL 重定向到新的 SEO URL

node.js - .htaccess:允许云访问(NODE.js)我的 MediaWiki

Apache 服务器上的 Angular 应用程序无需重写规则