当按钮单击时,使用flask-python将Mysql数据保存为CSV / Excel

时间:2014-11-07 07:40:11

标签: python mysql csv flask export

我是出口数据的新手,我在网上进行研究,但我很难理解,有人可以帮助我了解它的基本知识。

这是我的主要问题:我想从我在客户端选择的日期范围内从mysql下载一个特定数据,然后当我点击下载按钮时,我希望将来自mysql的这些数据一起保存在我的计算机中用户可以选择将其保存为CSV / Excel,我使用python作为我的webservice。谢谢

这是我在网络服务中正确知道的代码:

@api.route('/export_file/', methods=['GET', 'POST'])
def export_file():

    if request.method == 'POST':
        selectAttendance = """SELECT * FROM attendance"""
        db.session.execute(selectAttendance)
        db.session.commit()


        f = csv.writer(open("file.csv", "w"))
        for row in selectAttendance:
            f.writerow([str(row)])





    return jsonify({'success': True})

2 个答案:

答案 0 :(得分:2)

一般来说:

  1. 设置 mime标题" Content-Type"与您的数据匹配的相应MIME-Type的http标头的一部分。 这告诉浏览器Web服务器将发送什么类型的数据。
  2. 在' body'
  3. 中发送实际数据

    用烧瓶:

    Forcing application/json MIME type in a view (Flask)

    http://flask.pocoo.org/docs/0.10/patterns/streaming/

答案 1 :(得分:0)

def get(self):
    try:
        os.stat(BACKUP_PATH)
    except:
        os.mkdir(BACKUP_PATH)
    now = datetime.now() # current date and time
    year = now.strftime("%Y")
    month = now.strftime("%m")
    day = now.strftime("%d")
    time = now.strftime("%H:%M:%S")
    date_time = now.strftime("%d_%m_%Y_%H:%M:%S")
    TODAYBACKUPPATH = BACKUP_PATH + '/' + date_time

    try:
        os.stat(TODAYBACKUPPATH)
    except:
        os.mkdir(TODAYBACKUPPATH)
    print ("checking for databases names file.")

    if os.path.exists(DB_NAME):
        file1 = open(DB_NAME)
        multi = 1
        print ("Databases file found...")
        print ("Starting backup of all dbs listed in file " + DB_NAME)
    else:
        print ("Databases file not found...")
        print ("Starting backup of database " + DB_NAME)
        multi = 0

    if multi:
        in_file = open(DB_NAME,"r")
        flength = len(in_file.readlines())
        in_file.close()
        p = 1
        dbfile = open(DB_NAME,"r")

        while p <= flength:
            db = dbfile.readline()   # reading database name from file
            db = db[:-1]         # deletes extra line
            dumpcmd = "mysqldump -h " + DB_HOST + " -u " + DB_USER + " -p" + DB_USER_PASSWORD + " " + db + " > " + pipes.quote(TODAYBACKUPPATH) + "/" + db + ".sql"
            os.system(dumpcmd)
            gzipcmd = "gzip " + pipes.quote(TODAYBACKUPPATH) + "/" + db + ".sql"
            os.system(gzipcmd)
            p = p + 1
        dbfile.close()
    else:
        db = DB_NAME
        dumpcmd = "mysqldump -h " + DB_HOST + " -u " + DB_USER + " -p" + DB_USER_PASSWORD + " " + db + " > " + pipes.quote(TODAYBACKUPPATH) + "/" + db + ".sql"
        os.system(dumpcmd)
        gzipcmd = "gzip " + pipes.quote(TODAYBACKUPPATH) + "/" + db + ".sql"
        os.system(gzipcmd)
        # t = ("Your backups have been created in '" + TODAYBACKUPPATH + "' directory")
        return "Your Folder have been created in '" + TODAYBACKUPPATH + "'."