【问题标题】:Writing Tornado templates to work with nginx proxied location编写 Tornado 模板以使用 nginx 代理位置
【发布时间】:2018-04-11 23:33:23
【问题描述】:

我有一个 Tornado 应用程序,我想使用 nginx 在非 root 位置下托管它。所以我有一个看起来像

的 nginx 配置
server {
    listen 80;
    server_name mysite.com;

    location /myapp/ {
        proxy_pass http://localhost:8888/;
    }
}

我希望应用程序位于mysite.com/myapp/。使用当前配置,所有处理程序都被路由到正确的 url,但是模板中使用的所有链接都是错误的。例如

<a href='/'>Home</a>

链接到mysite.com/ 而不是mysite.com/myapp/。我还希望该应用程序仍能在本地运行,因此我不希望将 /myapp/ 硬编码到模板中。

有没有办法用 nginx 或 Tornado 来处理这个问题?

到目前为止,我的解决方案是在模板命名空间中添加一个便利函数

import tornado.ioloop
import tornado.web
import os

APPLICATION_ROOT = os.environ.get('MYAPP_ROOT')

class BaseHandler(tornado.web.RequestHandler):
    def full_url(self, path, *args, **kwargs):
        if path.startswith('/'):
            path = path.lstrip('/')
            return os.path.join(APPLICATION_ROOT, path)
        else:
            return path

    def get_template_namespace(self):
        """Returns a dictionary to be used as the default template namespace.

        May be overridden by subclasses to add or modify values.

        The results of this method will be combined with additional
        defaults in the `tornado.template` module and keyword arguments
        to `render` or `render_string`.
        """
        namespace = dict(
            handler=self,
            request=self.request,
            current_user=self.current_user,
            locale=self.locale,
            _=self.locale.translate,
            pgettext=self.locale.pgettext,
            static_url=self.static_url,
            xsrf_form_html=self.xsrf_form_html,
            reverse_url=self.reverse_url,
            full_url=self.full_url
        )
        namespace.update(self.ui)
        return namespace

并将MYAPP_ROOT='/myapp/'设置为环境变量并使用

<a href="{{ full_url('/') }}">Home</a>

在模板中。

【问题讨论】:

    标签: python nginx tornado


    【解决方案1】:

    Tornado 对可以像这样重定位到不同路径的应用程序没有很好的支持 - 通常假设路径前缀是已知的并且可以硬编码。 (nginx proxy_pass 指令中的尾部斜杠很重要 - 删除它,nginx 将请求按原样传递给 Tornado)

    如果您仍然想根据您是否通过 nginx 使用不同的路径,我会推荐一个 URL 辅助函数,就像您在这里一样。其他选项包括始终在 URL 中使用相对路径而不是绝对路径(可能需要在主页上使用 /myapp/home/home 而不是 /myapp//),或者让 nginx 重写链接,如 @ 987654321@

    【讨论】:

    • nginx 重写最终成为最简单的修复。谢谢!
    猜你喜欢
    • 2020-12-18
    • 2015-12-28
    • 2015-03-10
    • 2014-03-12
    • 1970-01-01
    • 1970-01-01
    • 2019-01-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多