gpt4 book ai didi

python - Flask 网页通过 Cron Job - url_for 调用中断

转载 作者:太空宇宙 更新时间:2023-11-04 01:13:03 25 4
gpt4 key购买 nike

我的 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 页面。

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

最佳答案

您缺少 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 应用中的特殊 URL,让它将模板输出写入文件。

关于python - Flask 网页通过 Cron Job - url_for 调用中断,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26492786/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com