Skip to main content
 首页 » 编程设计

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

2024年12月31日10小虾米

我想使用下面的代码在 SQLite 数据库中保存 age_s、age_e、gender 和 filename,但是我有个问题。

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

我知道问题出在 html 文件上,但我无法同时将文件保存在目录中并将文件名保存在数据库中。

应用.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 %} 

表单.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() 

请您参考如下方法:

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