Giter Site home page Giter Site logo

dj-static's Introduction

DJ-Static

This is a simple Django middleware utility that allows you to properly serve static assets from production with a WSGI server like Gunicorn.

Note

You should probably use WhiteNoise instead. It's better software.

Django doesn't recommend the production use of its static file server for a number of reasons. There exists, however, a lovely WSGI application aptly named Static.

http://farm8.staticflickr.com/7387/8907351990_58677d7c35_z.jpg

"Finally, a super-simple way of serving assets in Django that’ll actually perform well" — @jacobian

It is suitable for the production use of static file serving, unlike Django. Enjoy!

Shouldn't I use a CDN?

If you have to ask that question, there's actually quite a good chance you don't. Static responses aren't very different than dynamic ones.

If you're running a top-tier application, optimizing for delivery and reducing frontend load, you will want to explore using a CDN with Django-Storages.

Usage

$ pip install dj-static

Configure your static assets in settings.py:

STATIC_ROOT = 'staticfiles'
STATIC_URL = '/static/'

Then, update your wsgi.py file to use dj-static:

from django.core.wsgi import get_wsgi_application
from dj_static import Cling

application = Cling(get_wsgi_application())

File uploads (optional)

In case you also want to serve media files that were uploaded to MEDIA_ROOT:

MEDIA_ROOT = 'media'
MEDIA_URL = '/media/'

Then again, update your wsgi.py file:

from django.core.wsgi import get_wsgi_application
from dj_static import Cling, MediaCling

application = Cling(MediaCling(get_wsgi_application()))

dj-static's People

Contributors

agriffis avatar andrewsg avatar axelmagn avatar gciding avatar goldibex avatar gone avatar jezdez avatar kennethreitz avatar kwilcox avatar maria avatar metakermit avatar roadmaster avatar salmanulfarzy avatar stefanw avatar tinnet avatar treyhunner avatar wking avatar wnh avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

dj-static's Issues

Error when deploying to Heroku

I was having this error when trying to deploy a Django app to Heroku (following their tutorial). This also happens when running foreman start locally.

ImproperlyConfigured: Requested setting USE_I18N, but settings are not configured.
You must either define the environment variable DJANGO_SETTINGS_MODULE or call
settings.configure() before accessing settings.

The solution?
Setting the DJANGO_SETTINGS_MODULE before importing and calling Cling.

import os
from django.core.wsgi import get_wsgi_application

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'trappt.settings')

from dj_static import Cling
application = Cling(get_wsgi_application())

AssertionError: Header values must be strings

2014-02-08T00:17:59.628381+00:00 app[web.1]: Traceback (most recent call last):
2014-02-08T00:17:59.628381+00:00 app[web.1]:   File "/app/.heroku/python/lib/python2.7/wsgiref/handlers.py", line 85, in run
2014-02-08T00:17:59.628381+00:00 app[web.1]:     self.result = application(self.environ, self.start_response)
2014-02-08T00:17:59.628381+00:00 app[web.1]:   File "/app/.heroku/python/lib/python2.7/site-packages/dj_static.py", line 64, in __call__
2014-02-08T00:17:59.628381+00:00 app[web.1]:     return self.cling(environ, start_response)
2014-02-08T00:17:59.628381+00:00 app[web.1]:   File "/app/.heroku/python/lib/python2.7/site-packages/static/apps.py", line 118, in __call__
2014-02-08T00:17:59.628381+00:00 app[web.1]:     start_response("200 OK", headers)
2014-02-08T00:17:59.628381+00:00 app[web.1]:   File "/app/.heroku/python/lib/python2.7/wsgiref/handlers.py", line 180, in start_response
2014-02-08T00:17:59.628381+00:00 app[web.1]:     assert type(val) is StringType,"Header values must be strings"
2014-02-08T00:17:59.628381+00:00 app[web.1]: AssertionError: Header values must be strings

I'm getting this. Any ideas? Only happens with JavaScript files. Versions: dj-static==0.0.5, static==1.0.2, and django-pipeline==1.3.16.

CORS header on images

Hi,

i noticed that calls to my images are not even passing the django cors headers middleware and thus those requests wont get the CORS headers attached. What's the best option to get CORS headers on media files without removing djstatic?

Static files not working on Heroku with Django 1.8

With Django 1.7, I have no problem serving my static files on Heroku. With Django 1.8, it overwrites static every time I call collectstatic, as if the files are not there, and when I go to my site, all static files are a 404.

index.html not found in media_root

I followed the tutorial to set the MEDIA_ROOT.
My settings at below:

