简体   繁体   English

如何使用 sqlalchemy(python 烧瓶)上传图像

[英]How to upload image using sqlalchemy (python flask)

I'm a new programmer, i'm using python flask and sqlalchemy database.我是一名新程序员,我正在使用 python flask 和 sqlalchemy 数据库。 i want to upload image and add the filename to my database this is my code:我想上传图片并将文件名添加到我的数据库中,这是我的代码:

in this python file i create Post db model models.py在这个 python 文件中,我创建 Post db model models.py

class Post(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    title = db.Column(db.String(100), nullable=False)
    date_posted = db.Column(db.DateTime, nullable=False, default=datetime.utcnow)
    content = db.Column(db.Text, nullable=False)
    user_id = db.Column(db.Integer, db.ForeignKey('user.id'), nullable=False)
    image_file = db.Column(db.Text, unique=True, nullable=False)

Here create form using class forms.py这里使用 class forms.py 创建表单

class PostForm(FlaskForm):
    title = StringField('Title', validators=[DataRequired()])
    content = TextAreaField('Content', validators=[DataRequired()])
    picture = FileField('Update Picture', validators=[FileAllowed(['jpg', 'png'])])
    submit = SubmitField('Post')

Here my route: route.py这是我的路线:route.py

@app.route("/post/new", methods=['GET', 'POST'])
@login_required
def new_post():
    form = PostForm()
    if form.validate_on_submit(): 
        if form.picture.data:
            picture_file = save_picture_post(form.picture.data) 

        post = Post(title=form.title.data, content=form.content.data , image_file = picture_file ,author=current_user)    
        db.session.add(post)
        db.session.commit()
        flash('Your post has been created!', 'success')
        return redirect(url_for('home'))
    return render_template('create_post.html', title='New Post',
                           form=form, legend='New Post')

And my html to create post is as following: create_post.html我的 html 创建帖子如下: create_post.html

{% extends "layout.html" %}
{% block content %}
<div class="container">
    <div class="col-md-8"></div>
        <div class="content-section">
            <form method="POST" action="">
                {{ form.hidden_tag() }}
                <fieldset class="form-group">
                    <legend class="border-bottom mb-4">new post</legend>
                    <div class="form-group">
                        <label for="title">title</label>
                        {% if form.title.errors %}
                            {{ form.title(class="form-control form-control-lg is-invalid") }}
                            <div class="invalid-feedback">
                                {% for error in form.title.errors %}
                                    <span>{{ error }}</span>
                                {% endfor %}
                            </div>
                        {% else %}
                            {{ form.title(class="form-control form-control-lg") }}
                        {% endif %}
                    </div>
                    <div class="form-group">
                        <label for="content">post</label>
                        {% if form.content.errors %}
                            {{ form.content(class="form-control form-control-lg is-invalid") }}
                            <div class="invalid-feedback">
                                {% for error in form.content.errors %}
                                    <span>{{ error }}</span>
                                {% endfor %}
                            </div>
                        {% else %}
                            {{ form.content(class="form-control form-control-lg") }}
                        {% endif %}
                    </div>
                    <div class="form-group" style="float: right;">
                        <label for="picture">add photo </label>
                        {{ form.picture(class="form-control-file") }}
                        {% if form.picture.errors %}
                            {% for error in form.picture.errors %}
                                <span class="text-danger">{{ error }}</span></br>
                            {% endfor %}
                        {% endif %}
                    </div>
                </fieldset>
                <div class="form-group">
                    {{ form.submit(class="btn btn-warning") }}
                </div>
            </form>
        </div>
    </div>
</div>
{% endblock content %}


My problem is the following line of code not working:我的问题是以下代码行不起作用:

if form.picture.data:
            picture_file = save_picture_post(form.picture.data)

my error:我的错误:

return func(*args, **kwargs)
  File "E:\flask\HomeX\application\routes.py", line 154, in new_post
    post = Post(title=form.title.data, content=form.content.data , image_file = picture_file ,author=current_user)
UnboundLocalError: local variable 'picture_file' referenced before assignment

Edit: The save_picture_post is a method in route.py:编辑: save_picture_post 是 route.py 中的一个方法:

def save_picture_post(form_picture):
    random_hex = secrets.token_hex(8)
    _, f_ext = os.path.splitext(form_picture)
    picture_fn = random_hex + f_ext
    picture_path = os.path.join(app.root_path, 'static/job', picture_fn)

    output_size = (125, 125)
    i = Image.open(form_picture)
    i.thumbnail(output_size)
    i.save(picture_path)

    return picture_fn

Your saving logic should be within form.picture.data, viz.您的保存逻辑应该在 form.picture.data 中,即。

if form.validate_on_submit(): 
    if form.picture.data:
        picture_file = save_picture_post(form.picture.data) 

        post = Post(title=form.title.data, content=form.content.data , image_file = picture_file ,author=current_user)    
        db.session.add(post)
        db.session.commit()
        flash('Your post has been created!', 'success')
        return redirect(url_for('home'))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM