Home > Mobile >  django manage static files accessibility
django manage static files accessibility

Time:11-09

example app tree:

articles
├── admin.py
├── apps.py
├── models.py
├── static
│   ├── css
│   │   ├── article_change.css
│   │   ├── article_create.css
│   │   ├── article_detail.css
│   └── js (obfuscated)
│       ├── article_create.js
│       ├── article_list.js
│       ├── edit_process.js
│       ├── editor.js
│       └── js (readable)
│           ├── article_create.js
│           ├── article_list.js
│           ├── edit_process.js
│           └── editor.js
├── templates
│   └── articles
│       ├── article_create.html
│       ├── article_detail.html
│       ├── edit_process.html
│       └── editor.html
├── tests.py
├── urls.py
└── views.py
  1. static/js/js contains javascript that is human readable
  2. static/js contains obfuscated javascript files.

I wrote a template tag to includes files:

@register.simple_tag
def jstatic(path):
    s = ''
    if settings.DEBUG:
        s = 'js/'
    return static(s   path)

in templates, I can do:

<script src="{% jstatic 'js/info.js' %}"></script>

which conditionally renders static javascript files based on DEBUG mode. whereas, if not in DEBUG mode, will serve obfuscated files.

the thing is, I don't want unobfuscated file to be accessed when DEBUG is not on, which is running the application on server.

when debug is on, I want user user only to visit obfuscated files:

static/js/js/info.js

and have no access to

static/js/info.js

all the apps follows this root tree convention, I wonder if there is a way, for me to block static/js/info.js is DEBUG is not on.


I have thought about shell setting directory permissions, but give up eventually. because, it will not work due to the wrapping structure of the directory. and it will be too much work to modify it, in the project there are about 20 apps.

CodePudding user response:

This is not possible through standard configuration. How to solve this depends on your configuration, but there are three ways to solve this:

  • If you use some kind of minifier/webpack like configuration to obfuscate your JS files, you could move the JS files to a src directory and have your tooling only copy when DEBUG is True, and copy and obfuscate when debug is False.

  • You can use two static directories, one for readable files, and the other for obfuscated files (something like src/static/* and dist/static/*), and then only point to the source directory on development environments: STATICFILES_DIRS = [ "src/static", "dist/static"] vs. STATICFILES_DIRS = [ "dist/static"] on production. In this case, Django's static files finder will return the first match found.

  • Leave your configuration as is, but use a webserver like NGINX for serving static files (Which is already the recommended way to serve static files.) In NGINX's configuration you can define a location that 404's as long as it appears before the location serving your static files.

  • Related