exupero / django-cors

Django utilities for handling Cross-Origin Resource Sharing.
21 stars 9 forks source link

does not work for static files (internal server/runserver) #3

Open theandyl opened 12 years ago

theandyl commented 12 years ago

Hi,

great solution! Thanks. However, the middleware does not send headers when serving static files - this would be ok for Apache via WSGI since it can be achieved by mod_headers. But for local testing it would be great, if django-cors middleware would also add headers to files served by staticfiles. Is there a chance to do this?

thanks a lot! Andy

exupero commented 12 years ago

Sorry to just now see this, @theandyl. I haven't run into the situation you're talking about; would you mind describing your setup a bit more?

theandyl commented 12 years ago

Hi @exupero!

I wrote a quick patch for django core, which hooks in django-cors - this is not a final solution, however, it saved me the night ;-)

Maybe it helps to understand what I mean. Because static files are not served via the middleware pipeline, no CORS headers will be set for images, CSS, and most importantly JS files!

Best, Andy

--- ../bigdatamaps_server/venv/lib/python2.7/site-packages/django/views/static.py   2012-09-26 23:59:13.000000000 +0200
+++ venv/lib/python2.7/site-packages/django/views/static.py 2012-10-13 18:37:16.000000000 +0200
@@ -62,6 +62,12 @@
     with open(fullpath, 'rb') as f:
         response = HttpResponse(f.read(), mimetype=mimetype)
     response["Last-Modified"] = http_date(statobj.st_mtime)
+
+    # cors middleware hook
+    from cors.middleware import AllowOriginMiddleware
+    cmw = AllowOriginMiddleware()
+    cmw.process_response(request, response)
+    
     if stat.S_ISREG(statobj.st_mode):
         response["Content-Length"] = statobj.st_size
     if encoding:

if you want to get an executable patch (github applied formatting rules), just drop me a message

exupero commented 12 years ago

(I fiddled with your comment to pretty the diff snippet.)

Thanks for the explanation about static files not going through middleware. I didn't know that about Django. How to fix that is a good question. I'll have to think about that a bit.