# wsgi.py 
import os

from django.core.wsgi import get_wsgi_application
from dj_static import Cling, MediaCling

os.environ.setdefault("DJANGO_SETTINGS_MODULE", "myapp.settings")
application = Cling(MediaCling(get_wsgi_application()))
#settings.py
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
DEBUG = True
ALLOWED_HOSTS = ['*']
...
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'static', 'static_root')
STATICFILES_DIRS = (os.path.join(BASE_DIR, 'static', 'static_dirs'),
)

MEDIA_ROOT = os.path.join(BASE_DIR, 'static', 'media_root')
MEIDA_URL = '/media/'

My error message :
[WinError 2] The system cannot find the file specified : 'C:/myapps/static/media_root/index.html'

And my localhost:8000 directs me to 404 Not Found

I found this code in static.py. I think is somehow related to the issue.

class Cling(object):

    """A stupidly simple way to serve static content via WSGI.

    Serve the file of the same path as PATH_INFO in self.datadir.

    Look up the Content-type in self.content_types by extension
    or use 'text/plain' if the extension is not found.

    Serve up the contents of the file or delegate to self.not_found.
    """

    block_size = 16 * 4096
    index_file = 'index.html'
    not_found = StatusApp('404 Not Found')

New version for static/static3

The current version on PyPi 0.0.6 has the static3 requirement.
Would it be possible to do a 0.0.7 release that captures the change in setup.py back to static?

Thanks.

When starting django server out of the root path, statics paths can fail

