2014-10-21 20 views
1

매 5 분마다 실행되는 Flask App에있는 스크립트가 있습니다. 많은 이유들로 인해. 하지만 그건 중요하지 않습니다.플라스크 웹 페이지 비아 크론 작업 - url_for 호출이 깨졌습니다.

이 코드를 실행할 때이 웹 페이지의 링크를 내 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 

.


업데이트 :

나는 내가 할 시도하고있는 무슨 심지어 원격으로 가까이 아무것도 찾을 수 없습니다입니다. 배경 파이썬 코드가 정보를 가져오고 내 app.py이 HTML을 빌드하도록 이렇게 다시 빌드 할 수 있음을 이해합니다. 백그라운드 응용 프로그램은 데이터베이스를 채우고 app.py 내의 함수는 데이터베이스에서 필요한 정보를 가져 와서 HTML 페이지에 게시합니다.

이것은 응용 프로그램의 전체 부분을 재 설계해야하므로 매우 최후의 수단이지만, app.py 플라스크 밖에서이 웹 페이지를 생성 할 수있는 솔루션이 있는지 알고 싶습니다.

답변

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) 

그러나,주기적인 작업, 당신은 당신의 플라스크에 특별한 URL을 호출하는 curl을 사용할 수 있습니다 app을 사용하여 템플릿 출력을 파일에 씁니다.