部署在 Apache 上时,使用带有相对路径的 webpy 的 web.template.render()

发布于 2024-09-19 01:58:05 字数 532 浏览 2 评论 0原文

使用 webpy,引用 web.template.render() 的模板目录的正确方法是什么,以便它可以在 webpy 开发 Web 服务器和 Apache 上运行?

以下代码可以在开发服务器上运行,但在我的 Apache 服务器上运行时则不行。

import web

urls = (
  '/', 'index',
  )

class index:
  def GET(self):
    render = web.template.render('templates/')
    return render.index(self)

我知道问题在于 web.template.render('templates/') 是问题所在,因为当 Apache 从 C:\Program Files\Apache 运行时,相对路径不再有效软件基础\Apache2.2。我的模板目录位于我的项目文件夹中。

我不想做的是使用绝对路径,因为我希望能够移动我的项目文件,而不必修改代码以保持其正常工作。

Using webpy, what's the proper way to reference the templates directory for web.template.render() so that it works on both the webpy development web server and on Apache?

The following code works using the development server but not when running on my Apache server.

import web

urls = (
  '/', 'index',
  )

class index:
  def GET(self):
    render = web.template.render('templates/')
    return render.index(self)

I know the problem is that web.template.render('templates/') is the problem, because the relative path is no longer valid when Apache runs from C:\Program Files\Apache Software Foundation\Apache2.2. My templates directory is within my project folder.

What I don't want to do is use an absolute path, because I'd like to be able to move my project files around without having to tinker with the code to keep it working.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

-残月青衣踏尘吟 2024-09-26 01:58:05

如果您使用 mod_wsgi,最简单的解决方案是设置 home= 选项 适当地,

或者,您可以获取模块的路径并将其与模板结合起来,即

os.path.join(os.path.dirname(__file__), 'templates/')

如果您经常需要它,请将其放入函数中。请注意,如果您将其放在单独的模块中,则该模块需要与模板目录位于同一文件夹中,否则您将再次得到错误的目录。

如果您想将其放入系统范围的包中,您可以轻松找到调用者目录:

def abspath(path): 
    frame = sys._getframe(1)
    base = os.path.dirname(frame.f_globals['__file__'])
    return os.path.join(base, path)

If you're using mod_wsgi, the easiest solution is to set the home= option appropriately,

Alternatively, you can get the module's path and combine that with the template, i.e.

os.path.join(os.path.dirname(__file__), 'templates/')

Put it in a function if you need it often. Be aware that if you put it in a separate module, this module needs to be in the same folder as the templates directory or you'll end up with the wrong directory again.

In case you want to put it in a system wide package, you can find out the callers directory easily:

def abspath(path): 
    frame = sys._getframe(1)
    base = os.path.dirname(frame.f_globals['__file__'])
    return os.path.join(base, path)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文