In Django can I dump out a variable to see what is in it within a view (not using command line)?
for example:
device = mobile(request)
print device
abort
or
device = mobile(request)
return HttpResponse(device)
Writing to a file is usually a fool-proof way to "dump" data as a debug method when you are working with a hooked framework that doesn't otherwise lend itself well to direct debugging.
e.g.
device = mobile(request)
with open('path/to/debug_out.txt', 'w') as outfile:
outfile.write(device)
abort
for convenience, you could put this in a predefined function in some debug helper module. Alternatively, you could use sys.excepthook to automatically write all exceptions to this file, before forwarding/re-raising them.
There is a similar question:
Django debug display all variables of a page
You can type
assert False, locals()
in your view to see all your view variables. Or use the {%debug%} template tag inside your template which will do the same.
Related
How to replace just one exception template for own exception inside a plugin, which is extended built-in exception? :)
Exception located is in /vendor/author/pluginName/src/Exception/TestException.php
But i try replace template by create file /src/Template/PluginName/Error/test.ctp but doesn't work.
Of course, if I create file inside /src/Template/Error/test.ctp works fine.
I have many plugins and each can has own TestException class.
So, How I can use /PluginName direcotry?
Cake 3.6
The correct template path for overriding a plugin template on app level starts with Template/Plugin/, followed by the plugin name and the expected local template path, ie for a plugin named Foobar, the path for overriding its test error template would be:
src/Template/Plugin/Foobar/Error/test.ctp
Also it's important to keep in mind that error templates will by default only be looked up in plugins, if the exception is being triggered in a plugin controller request, to be specific, when the current global request object (Router::getRequest(true)) has a plugin parameter set ($request->getParam('plugin'))!
It should also be noted that individual templates that map to exception/method names, will only be used for non-HTTP exceptions (\Cake\Http\Exception\HttpException), and only when debug mode is enabled, if it's a HTTP-Exception or debug mode is disabled, then only the error400 or error500 template will be used!
See also
Cookbook > Plugins > Plugin Views > Overriding Plugin Templates from Inside Your Application
I'm using the program Maya to make a rather large project in python. I have numerous options that will be determined by a GUI and input by the user.
One example of an option is what dimensions to render at. However I did not make a GUI yet and am still in the testing faze.
What I ultimately want is a way to have variables be able to be looked up and used by various classes/methods within multiple modules. And also that there be a way that I can test all the code without having an actual GUI.
Should I directly pass all data to each method? My issue with this is if method foo relies on variable A, but method bar needs to call foo, it could get real annoying passing these variables to Foo from everywhere its called.
Another way I saw was passing all variables through to each class instance itself and using instance variables to access. But what if an option changes, then i'd have to put reload imports every time it runs.
For testing what I use now is a module that gets variables from a config file with the variables, and i import that module and use the instance variables throughout the script.
def __init__(self):
# Get and assign all instance variables.
options = config_section_map('Attrs', '%s\\ui_options.ini' %(data_path))
for k, v in options.items():
if v.lower() == 'none':
options[k] = None
self.check_all = int(options['check_all'])
self.control_group = options['control_group']
Does anyone have advice or can point me in the right direction dealing with getting/using ui variables?
If the options list is not overly long and won't change, you can simply set member variables in the class initializer, which makes the initialization easy for readers to understand:
class OptionData(object):
def __init___(self):
#set the options on startup
self.initial_path = "//network"
self.initial_name = "filename"
self.use_hdr = True
# ... etc
If you expect the initializations to change often you can split out the initial values into the constructor for the class:
class OptionData(object):
def __init___(self, path = "//network", name = "filename", hdr=True)
self.initial_path = path
self.initial_name = name
self.use_hdr = hdr
If you need to persist the data, you can fill out the class reading the cfg file as you're doing, or store it in some other way. Persisting makes things harder because you can't guarantee that the user won't open two Maya's at the same time, potentially changing the saved data in unpredictable ways. You can store per-file copies of the data using Maya's fileInfo.
In both of these cases I'd make the actual GUI take the data object (the OptionData or whatever you call yours) as an initializer. That way you can read and write the data from the GUI. Then have the actual functional code read the OptionData:
def perform_render(optiondata):
#.... etc
That way you can run a batch process without the gui at all and the functional code will be none the wiser. The GUI's only job is to be a custom editor for the data object and then to pass it on to the final function in a valid state.
When I raise my owns exceptions in my Python libraries, the exception stack shows the raise-line itself as the last item of the stack. This is obviously not an error, is conceptually right, but points the focus on something that is not useful for debugging when you're are using code externally, for example as a module.
Is there a way to avoid this and force Python to show the previous-to-last stack item as the last one, like the standard Python libraries.
Due warning: modifying the behaviour of the interpreter is generally frowned upon. And in any case, seeing exactly where an error was raised may be helpful in debugging, especially if a function can raise an error for several different reasons.
If you use the traceback module, and replace sys.excepthook with a custom function, it's probably possible to do this. But making the change will affect error display for the entire program, not just your module, so is probably not recommended.
You could also look at putting code in try/except blocks, then modifying the error and re-raising it. But your time is probably better spent making unexpected errors unlikely, and writing informative error messages for those that could arise.
you can create your own exception hook in python. below is the example of code that i am using.
import sys
import traceback
def exceptionHandler(got_exception_type, got_exception, got_traceback):
listing = traceback.format_exception(got_exception_type, got_exception, got_traceback)
# Removing the listing of statement raise (raise line).
del listing[-2]
filelist = ["org.python.pydev"] # avoiding the debuger modules.
listing = [ item for item in listing if len([f for f in filelist if f in item]) == 0 ]
files = [line for line in listing if line.startswith(" File")]
if len(files) == 1:
# only one file, remove the header.
del listing[0]
print>>sys.stderr, "".join(listing)
And below are some lines that I have used in my custom exception code.
sys.excepthook = exceptionHandler
raise Exception("My Custom error message.")
In the method exception you can add file names or module names in list "filenames" if you want to ignore any unwanted files. As I have ignored the python pydev module since I am using pydev debugger in eclipse.
The above is used in my own module for a specific purpose. you can modify and use it for your modules.
I'd suggest to not use the Exception mechanism to validate arguments, as tempting as that is. Coding with exceptions as conditionals is like saying, "crash my app if, as a developer, I don't think of all the bad conditions my provided arguments can cause. Perhaps using exceptions for things not only out of your control but also which is under control of something else like the OS or hardware or the Python language would be more logical, I don't know. In practice however I use exceptions as you request a solution for.
To answer your question, in part, it is just as simple to code thusly:
class MyObject(object):
def saveas(self, filename):
if not validate_filename(filename):
return False
...
caller
if not myobject.saveas(filename): report_and_retry()
Perhaps not a great answer, just something to think about.
So this is how my program flows. User loads a file, through the menu and loadFile function will be called.
def loadFile():
dictList = defaultdict(list)
filename = askopenfilename(filetypes=[("text files","*.txt")])
#process the file content and store in dictList
return dictList
Now in the GUI, when user clicks on the load file menu, load file will get called. Since loadfile returns me a dictList object, which I need it for further processing later. How do I get the returned object without using global variables? I'm not coding in object-oriented way either.
fileMenu.add_command(label="Load File", command=loadFile)
You can't do it without using a global variable. The variable has to be stored in a way that it can be accessed from multiple functions. Since you're not using objects, your only1 choice is to use a global variable.
1 technically speaking, it's not your only choice. You could use a database of some sort, or write the value to disk, but it's the only practical choice in this scenario.
I understand that to share variables between templates you have to use hook preprocess.
I think I've got the hook preprocess bit ok.
I've got this in my theme's template php file.
function rootcandy_preprocess_views_view_fields__default(&$vars) {
$vars ['brian'] = 'hello from brian';
In views-view-fields--default.tpl.php I've got this:
print $brian ;
So it prints out "hello from brian". Hooray.
However I want to print out the header of my View - which is available in views-view.tpl.php but not in views-view-fields.
This code below looks promising but I don't understand why it doesn't result in my header being printed out in views-view-fields--default.tpl.php
function rootcandy_preprocess_views_view_fields__default(&$vars)
{$vars['mytitle'] = $vars['view']->display[$vars['view']->current_display]->header['area'];
}
I have of course got print $mytitle ; in views-view-fields--default.tpl.php
Any ideas?
Thanks.
It is a matter of timing, when views-view-fields is parsing, views-view has been parsed and you can't get his variables - They are not 'existing' anymore.
Use a function to generate the value and refer to that function in views-view and in views-view-fields, or create a module to produce this value and use it freely in any template.