如何使用Flask、Python在SQLite数据库中添加图像文件

2024-04-19 09:50:01 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在使用Python和web框架编写一个小型web商店

我正在尝试使用以下命令在SQLite数据库中添加图像文件

@app.route('/new_product_reg', methods=['POST', 'GET'])
def new_product_reg():
    if request.method == 'POST':

        img_name = request.form['product_img']
        product_img = readImage(img_name)
        product_img_binary = lite.Binary(product_img)

        product_data = NewProduct(product_img=product_img_binary)

        try:
            db.session.add(product_data)
            db.session.commit()
            return redirect('/new_product_reg')
        except:
            return "ERROR!"

其中readImage

def readImage(img_name):
   try:
       fin = open(img_name, 'rb')
       img = fin.read()
       return img
   except:
       print("ERROR!!")

我拍摄图像的形式:

    <form enctype="multipart/form-data" method="post">
            <input type="file" name=product_img id="product_img"><br>
            <input type="submit" value="Submit">
    </from>

我想在其中添加图像的数据库类如下所示:

class NewProduct(db.Model):
    product_img = db.Column(db.BLOB())

    def __repr__(self):
        return '<NewProduct %r>' % self.id

所以,问题是,当我通过按表单中的“添加图像”按钮并按“提交”按钮添加图像时,我得到了BadRequestKeyError 400。调试器说问题出在img_name = request.form['product_img']。那么,我该如何解决这个问题以及我做错了什么


Tags: name图像formwebimgnewdbdata
1条回答
网友
1楼 · 发布于 2024-04-19 09:50:01

首先,我想说直接在SQLite中存储大中型图片不是一个很好的解决方案。在此处了解更多信息:https://www.sqlite.org/intern-v-extern-blob.html

对于您的问题,请尝试按照文档中的操作: https://flask.palletsprojects.com/en/1.1.x/patterns/fileuploads/

注:使用了:

        # check if the post request has the file part
        if 'file' not in request.files:
            flash('No file part')
            return redirect(request.url)
        file = request.files['file']
        # if user does not select file, browser also
        # submit an empty part without filename
        if file.filename == '':
            flash('No selected file')
            return redirect(request.url)

也许这篇文章也能帮助你: Python SQLite BLOB to Insert and Retrieve file and images

相关问题 更多 >