Issue
I am struggling with the following problem: what is the correct way to serve media files in Flask? I have build a model Posts
in a blog system, I'm using flask-file-upload
# models/blog.py
from app import db, file_upload
@file_upload.Model
class Posts(db.Model):
"""
Defines the attributes of posts table in the database
"""
...
image = file_upload.Column()
...
in my settings.py
file i have
import os
from pathlib import Path
PROJECT_ROOT = Path(__file__).parent.parent
UPLOAD_FOLDER = os.path.join(PROJECT_ROOT, 'media')
so, when I add a Post object it saves the file name in the database and the file in media folder with path media/posts/<post_id>/filename
So far it works perfectly. But I need serve these images, so I created the following route:
# routes.py
from app import app
@app.get('/media/<path:path>')
def send_media(path):
"""
:param path: a path like "posts/<int:post_id>/<filename>"
:return:
"""
path_list = path.split('/')
path_ = '/'.join(path_list[:-1]) + '/'
file_name = path_list[-1]
return send_from_directory(
directory=app.config['UPLOAD_FOLDER'], path=path_, filename=file_name, as_attachment=True
)
but it is not working, when I browse http://127.0.0.1:5000/media/posts/15/python.jpg
my Flask app responds with 404 - Not Found, even the python.jpg file being there.
How can I correctly access the media files in Flask?
I need this because I have to create an API that sends the file_name
and the frontend will render the image, something like
<img src="http://localhost:8000/media/posts/<post_id>/file_name">
Solution
Solution: seeing the send_from_directory() docstring I got it! We don't need path_list
, path_
and file_name
variables. The correct way to serve media files with Flask is:
@app.get('/media/<path:path>')
def send_media(path):
"""
:param path: a path like "posts/<int:post_id>/<filename>"
"""
return send_from_directory(
directory=app.config['UPLOAD_FOLDER'], path=path
)
Answered By - Jailton Silva
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.