I have a Django project, and what I would like to do is be able to create a reference to a variable defined in urls.py that is kept for the duration of the process.
I've tried an approach using global vars - but for whatever reason, the value of the variable in urls.py is the initial value - even if I change it somewhere else. I've followed the concepts as explained here, but just doesn't work.
However, when I try such a scenario outside of Django, it works as expected.
I think I'm missing a trick (or two) with Django - it's great, I'm new to it, and I think I'm going down the wrong path. Should I be using the caching stuff included with Django to store the variable, or is that even more off track?
Many thanks for any pointers.
I agree with S.Lott's comment, your question is a little vague. I think you're trying to reference some variable defined in urls? You know you can import urls.py into any other python script as long as it's on your PYTHONPATH. Assuming you're talking about a Django view when you say a "process", you could import a URL directly into a view function:
def foo_view(request):
from bar_app.urls import BAR_URL_PATTERN
Please give us more information on your specific use case, and I'll amend my answer to give you a better response.
Good Luck! I hope you're enjoying your first foray into the wonderful world of Django!
Related
I want to implement the solution detailed in this thread but I can't for the life of me figure out the Python path syntax in settings.py needed to link back to my custom validators.py I'm not even sure where to put it. I feel like a simple explanation of how the Python path syntax works in Django ought to be in the docs but after almost 20 minutes of looking through them I don't see anything. Any help would be greatly appreciated.
I'm assuming your custom validators.py is within your project, so like any of your other Python project's module it is accessed using dot notation.
The only thing "different" here is that you append the actual class name to this module string. For example:
AUTH_PASSWORD_VALIDATORS = [
'yourproject.validators.YourValidatorClass',
]
(although the format is not specified in this specific setting in the docs, it is a constant pattern used throughout Django settings)
I am using RIDE and looking for a variable e.g. ${customer_email} . I only see Search option for Keyword,Tests and Tag. Any idea how to find it?
Thanks
AFAIK there is no way to search for a variable in RIDE, however you can use the keyword Log Variables that will provide you with all variables in the current scope.
it would be very good if in RIDE user is able to search variables in resource files. unfortunately it's impossible for now.
In the Django docs it says about url patterns:
It is possible to pass a string containing the path to a view rather
than the actual Python function object. This alternative is supported
for the time being, though is not recommended and will be removed in a
future version of Django.
Does anyone have any insight as to why this the case? I find this alternative to be quite handy and can't find anything explaining why this is a bad (or, at least, less than ideal) idea.
I think the 1.8 Release Notes in the repo explains it quite well. Here's a summary of the main points:
In the modern era, we have updated the tutorial to instead recommend importing
your views module and referencing your view functions (or classes) directly.
This has a number of advantages, all deriving from the fact that we are using
normal Python in place of "Django String Magic": the errors when you mistype a
view name are less obscure, IDEs can help with autocompletion of view names,
etc.
Thus patterns() serves little purpose and is a burden when teaching new users
(answering the newbie's question "why do I need this empty string as the first
argument to patterns()?"). For these reasons, we are deprecating it.
Updating your code is as simple as ensuring that urlpatterns is a list of
:func:django.conf.urls.url instances.
I don't have an easy access to the code, I'm working only with a Mako template, and I would like to know all the values that were made available to the template, which I can use.
Is there a way to add something in the template, so that the output result would contain all the variables (recursively)?
You're looking for the context object. After a minute or two of play:
${context.keys()} # list of direct variable names
${context.__dict__} # probably more along what you're looking for.
The entire section on the Mako Runtime environment is probably worth reading, especially the part 'All the built in names.' You may find the other post I just made relevant:
Mako how to check if variable exists or not.
Lets try this I think this must help:
${globals()}
One of my favorite features about python is that you can write configuration files in python that are very simple to read and understand. If you put a few boundaries on yourself, you can be pretty confident that non-pythonistas will know exactly what you mean and will be perfectly capable of reconfiguring your program.
My question is, what exactly are those boundaries? My own personal heuristic was
Avoid flow control. No functions, loops, or conditionals. Those wouldn't be in a text config file and people aren't expecting to have understand them. In general, it probably shouldn't matter the order in which your statements execute.
Stick to literal assignments. Methods and functions called on objects are harder to think through. Anything implicit is going to be a mess. If there's something complicated that has to happen with your parameters, change how they're interpreted.
Language keywords and error handling are right out.
I guess I ask this because I came across a situation with my Django config file where it seems to be useful to break these rules. I happen to like it, but I feel a little guilty. Basically, my project is deployed through svn checkouts to a couple different servers that won't all be configured the same (some will share a database, some won't, for example). So, I throw a hook at the end:
try:
from settings_overrides import *
LOCALIZED = True
except ImportError:
LOCALIZED = False
where settings_overrides is on the python path but outside the working copy. What do you think, either about this example, or about python config boundaries in general?
There is a Django wiki page, which addresses exactly the thing you're asking.
http://code.djangoproject.com/wiki/SplitSettings
Do not reinvent the wheel. Use configparser and INI files. Python files are to easy to break by someone, who doesn't know Python.
Your heuristics are good. Rules are made so that boundaries are set and only broken when it's obviously a vastly better solution than the alternate.
Still, I can't help but wonder that the site checking code should be in the parser, and an additional configuration item added that selects which option should be taken.
I don't think that in this case the alternative is so bad that breaking the rules makes sense...
-Adam
I think it's a pain vs pleasure argument.
It's not wrong to put code in a Python config file because it's all valid Python, but it does mean you could confuse a user who comes in to reconfigure an app. If you're that worried about it, rope it off with comments explaining roughly what it does and that the user shouldn't edit it, rather edit the settings_overrides.py file.
As for your example, that's nigh on essential for developers to test then deploy their apps. Definitely more pleasure than pain. But you should really do this instead:
LOCALIZED = False
try:
from settings_overrides import *
except ImportError:
pass
And in your settings_overrides.py file:
LOCALIZED = True
... If nothing but to make it clear what that file does.. What you're doing there splits overrides into two places.
As a general practice, see the other answers on the page; it all depends. Specifically for Django, however, I see nothing fundamentally wrong with writing code in the settings.py file... after all, the settings file IS code :-)
The Django docs on settings themselves say:
A settings file is just a Python module with module-level variables.
And give the example:
assign settings dynamically using normal Python syntax. For example:
MY_SETTING = [str(i) for i in range(30)]
Settings as code is also a security risk. You import your "config", but in reality you are executing whatever code is in that file. Put config in files that you parse first and you can reject nonsensical or malicious values, even if it is more work for you. I blogged about this in December 2008.