如何使用flask SQLAlchemy在数据库和目录中保存文件?

时间:2018-11-20 06:31:36

标签: python flask flask-sqlalchemy

我想使用以下代码在SQLite数据库中保存age_sage_egenderfilename,但是我有一个问题。

当我上传文件时,我的文件名存储在SQLite数据库中,但是文件本身未存储在我的系统目录中。如何在我的系统目录中保存文件?

我知道问题出在html文件,但是我不能同时将文件保存在目录中和将文件名保存在数据库中。

app.py

@app.route("/new_contact", methods=('GET', 'POST'))
def new_contact():
    '''
    Create new contact
    '''
    form = ContactForm()
    if form.validate_on_submit():
        my_contact = Contact()
        form.populate_obj(my_contact)
        db.session.add(my_contact)
        try:
            db.session.commit()
            # User info
            flash('Contact created correctly', 'success')
            return redirect(url_for('contacts'))
        except:
            db.session.rollback()
            flash('Error generating contact.', 'danger')

    return render_template('web/new_contact.html', form=form)

new_contact.html

{% extends 'layouts/master.html' %}
{% block title %}New contact{% endblock %}
{% block body %}
<h1>New contact</h1>
<form action="{{ url_for('new_contact') }}" method="post">
    {{ generate_fields(form) }}
    <input type="submit" class="btn btn-success" value="Add">
</form>

{% endblock %}

forms.py

from flask_wtf import FlaskForm
from wtforms import StringField,SelectField,IntegerField,FileField
from wtforms.ext.sqlalchemy.fields import QuerySelectField
from wtforms.validators import DataRequired, Email, Length
class ContactForm(FlaskForm):
    age_s = SelectField(u'age_s', choices=age_types)
    age_e = SelectField(u'age_e', choices=age_types1)
    #age_e = IntegerField('age_e', validators=[Length(min=-1, max=100, message='You cannot have more than 100 characters')])
    gender = SelectField('gender', choices=gender_types)
    #filename = StringField('filename', validators=[Length(min=-1, max=20, message='You cannot have more than 20 characters')]) 
    filename = FileField()

1 个答案:

答案 0 :(得分:1)

尝试根据烧瓶docs将其保存到您的首选路径