通过Cron作业url_的flash网页呼叫中断

2024-04-18 22:18:40 发布

您现在位置:Python中文网/ 问答频道 /正文

我的Flask应用程序中有一个脚本,每5分钟执行一次。原因很多。但那没关系。在

当我运行这段代码,我现在想在这个网页中包括链接到我的函数应用程序副本烧瓶应用。在

应用程序副本

@app.route('/Historical-Service-Transitions/<service>')
@login_required
@nocache
def HSPC(service):
    return service

启动.py按计划运行。在

^{pr2}$

错误

Traceback (most recent call last):
  File "kickoff.py", line 1199, in <module>
    the_time=the_time
  File "/usr/lib/python2.6/site-packages/Jinja2-2.7.3-py2.6.egg/jinja2/environment.py", line 969, in render
    return self.environment.handle_exception(exc_info, True)
  File "/usr/lib/python2.6/site-packages/Jinja2-2.7.3-py2.6.egg/jinja2/environment.py", line 742, in handle_exception
    reraise(exc_type, exc_value, tb)
  File "<template>", line 534, in top-level template code
jinja2.exceptions.UndefinedError: 'url_for' is undefined

如有任何帮助,我们将不胜感激。


更新:

我找不到任何与我所要做的事情很接近的东西。我知道我可以重新构建它,这样后台Python代码获取信息,我的app.py构建HTML。后台应用程序将填充数据库,app.py中的函数将从数据库中获取所需的信息并发布到HTML页面。在

虽然这是最后的手段,因为它需要我重新设计整个应用程序的这一部分,但我仍然想看看是否有一个解决方案可以让我在app.py烧瓶之外生成这个网页。在


Tags: 函数代码inpyapp应用程序网页jinja2
1条回答
网友
1楼 · 发布于 2024-04-18 22:18:40

Jinja提供了你缺少的背景。使用^{}呈现字符串中定义的模板,将为您提供正确的模板上下文:

from flask import render_template_string

source_html = u'''
<tbody>
{% for x in the_best %}
    <tr>
        <td><a href="{{ url_for('HSPC', service ='x.service') }}">{{x.service}}</a></td>
        <td>{{x.ip}}</td>
        <td>{{x.router}}</td>
        <td>{{x.detail}}</td>
        <td>{{x.time}}</td>
    </tr>
{% endfor %}
</tbody>
'''

filename = "/var/www/flask-intro/templates/Test.html"

# provide a fake request context for the template
with app.test_request_context('/'), open(filename, "w") as outfh:
    full_html = render_template_string(
        source_html, the_best=the_best, the_time=the_time)
    outfh.write(full_html)

但是,对于周期性的作业,您可以使用curl在Flask应用程序中调用一个特殊的URL,让它将模板输出写到一个文件中。在

相关问题 更多 >