Created
February 4, 2020 11:02
-
-
Save ItsCosmas/81aaf47d467175b73956269c857b5031 to your computer and use it in GitHub Desktop.
Send an Image file to client on Python Flask REST
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from flask.views import MethodView | |
from flask import jsonify, request, abort | |
import uuid | |
import os | |
from werkzeug.utils import secure_filename | |
class MediaAPI(MethodView): | |
def __init__(self): | |
if request.method != 'GET' and not request.files: | |
abort(400) | |
def get(self, media_id): | |
if media_id: | |
# return image with specified id | |
# checks if media_id is a record on db and if so return the media | |
image = ImageModel.objects.filter(image_id=media_id).first() | |
if image: | |
# append media_id to file path so as to perfom send_file() | |
file_path = os.path.join(os.getcwd(), 'static', 'upload', 'image', '', media_id) | |
if os.path.isfile(file_path): | |
return send_file(file_path), 200 | |
else: | |
error = "Media not found" | |
return jsonify({"error":error}),404 | |
else: | |
error = "Media not found" | |
return jsonify({"error":error}),404 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment