1

I'm writing a small web-shop using Python and web-framework Flask.

I'm trying to add image file in SQLite database using this

@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!"

Where readImage is

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

Form where I taked the image:

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

And the class of database where I want to add image looks like that:

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

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

So, the problem is, when I added image by pressing "Add Image" button in form and pressed "Submit" button I get the BadRequestKeyError 400. The debugger said that the problem is in img_name = request.form['product_img']. So how can I fix that and what I'm doing wrong?

1 Answer 1

1
+100

At first I want to say that storing large and medium pictures directly in SQLite is not a very good solution. Learn more here: https://www.sqlite.org/intern-v-extern-blob.html

For your problem, try to do as in the documentation: https://flask.palletsprojects.com/en/1.1.x/patterns/fileuploads/

Note there is used:

        # 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)

And perhaps this article will also help you: Python SQLite BLOB to Insert and Retrieve file and images

Sign up to request clarification or add additional context in comments.

5 Comments

I tried to do how you said and i get "TypeError: expected str, bytes or os.PathLike object, not FileStorage" in line "with open(img_name, 'rb') as file:"
After file = request.files['file'], in file you have object type FileStorage. Read about FileStorage here: werkzeug.palletsprojects.com/en/1.0.x/datastructures/… It says how to get a file object from it.
So what should I do with FileStorage to make it binary and write to db?
Didn't helped, with file.stream.read() get same error - "TypeError: expected str, bytes or os.PathLike object, not FileStorage"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.