I
I
inalan2020-08-25 04:48:36
Flask
inalan, 2020-08-25 04:48:36

Flask store file to database?

How to store a file in the database so that each

Ticket
had your file attached to it? It is necessary to make sure that each Ticket has its own file attached. I am using Flask wtf Forms for user prompt.
here is my code
class Files(db.Model):
        id = db.Column(db.Integer,primary_key=True)
        description = db.Column(db.String(140),nullable=False)
        file = db.Column(db.LargeBinary)
        timestamp = db.Column(db.DateTime, default=datetime.utcnow)
        author = db.Column(db.Integer, nullable=True)
        ticket_id = db.Column(db.Integer, db.ForeignKey('tickets.id'),nullable=False)

class AddFile(FlaskForm):
       description = StringField('Description',validators=[DataRequired()])
       file = FileField('Files',validators=[FileRequired()])
       submit = SubmitField('Upload')

@app.route('/ticket/<ticket_id>',methods=['GET','POST'])
@login_required
def ticket(ticket_id):
        if fileform.validate_on_submit() and fileform.file.data:
            newFile = Files(description=fileform.description.data,file=fileform.file.data.read(),author = current_user.username)
            db.session.add(newFile)
            db.session.commit()
            flash('Your file has been uploaded.')
            return redirect(url_for('ticket', ticket_id=ticket_id))
        return render_template('ticket.html',ticket=ticket,fileform=fileform,filemodel=filemodel)

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question