我开始使用Flask,说实话,我已经达到了对抗学习桌面部分的优势。
我能够成功地使用flask创建一些路由,但是当我尝试动态生成它时,我不断遇到断言错误: “AssertionError:视图函数映射正在覆盖现有的端点函数:j_show_html”
为了解决这个问题,我尝试动态创建python函数(这似乎是一个坏主意)。什么是动态创建这些基于日期的页面的更好方法?
这是我的python脚本:
from flask import render_template, Flask
import pandas
from pandas.tseries.holiday import USFederalHolidayCalendar
from datetime import timedelta, datetime
app = Flask(__name__)
out_IP_address = "0.0.0.0"
out_port = 5000
fileLoc = "C:/"
fileName = "Rand_QA_Calls"
start_date = "2017-01-01"
out_date = []
cal = USFederalHolidayCalendar()
holidays = cal.holidays(start='2017-01-01', end='2017-12-31').to_pydatetime()
for i in range(0,365):
temp_date = datetime.strptime(start_date,"%Y-%m-%d") + timedelta(days=i)
code = """
def {0}():
report = pandas.read_excel('{1}'+"/"+'{2}'+"_"+'{3}'+"_"+'{3}'+".xlsx")
return render_template('view.html',
tables=[report.to_html(index=False)])""".format("j_show_html_"+str(i),fileLoc,fileName,temp_date.strftime("%Y%m%d"))
print(code)
@app.route("/"+temp_date.strftime("%Y%m%d"))
exec(eval(code))
if __name__ == "__main__":
app.run(host=out_IP_address,port=out_port,debug=True)
这是我的HTML(利用jinja2):
<!doctype html>
<title>Simple tables</title>
<link rel=stylesheet type=text/css href="{{ url_for('static', filename='style.css') }}">
<div class=page>
<h1>Rand_QA_Calls</h1>
{% for table in tables %}
<h2>{{titles[loop.index]}}</h2>
{{ table|safe }}
{% endfor %}
</div>
最后这里是CSS:
body { font-family: "Lucida Sans Unicode", "Lucida Grande", sans-serif;}
a, h1, h2 { color: #377ba8; }
h1, h2 { margin: 0; }
h1 { border-bottom: 2px solid #eee; }
h2 { font-size: 1.2em; }
table.dataframe, .dataframe th, .dataframe td {
border: none;
border-bottom: 1px solid #C8C8C8;
border-collapse: collapse;
text-align:left;
padding: 10px;
margin-bottom: 40px;
font-size: 0.9em;
}
tr:nth-child(odd) { background-color:#eee; }
tr:nth-child(even) { background-color:#fff; }
tr:hover { background-color: #ffff99;}
答案 0 :(得分:0)
我明白了。我没有通过路线传递变量,但这使得它更容易。
from flask import render_template, Flask
import pandas
from pandas.tseries.holiday import USFederalHolidayCalendar
#from datetime import datetime, timedelta
import urllib2
app = Flask(__name__)
out_IP_address = "0.0.0.0"
out_port = 5000
fileLoc = "C:/"
fileName = "Rand_QA_Calls"
start_date = "2017-01-01"
out_date = []
cal = USFederalHolidayCalendar()
holidays = cal.holidays(start='2017-01-01', end='2017-12-31').to_pydatetime()
@app.route("/tables/")
@app.route("/tables/<date>")
def j_show_html(date):
report = pandas.read_excel(fileLoc+"/"+fileName+"_"+date+"_"+date+".xlsx")
return render_template('view.html',
tables=[report.to_html(index=False)],
titles = ['na'],
labels = urllib2.unquote(date.encode('ascii','ignore')))
if __name__ == "__main__":
app.run(host=out_IP_address,port=out_port,debug=True)