Flask and sqlalchemy: Download the file using the path stored in the database

I use jar and sqlalchemy and I am having problems downloading files.

I upload a file with a form and save the URL in the DB, so I can display it inside on the page.

Here's the form code:

boxart = request.files['boxart'] if boxart: filename = secure_filename(boxart.filename) boxart_path = os.path.join(app.config['UPLOAD_FOLDER']+"boxart/", filename) boxart.save(boxart_path) game_son.boxart = boxart_path db.session.add(game_son) db.session.commit() 

So, I go to my template, and I can print the contents of game_son.boxart, and there is a full path to the file. If I click on the link, I can access, but the image will not be displayed inside the tag ...

I tried to get it on a template using:

  <img src="{{ game_son.boxart_url() }}" /> 

Inside the model, I defined the boxart_url method if I need to parse a string before sending it

  class Game_son(db.Model): __searchable__ = ['version_name'] son_id = db.Column(db.Integer, primary_key=True) version_name = db.Column(db.String(128), index=True, unique=False) son_timestamp = db.Column(db.DateTime) dad = db.Column(db.Integer, db.ForeignKey('game_dad.id')) console = db.Column(db.Integer, db.ForeignKey('platform.id')) boxart = db.Column(db.String(256)) thumbnail = db.Column(db.String(256)) genre = db.Column(db.String(32)) subgenre = db.Column(db.String(32)) def boxart_url(self): return self.boxart def __repr__(self): return '<Game %r>: %r' % (self.version_name, self.dad) 

The page view simply sends the entire object (game) to the page.

URL that appears on the page:

/home/removed_my_pc_user/app/media/boxart/image.jpg

Edit: I just remembered that I was using a virtual environment in a project.

Is this related to chmod?

Thanks in advance!

+6
source share
1 answer

Well, strange, but I will answer my question.

The solution is simple, I decided to store only the file names inside the database.

Then I created a route to the view, which will return the file using the send_from_directory function from flask.ext.uploads

 @app.route('/boxart/<filename>') def uploaded_boxart(filename): return send_from_directory(app.config['UPLOAD_FOLDER'],filename) 

So, inside the template, we can use the url_for() function to load the file, sending as a parameter the name of the file stored in the database.

 <img src="{{ url_for('uploaded_boxart', filename = game_son.boxart)}}" /> 

Also, I think one of my mistakes was setting the media / folder inside the app / folder, and not inside the root directory. Therefore, I also reconfigured UPLOAD_FOLDER in app.config.

+1
source

Source: https://habr.com/ru/post/987200/


All Articles