Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django: Serving static, media fles directly from Heroku

I recently deployed my first Django app to Heroku. It's for my master's project so scalability isn't a huge issue. I've read about problems that can occur from serving static and media files directly from Heroku and that Amazon S3 is the best solution. Thus far, the static files – CSS, JS – are being served properly from Heroku.

The media files are a bit of an issue, though.

The only media that can be uploaded by a user are photos. Again, as this is a small project, the volume will be low. Currently, those photos are being served properly. But when updates are pushed to Heroku, the links to the existing uploaded photos break on the page and have to be reuploaded to appear again, which is obviously unacceptable.

I'm trying to discern whether this is an issue with serving media that could be solved by an outside host such as Amazon S3 or something else that is occurring. I'm not eager to pay for hosting but if it will solve this issue, than it will likely be the solution chosen.

Any insight or experience welcomed.

like image 672
Why Not Avatar asked Dec 21 '22 19:12

Why Not


1 Answers

This is the expected behavior, because writes to the filesystem of a Heroku web dyno are not added to source control and will not be considered "part of your app". Basically, you should not allow any writes to the filesystem at all except for temporary files.

This isn't only a problem where pushing updates to your application cause the files to disappear; additionally, if you have multiple web dynos (the most typical use case in a Heroku app) your files will only appear for users that happen to hit the web dyno they were uploaded to.

The solution is to either have your users upload directly to another server or to S3 and pass the link to your application, or else to have your own server automatically send uploaded files to another destination such as S3 itself. In truth, static assets like CSS are better served from S3 as well, but this is sometimes practical and sometimes not.

like image 198
Andrew Gorcester Avatar answered Feb 03 '23 13:02

Andrew Gorcester