【问题标题】:Download link for database in Django [closed]Django中数据库的下载链接[关闭]
【发布时间】:2016-09-02 02:54:28
【问题描述】:

我想在我的 Django 应用程序中放置一个链接,以从 MySQL 服务器下载应用程序的数据作为 CSV 格式。有什么简单的方法吗?

更正:当我说数据库时,我是指相关表作为一个文件,这意味着我需要在下载之前加入它们。由于我是为客户端执行此操作,因此他们不需要查看所有表,包括日志和用户表。他们只能使用一个文件来进行基本报告,而不是使用整个关系数据库。因此,首先我需要对关系数据库进行非规范化并准备好下载。

【问题讨论】:

  • 我建议查看 django 导入/导出

标签: python mysql sql django


【解决方案1】:

这有点重复:django download csv file using a link

你可以这样做:

from io import StringIO

from django.core import management


def create_fixture(app_name, filename):
    buf = StringIO()
    management.call_command('dumpdata', app_name, stdout=buf)
    buf.seek(0)
    with open(filename, 'w') as f:
        f.write(buf.read())


class YourPage(...):
    ....

    def dispatch(self, *args, **kwargs):
        create_fixture('<yourapp>', '<yourapp>/static/reports/test.csv')
        return super(YourPage, self).dispatch(*args, **kwargs)

那么在你看来,(假设你正确配置了静态文件路径)

{% load staticfiles %}
<a href="{% static '<yourapp>/test.csv' %}">Download CSV</a>

显然实际上并没有在视图逻辑中执行数据转储,因为这会减慢速度,您可能需要考虑在代码库的其他地方异步执行它。

【讨论】:

  • 谢谢杰克,但我找到了一个更简单的解决方案。坦率地说,我无法在我的应用中实现你的。
【解决方案2】:

我通过创建一个外部函数来加入和下载表格来解决这个问题,然后我在我的静态文件中提供一个指向下载文件的链接。

这是我的辅助函数,

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>

我仍然不能完全确定这是最好的解决方案。但这是我现在能做的,而且效果很好。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-09-12
    • 1970-01-01
    • 1970-01-01
    • 2016-09-11
    • 2018-06-08
    • 2015-04-26
    • 2016-02-20
    • 2012-08-05
    相关资源
    最近更新 更多