在Flask应用程序中实现下载

时间:2016-01-02 15:44:42

标签: python flask download flask-wtforms

我是Python / Flask编程的初学者,我在Flask应用程序中实现“下载功能”时遇到了一些问题。

我已经用Flask-Table创建了一个表格,我从数据库中提取了我的材料。直到现在,一切都好。 这里有我的代码:

def get_table(number):

items = Material.query.filter_by(university_id = number)

class ItemTable(Table):
    author = Col('Author')
    title = Col('Title')
    subject = Col('Subject')
    description = Col('Description')
    university_id = Col('Faculty')
    professor = Col('Professor')
    rating = Col('Rating')
    download = ButtonCol('Download','download')

class Item(object):
    def __init__(self, author,title,subject,description,university_id,professor,rating,download):
        self.author = author
        self.title = title
        self.subject = subject
        self.description = description
        self.university_id = university_id
        self.professor = professor
        self.rating = rating
        self.download = items.link

table = ItemTable(items)
return table

这是我的课材料:

class Material(Base):
__tablename__ = 'material'
id = Column(Integer, primary_key=True)
title = Column(String(100), nullable=False)
link = Column(String(200), nullable=False)
author = Column(String(20), ForeignKey('user.username'), nullable=False)
university_id = Column(Integer, ForeignKey('university.id'), nullable=False)
professor = Column(String(30), nullable=False)
subject = Column(String(30), nullable=False)
description = Column(Text, nullable=False)
rating = Column(Enum('1', '2', '3', '4', '5'))

def __init__(self, id, title, link, author, university_id, professor, subject, description, rating):
    self.id = id
    self.title = title
    self.link = link
    self.author = author
    self.university_id = university_id
    self.professor = professor
    self.subject = subject
    self.description = description
    self.rating = rating

然后我尝试将ButtonCol放在我的“ItemTable类”中,因为我想为所有材料提供一个按钮,并让用户可以下载它们。 但老实说,我不知道继续下去。 我已经实现了上传功能,我已经保存了上传到数据库中的资料的URL,但我真的不知道如何从数据库中获取此链接并下载用户点击的文件。 我也想过表格中的一个表格,所以我可以发送一个“提交”文件的链接并创建一个下载功能,但是使用Flask-Table我不能在表格中放一个表格。

这里有我上传功能的代码:

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

form1 = MaterialForm(csrf_enabled=False)
form2 = UploadForm(csrf_enabled=False)

file = request.files['doc']
if form2.validate_on_submit():

    title = request.form['title']
    author = request.form['author']
    university = request.form['university']
    professor = request.form['professor']
    subject = request.form['subject']
    description= request.form['description']

    uniid = applicativo.get_id_by_uni(university)
    last = Material.query.order_by(Material.id.desc()).first()
    num = (last.get_id() + 1)

    newrow = Material(
                id = num,
                title = title,
                link= file,
                author = author,
                university_id = uniid,
                professor= professor,
                subject = subject,
                description = description,
                rating = ''
                    )

    db.session.add(newrow)
    db.session.commit()

    filename = secure_filename(file.filename)
    file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
    return redirect(url_for('uploaded_file',
                            filename=filename))

我希望你能帮帮我:)。

1 个答案:

答案 0 :(得分:0)

基本上每当用户点击"下载"您应该将该文件作为数据库中的二进制数据。如果它不是二进制数据,您可以转换它,然后您必须使用与文件MIME类型相关的自定义标头进行响应,以便浏览器知道如何在响应上处理它,例如启动下载过程。 您可以将此示例看作是开头的一些参考:http://code.runnable.com/UiIdhKohv5JQAAB6/how-to-download-a-file-generated-on-the-fly-in-flask-for-python

为一个文件实现基本下载后,您可以使用自定义路由从数据库下载不同的文件。

您的路线可能类似于:

@app.route("/download/<filename>")
def download(filename):
    #get the file from the database depending on the filename
    #once you have the file convert it to binary data if it is not, but usually it should be.
    #configure the correct "Content-Type" headers
    #usually the headers "Content-Type: application/octet-stream"
    # and Content-Disposition: attachment; filename="myfile.txt" should be ok for the browser to start the downloader
    #make the response with the binary data and the headers included

这是关于如何流式文档的官方文档的帖子,基本上应该如上所述:http://flask.pocoo.org/docs/0.10/patterns/streaming/