I managed to find/solve my problem, but I still wanted to ask in case some one have the same problem. I also would like to know if this is a normal behaviour! (I'm pretty new to django..)

I created a django server and I installed dj-static. When I was developping over my computer everything worked great, all the static files was working. Then, when I moved the project over
a server and I realized that some static files didn't work... Long story or short, after some time I found that the problem was the way of starting the server:

  • it seems that to make dj-static work correctly, the current working directory must be in the mange folder.

For example, my project was under /django, and starting it by doing
'python /django/manage runserver 0.0.0.0:80' if my current directory is /
some static urls failed. But when doing a cd /django and then starting the server it works like a charm.

ImportError: cannot import name get_path_info

I am on the way to deploy my application to heroku finally i add below lines to wsgi.py

from dj_static import Cling
application = Cling(get_wsgi_application())     

Then below error is comming ;--

(env)ri@ri-desktop:~/studio/project/readtamil$ foreman start
17:57:26 web.1  | started with pid 22896
17:57:26 web.1  | 2014-09-10 17:57:26 [22896] [INFO] Starting gunicorn 18.0
17:57:26 web.1  | 2014-09-10 17:57:26 [22896] [INFO] Listening at: http://0.0.0.0:5000 (22896)
17:57:26 web.1  | 2014-09-10 17:57:26 [22896] [INFO] Using worker: sync
17:57:26 web.1  | 2014-09-10 17:57:26 [22903] [INFO] Booting worker with pid: 22903
17:57:26 web.1  | 2014-09-10 17:57:26 [22903] [ERROR] Exception in worker process:
17:57:26 web.1  | Traceback (most recent call last):
17:57:26 web.1  |   File "/home/ri/studio/project/env/local/lib/python2.7/site-packages/gunicorn/arbiter.py", line 495, in spawn_worker
17:57:26 web.1  |     worker.init_process()
17:57:26 web.1  |   File "/home/ri/studio/project/env/local/lib/python2.7/site-packages/gunicorn/workers/base.py", line 106, in init_process
17:57:26 web.1  |     self.wsgi = self.app.wsgi()
17:57:26 web.1  |   File "/home/ri/studio/project/env/local/lib/python2.7/site-packages/gunicorn/app/base.py", line 114, in wsgi
17:57:26 web.1  |     self.callable = self.load()
17:57:26 web.1  |   File "/home/ri/studio/project/env/local/lib/python2.7/site-packages/gunicorn/app/wsgiapp.py", line 62, in load
17:57:26 web.1  |     return self.load_wsgiapp()
17:57:26 web.1  |   File "/home/ri/studio/project/env/local/lib/python2.7/site-packages/gunicorn/app/wsgiapp.py", line 49, in load_wsgiapp
17:57:26 web.1  |     return util.import_app(self.app_uri)
17:57:26 web.1  |   File "/home/ri/studio/project/env/local/lib/python2.7/site-packages/gunicorn/util.py", line 354, in import_app
17:57:26 web.1  |     __import__(module)
17:57:26 web.1  |   File "/home/ri/studio/project/readtamil/readtamil/wsgi.py", line 28, in <module>
17:57:26 web.1  |     from dj_static import Cling
17:57:26 web.1  |   File "/home/ri/studio/project/env/local/lib/python2.7/site-packages/dj_static.py", line 7, in <module>
17:57:26 web.1  |     from django.core.handlers.base import get_path_info
17:57:26 web.1  | ImportError: cannot import name get_path_info

But i pushed my project to heroku, And my app running in heroku, Still no problem but i am not using dj-static here. Is that important ? And still i am getting the error when i put cling there.

I posted question in stackoverflow also but no answer there too..

http://stackoverflow.com/questions/25844101/importerror-cannot-import-name-get-path-info

Getting "Internal Server Error" with non-contrib `staticfiles` and DEBUG=True

If you are using Django + django-staticfiles + DEBUG=True, then you get a generic "Internal Server Error".

If you dig down, the error raised is:

Finder "<class 'staticfiles.finders.FileSystemFinder'>" is not a subclass of "<class 'django.contrib.staticfiles.finders.BaseFinder'>"

The solution is to use django.contrib.staticfiles instead of staticfiles.

Opening and closing in case anyone else runs into this.

Add ability to serve media uploads

I realize that file uploads are less likely to happen on Heroku, your home platform, but in case people want to use DJ Static for other platforms where writable file storage exists, e.g. Webfaction, they should be able to do that.

I propose to add a MediaCling which has get_base_url|dir methods using the MEDIA_* settings and doesn't use staticfiles' WSGI handler in debug mode but static's Cling, too.

pypi version is out of date

The Cling constructor in the PyPI version has this:

self.cling = static.Cling(base_dir)
self.debug_cling = DebugHandler(base_dir)

but the DebugHandler constructor expectes (application, base_dir=base_dir). This was already fixed a while back in 907b03f but we need a new release. Thank you!

dj_static does not work with Django 1.7 dev server

Django 1.7 static file changes appear to break the latest (from master) version of dj-static:

System check identified no issues.
January 20, 2014 - 15:53:33
Django version 1.7.dev20140120183207, using settings 'redactedapp.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CONTROL-C.
Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x7f1d91dc0050>
Traceback (most recent call last):
  File "/home/andrewsg/src/redactedapp-py3-env/src/django/django/utils/autoreload.py", line 170, in wrapper
    fn(*args, **kwargs)
  File "/home/andrewsg/src/redactedapp-py3-env/src/django/django/core/management/commands/runserver.py", line 127, in inner_run
    handler = self.get_handler(*args, **options)
  File "/home/andrewsg/src/redactedapp-py3-env/src/django/django/contrib/staticfiles/management/commands/runserver.py", line 25, in get_handler
    handler = super(Command, self).get_handler(*args, **options)
  File "/home/andrewsg/src/redactedapp-py3-env/src/django/django/core/management/commands/runserver.py", line 46, in get_handler
    return get_internal_wsgi_application()
  File "/home/andrewsg/src/redactedapp-py3-env/src/django/django/core/servers/basehttp.py", line 55, in get_internal_wsgi_application
    error_prefix="WSGI application '%s' could not be loaded; " % app_path
  File "/home/andrewsg/src/redactedapp-py3-env/src/django/django/utils/module_loading.py", line 24, in import_by_path
    module = import_module(module_path)
  File "/home/andrewsg/src/redactedapp-py3-env/lib/python3.3/importlib/__init__.py", line 90, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
  File "<frozen importlib._bootstrap>", line 1584, in _gcd_import
  File "<frozen importlib._bootstrap>", line 1565, in _find_and_load
  File "<frozen importlib._bootstrap>", line 1532, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 584, in _check_name_wrapper
  File "<frozen importlib._bootstrap>", line 1022, in load_module
  File "<frozen importlib._bootstrap>", line 1003, in load_module
  File "<frozen importlib._bootstrap>", line 560, in module_for_loader_wrapper
  File "<frozen importlib._bootstrap>", line 868, in _load_module
  File "<frozen importlib._bootstrap>", line 313, in _call_with_frames_removed
  File "/home/andrewsg/src/redactedapp-venv/redactedapp/redactedapp/wsgi.py", line 16, in <module>
    application = Cling(get_wsgi_application())
  File "/home/andrewsg/src/redactedapp-py3-env/src/dj-static/dj_static.py", line 44, in __init__
    self.debug_cling = DebugHandler(application, base_dir=base_dir)
TypeError: __init__() got an unexpected keyword argument 'base_dir'

This appears to be a signature change to StaticFilesHandler; in 1.6 it accepted a base_dir kwarg and in 1.7 it does not.

Cannot make it work with DEBUG=False on Heroku

I'm trying to serve statics on heroku with DEBUG=False. When DEBUG is True everything works perfectly so it is when I run my application locally with Heroku's Foreman. Collectstatic runs with no problems in both ambients.
Forman works with the following setting:

STATIC_ROOT = root('staticfiles')
STATIC_URL = '/static/'

But i've tried setting it with:

STATIC_ROOT = 'staticfiles'
STATIC_URL = '/static/'

with no success.

My app is structured in the following way:

Procfile
requirements.txt
projetc/
   manage.py
   project/
   staticfiles/

I'm setting --pythonpath to the project folder in the procfile.

base_url option missing

The base_url option that was added in #26 is missing from the dj-static available on PyPI.
Since the latest PyPI release happened on the same day that PR was merged, I'd guess that there was an issue with the release.

Allow using `dj-static` in view form

I currently have this in my urlpatterns:

url(r'^favicon.ico$', 'django.views.static.serve',
    {'document_root': settings.STATIC_ROOT,
     'show_indexes': False,
     'path': django.conf.settings.FAVICON_PATH,}),

This serves favicon.ico using Django's own static file serving.

It would be nice if I could serve favicon.ico using dj-static. Can dj-static be made to be invokable as a view?

Anyone else experiencing below error when running pip install dj-static

Downloading/unpacking dj-static
Running setup.py egg_info for package dj-static

Downloading/unpacking static (from dj-static)
Running setup.py egg_info for package static
Traceback (most recent call last):
File "", line 16, in
File "/home/ogi/virtualenv/trypviewer/build/static/setup.py", line 7, in
with open('README.md') as readme_file:
IOError: [Errno 2] No such file or directory: 'README.md'
Complete output from command python setup.py egg_info:
Traceback (most recent call last):

File "", line 16, in

File "/home/ogi/virtualenv/trypviewer/build/static/setup.py", line 7, in

with open('README.md') as readme_file:

IOError: [Errno 2] No such file or directory: 'README.md'

dj-static works with runserver but not gunicorn?

I've been trying to get dj-static to work on my site but for some reason it doesn't seem to work with gunicorn. This can't be (that's the whole point of dj-static!) and I was sure it was PEBCAK, so I created a brand new hellodjango app following the instructions here to be sure it wasn't something in my code.

