通过Cron作业访问Flask网页 - url_for调用失效

2 投票
1 回答
783 浏览
提问于 2025-04-28 20:34

我在我的Flask应用里有一个脚本,每5分钟就会执行一次。原因有很多,但这些不重要。

现在,当我运行这段代码时,我想在这个网页上添加一些链接,链接到我在app.py这个Flask应用里的功能。

app.py:

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

kickoff.py是一个定时运行的脚本。

from jinja2 import Template
import paramiko 
import socket
import time
import pprint
import sys
import mysql.connector
from mysql.connector import errorcode
from collections import namedtuple
import datetime
from app import HSPC
from flask import url_for


source_html =Template(u'''
....#The part that is failing
<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>
....''')

full_html = source_html.render(
the_best=the_best,
the_time=the_time
)


write_that_sheet = open("/var/www/flask-intro/templates/Test.html", "w+")
write_that_sheet.write(full_html)
write_that_sheet.close()

错误信息:

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之外生成这个网页。

暂无标签

1 个回答

3

你缺少了Flask提供的Jinja上下文。可以使用 flask.render_template_string() 来渲染一个在字符串中定义的模板,这样就会为你提供正确的模板上下文:

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应用中的一个特殊网址,这样就可以把模板的输出写入一个文件。

撰写回答