【问题标题】:How do I deal with URL reroutes in Python Bottle and Apache .htaccess?如何处理 Python Bottle 和 Apache .htaccess 中的 URL 重新路由?
【发布时间】:2013-05-26 15:20:45
【问题描述】:

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

以下网址给了我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 代码中处理重新路由?什么会被认为是最 Python 或最佳实践?

我正在运行 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/

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

【问题讨论】:

  • Phil,“使 URL 统一”是什么意思?您向我们展示了您当前代码的输出——很好——但也可以看到您/期望/看到的输出,以便更清楚您正在尝试做什么以及我们如何提供帮助。
  • @ron.rothman 已编辑以包含预期输出

标签: python apache .htaccess bottle fastcgi


【解决方案1】:

几个想法。希望其中的部分或全部会有所帮助。

1) 您可以像这样将“/”重定向到“/pytest/dispatch.fcgi”:

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

2) 你能用 ScriptAlias 代替 DirectoryIndex 吗?我看到您在共享环境中,所以我不确定。我的瓶子/apache 服务器使用 ScriptAlias(或 WSGIScriptAlias),它在那里工作得很好;它会让你的代码与 apache 交互的方式更加清晰。

3) 如果情况变得更糟,您能否巧妙地检测到 foo == '/pytest/dispatch.fcgi' 的情况并采取相应措施? (例如,将其视为空字符串。)

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

【讨论】:

  • 感谢您的帮助,虽然这不是我想出的解决方案。我发现如果我没有在 fcgi 文件后添加额外的斜杠,Bottle 就会很困惑。
【解决方案2】:

Bottle 似乎很困惑,因为它需要一个斜杠,后跟参数。出于这个原因,我将 .htaccess 文件更改为如下所示:

DirectoryIndex dispatch.fcgi/

另一种选择是让所有错误回退到调度脚本。这可以通过mod_rewrite 完成:

<IfModule mod_rewrite.c>
Options -MultiViews

# rewrite for current folder
RewriteEngine On
RewriteBase /pytest

# redirect to front controller
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ dispatch.fcgi/ [R=301,QSA,L]
</IfModule>

FallbackResource:

FallbackResource /pytest/dispatch.fcgi/

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-04-24
    • 2013-01-23
    • 1970-01-01
    • 2015-03-03
    • 1970-01-01
    • 1970-01-01
    • 2017-12-04
    • 2010-09-20
    相关资源
    最近更新 更多