Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
150 views
in Technique[技术] by (71.8m points)

python - How do i link to images not in Static folder in flask

In flask, how do I serve images that are not in the static folder?

I currently save the user uploaded photos on a directory that is outside the flask folder (On openshift, image currently saving in the data folder under app-root/data and the flask files are in app-root/repo/).

In my templates, how do i serve the image files ?

Using url_for, how do i reference these image files that are outside the flask folder?

- data/
 |
  -- uploads/
- repo/
 |
  -- app/
    |
     -- __init__.py

As you can see the data folder outside the flask app folder. How do i generate links to files stored in data/uploads (one level up) from the flask app directory is the question ?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You have the send_from_directory function that does what you want, what I would do is declare a constant called MEDIA_FOLDER with the path where the media files are located and then, the only thing you need to do is to call the function like this:

from config import MEDIA_FOLDER

@app.route('/uploads/<path:filename>')
def download_file(filename):
    return send_from_directory(MEDIA_FOLDER, filename, as_attachment=True)

Then, to invoke it, you just do this:

{{ url_for('download_file', filename='dogs.jpg') }}

You can have more info about this here.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...