flask api post request with an image with an orm in python

Here's an example of how to implement a Flask API with a POST request that accepts an image and saves it to a database using an ORM, SQLAlchemy:

main.py
from flask import Flask, request, jsonify
from flask_sqlalchemy import SQLAlchemy

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'DATABASE_URI'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
db = SQLAlchemy(app)

class Image(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(100))
    data = db.Column(db.LargeBinary)

@app.route('/upload_image', methods=['POST'])
def upload_image():
    name = request.form['name']
    file = request.files['file']

    img = Image(name=name, data=file.read())
    db.session.add(img)
    db.session.commit()

    return jsonify({'message': 'Image uploaded successfully'}), 200

if __name__ == '__main__':
    app.run()
718 chars
27 lines

In this example, we first import the necessary modules and create a Flask app. We then configure the app to connect to a database using SQLAlchemy.

We define an Image class which inherits from db.Model and represents a table in the database. This class has an id, a name, and a data column. The data column is used to store the image binary data.

In the upload_image() function, we retrieve the name and file from the form data sent in the POST request. We then create an instance of the Image class and store the image data in the data column. We add this instance to the session and commit the changes to the database.

Finally, we return a success message to the client in the form of a JSON object.

gistlibby LogSnag