我通过创建一个外部函数来加入和下载表格来解决这个问题,然后我在我的静态文件中提供一个指向下载文件的链接。
这是我的辅助函数,
def database_downloader():
import pymysql # run pip install pymysql if this fails
import sys
import time
import csv
start = time.time()
connect = 0
attempt = 1
while connect==0: #if connection is not secured, will try again in 3 seconds.
try:
print "connecting, attempt "+str(attempt)
conn = pymysql.connect(host='url', port=3306, user='username', passwd='pass', db='db', autocommit=True) #setup our credentials
cur = conn.cursor()
connect = 1
except:
print "try again in 3 seconds"
time.sleep(3)
attempt+=1
continue
print "connected to server in " +str(time.time()-start)+ " seconds."
out_file = open("main_app/static/main_app/reports/output.csv", "wb")
writer = csv.writer(out_file)
sql = "SELECT * FROM main_app_basic_info b LEFT JOIN main_app_add_info a ON a.Student_ID = b.Student_ID;"
cur.execute(sql)
column_names = []
for i in cur.description:
column_names.append(i[0])
writer.writerow(column_names)
for i in cur.fetchall():
writer.writerow(i)
print "Downloading completed in " + str((time.time()-start)) + " seconds."
out_file.close() # you need to close to save before sending
然后我在每次页面加载时运行此函数以保持更新并准备好下载。像这样,
def index(request):
student_list = basic_info.objects.order_by('-id')[:5]
student_list_full = basic_info.objects.order_by('-id')
context = {'student_list': student_list, 'student_list_full': student_list_full}
database_downloader() # this downloads the database in every refresh to main_app/reports/output.csv
return render(request, 'main_app/index.html', context)
最后,我将它添加到我的模板中,
{% load static %}
<div><a href="{% static "main_app/reports/output.csv" %}" download>Click Here to Download to Database</a></div>
我仍然不能完全确定这是最好的解决方案。但这是我现在能做的,而且效果很好。