Open bekab95 opened 6 years ago
from flask import Flask
from flask_mongoengine import MongoEngine
from flask_admin import Admin
from flask_admin.contrib.mongoengine import ModelView
from flask import send_file
app = Flask(__name__)
app.config['MONGODB_SETTINGS'] = {
'db': 'your_database_name',
'host': 'your_mongodb_uri',
'port': 27017 # Change as per your MongoDB configuration
}
db = MongoEngine(app)
admin = Admin(app)
# Define your MongoDB models
class Product(db.Document):
name = db.StringField(max_length=100)
images = db.ListField(db.FileField())
# Register Flask-Admin views
class ProductAdmin(ModelView):
pass
admin.add_view(ProductAdmin(Product))
# Serve images route
@app.route('/admin/product/api/file/')
def serve_image():
coll = request.args.get('coll')
id = request.args.get('id')
if coll == 'images' and id:
product = Product.objects(id=id).first()
if product:
# Assuming the image is stored as a FileField in MongoDB
image_data = product.image.read() # Read the image data
return send_file(image_data, mimetype='image/jpeg') # Adjust mimetype as per your image format
return 'Image not found or invalid request', 404
if __name__ == '__main__':
app.run(debug=True)
for example if I have images list and each list item has imageField if I will try to open image in browser new window
/admin/product/api/file/?coll=images&id=59b48422ab2cfb4f873360ca
it opens in binary mode and does not display image
Using mongodb.