当前位置: 动力学知识库 > 问答 > 编程问答 >

django - installing snippets

问题描述:

How do I install snippets in django? (specifically this)

I have the file /{project}/snippets/EnforceLoginMiddleware.py and I have tried any number of permutations inside MIDDLEWARE_CLASSES to load it as well as googling django snippets install to no avail :(

Any help would be grateful :)

PS(Why can't I find any documentation or examples on the installation of snippets. Maybe I'm just a bad googler)

网友答案:

"snippets" does not point to a specific element of Django, it just means : here is a piece of code for you to use. In this case, it's a Middleware, a specific Django module that will be called before and after a web request. Read django docs if needed

I use this middleware too, just paste everything in a file called middleware.py in your main application folder (any app folder will do, given this app is mentioned in INSTALLED_APPS)

Then add these lines in your settings.py file :

MIDDLEWARE_CLASSES = (
    #...all others middleware, on the last line, paste :
    'main.middleware.EnforceLoginMiddleware',
)

Note that here the app where I put the file is called main, yours may be named differently.

Don't forget to read the docstring of the snippet :

Middlware class which requires the user to be authenticated for all urls except 
those defined in PUBLIC_URLS in settings.py. PUBLIC_URLS should be a tuple of regular 
expresssions for the urls you want anonymous users to have access to. If PUBLIC_URLS 
is not defined, it falls back to LOGIN_URL or failing that '/accounts/login/'.  
Requests for urls not matching PUBLIC_URLS get redirected to LOGIN_URL with next set 
to original path of the unauthenticted request. 
Any urls statically served by django are excluded from this check. To enforce the same
validation on these set SERVE_STATIC_TO_PUBLIC to False.
网友答案:

You need to make sure your snippet is on your PYTHONPATH (sys.path) or, that the snippet is within a module that exists on your PYTHONPATH.

In this case, if you add an __init__.py file to your snippets folder, that will treat the snippets folder as a module, and then you can do from snippets.EnforceLoginMiddleware import EnforceLoginMiddleware. I think this is the crucial step you're missing.

Your middleware classes would then look like:

MIDDLEWARE_CLASSES = (..., 'snippets.EnforceLoginMiddleware.EnforceLoginMiddleware')
网友答案:

In your example your new entry to MIDDLEWARE_CLASSES would have to look like '{project}.snippets.EnforceLoginMiddleware.EnforceLoginMiddleware' (replace with the package name for your project).

Make sure, that your snippets folder also has an __init__.py file!

P.S.: that's probably because there is no such thing as a "snippet" when it comes to official components in Django. They usually are simple Python code fragments and have to be treated as such. Djangosnippets is just a site where you can post and share django code (also called snippets).

分享给朋友:
您可能感兴趣的文章:
随机阅读: