简体   繁体   中英

Django - How to serve user uploaded content in production

I have written a small ecommerce app in Django. The admin user will be uploading photos of the products. I got this working on my dev machine by specifying the following handler in urls.py

if settings.DEBUG:
urlpatterns += patterns('django.views.static',
    (r'media/(?P<path>.*)', 'serve', {'document_root': settings.MEDIA_ROOT}),
)

In my Product model I have the following method returning the image url:

def detail_thumbnail_url(self) : return  self.detail_thumbnail.url

And from my template:

<img src="{{ product.detail_thumbnail_url }}">

There are warnings everywhere on not making Django handle this in production, but nowhere can I find how to handle this in production. Surely someone must have done this!

I want to serve the images from the same server that's running the web app.

As you may have read, that approach is not recommended. You must use a webserver along with your django app and connect them via WSGI . You've got basically three options….


Configure and use your webserver

This means you need to install a webserver (Nginx recommended) and configure it along with WSGI interfaces like Gunicorn or uWSGI . This option gives you maximum freedom and will help you understand how things work under the hood.

If you want to develop locally with all this config and skip the burden of installation and configuration you can use pre-baked Vagrant VMs for development.


Use a PaaS solution

Deploying your app to Heroku , ElasticBeanstalk , GAE, etc or your own PaaS (heroku-style git deployments) with docker/dokku . This solution will handle most of the the configurations for you. It will save you time (and money).


Serving from a CDN

It would be much better if you serve the statics from a CDN, no matter if you deploy to PaaS or your machines. For instance you could programatically upload the user pics and media directly to AWS S3 with the help of django apps like django-s3direct or make your own with boto… (no need to reinvent the wheel tho).

This option will ease the load of your server and speed up your website.

You do it by configuring your actual server - Apache, or whatever - to serve files from wherever MEDIA_ROOT is, on whatever MEDIA_URL is. Django should have nothing to do with it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM