Walty Yeung
Walty Yeung

Reputation: 3564

django dynamic file serving optimization

I am working on a django project that provides an API to generate thumbnails of images, and the basic logic is like the following:

  1. when the source image URL comes for the first time, the django would do some sort of image manipulation, and return the thumbnail image

  2. when the same image URL comes again, django would simply serve the previous thumbnail image (stored as static media) again.

basically, case 2 happened much often than case 1. Now I used django to serve the images all the time, which I believe is a bad practice.

I wonder if it's possible to do a better way of image serving for case 2? For example, is there some sort of way to ask django to send proxy requests to apache and ask apache to serve the file?

I know I could use HTTP redirect to do that, but that seems to generate too much redirect requests on the client side (one HTML page would contain a lot of links to this API).

thx.

Upvotes: 0

Views: 642

Answers (3)

Graham Dumpleton
Graham Dumpleton

Reputation: 58523

See later part of this section in documentation:

http://code.google.com/p/modwsgi/wiki/ConfigurationGuidelines#The_Apache_Alias_Directive

Using Alias/AddHandler/mod_rewrite allows Django to overlay static files in filesystem. In other words, static files take precedence.

Upvotes: 0

Evan Brumley
Evan Brumley

Reputation: 2468

The simplest solution of the top of my head would be to use an Apache rewrite rule with a condition.

RewriteCond %(REQUEST_URI) ^media
RewriteCond %{REQUEST_FILENAME} !-f 
RewriteRule #Some rewrite rule to redirect from '/media/filename' to '/image_generator/filename'

This basically just checks to see whether the file exists in the media directory, and if it doesn't it sends the user to the image generator, which can then generate and save the file to /media where it can be found for the next request.

NB: I've never actually tried this sort of redirection with Django, so it may need some measure of tweaking..

Upvotes: 2

S.Lott
S.Lott

Reputation: 391818

For example, is there some sort of way to ask django to send proxy requests to apache and ask apache to serve the file?

You have that exactly backwards.

Read the Django deployment guide. https://docs.djangoproject.com/en/1.3/howto/deployment/modwsgi/#serving-files

Apache should be serving all static files (images, for example) all the time. Always.

Django should never, ever serve an image file (or a .css or .js or anything other than .html).

Upvotes: 0

Related Questions