Steps to reproduce:

  • Copy the code for this app
  • Activate the virtualenv: $ source venv/bin/activate
  • Run collectstatic (you may have to do $ mkdir staticfiles first): $ foreman run python manage.py collectstatic --noinput

Now, run foreman run python manage.py runserver and visit http://127.0.0.1:8000/static/test.txt and see SUCCESS. Looking good so far!
Kill that and run gunicorn foreman run gunicorn hellodjango.wsgi and visit http://127.0.0.1:8000/static/test.txt and see a 'Page not found (404)' error. If you visit http://127.0.0.1:8000 instead you'll see that gunicorn does work, just not for static content.

How can this be? What am I doing wrong?

Thanks!

Also, one uber-weird note: if I set DEBUG and TEMPLATE_DEBUG to False. Then I get a 404 page using both runserver and gunicorn. Perhaps this is the same thing happening in issue #11?

Update pypi to include MediaCling

Version 0.0.5 that is currently on pypi does not include the MediaCling class. This means you cannot follow the read me instructions on github using pip install dj-static and get the results shown. Instead you get:

ImportError: cannot import name MediaCling

Just a friendly reminder to update pypi. It looks like hundreds of people download this project from pypi each day.

https://pypi.python.org/pypi/dj-static/0.0.5

The workaround is to install from github directly.

pip install -e git+git://github.com/kennethreitz/dj-static.git#egg=dj-static

Static requests are slower with dj-static than without

We've been using Django's builtin static serving, and today I gave dj-static a try. (We're on Heroku, for what it's worth.)

It made everything slower. For example, one static request that previously took 85ms, now takes 466ms. Another request that took 322ms, now takes 1,120ms.

Any idea why?

(One suspicion I have is that dj-static isn't emitting the correct cache headers, causing CloudFlare to not cache them correctly. But even so... I don't think that explain a 1,120ms response time for a static file.

Cache-Control headers

I can't see anything in the documentation about whether it's possible to set cache-control headers on the returned files. If such a thing were possible, it would be great!

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.