Server getting overloaded [duplicate] - python

I'm working on a project in Django and I've just started trying to extend the User model in order to make user profiles.
Unfortunately, I've run into a problem: Every time I try to get the user's profile inside of a template (user.get_template.lastIP, for example), I get the following error:
Environment:
Request Method: GET
Request URL: http://localhost:8000/
Django Version: 1.1
Python Version: 2.6.1
Template error:
In template /path/to/base.tpl, error at line 19
Caught an exception while rendering: too many values to unpack
19 : Hello, {{user.username}} ({{ user.get_profile.rep}}). How's it goin? Logout
Exception Type: TemplateSyntaxError at /
Exception Value: Caught an exception while rendering: too many values to unpack
Any ideas as to what's going on or what I'm doing wrong?

That exception means that you are trying to unpack a tuple, but the tuple has too many values with respect to the number of target variables. For example: this work, and prints 1, then 2, then 3
def returnATupleWithThreeValues():
return (1,2,3)
a,b,c = returnATupleWithThreeValues()
print a
print b
print c
But this raises your error
def returnATupleWithThreeValues():
return (1,2,3)
a,b = returnATupleWithThreeValues()
print a
print b
raises
Traceback (most recent call last):
File "c.py", line 3, in ?
a,b = returnATupleWithThreeValues()
ValueError: too many values to unpack
Now, the reason why this happens in your case, I don't know, but maybe this answer will point you in the right direction.

try unpacking in one variable,
python will handle it as a list,
then unpack from the list
def returnATupleWithThreeValues():
return (1,2,3)
a = returnATupleWithThreeValues() # a is a list (1,2,3)
print a[0] # list[0] = 1
print a[1] # list[1] = 2
print a[2] # list[2] = 3

This problem looked familiar so I thought I'd see if I could replicate from the limited amount of information.
A quick search turned up an entry in James Bennett's blog here which mentions that when working with the UserProfile to extend the User model a common mistake in settings.py can cause Django to throw this error.
To quote the blog entry:
The value of the setting is not "appname.models.modelname", it's just "appname.modelname". The reason is that Django is not using this to do a direct import; instead, it's using an internal model-loading function which only wants the name of the app and the name of the model. Trying to do things like "appname.models.modelname" or "projectname.appname.models.modelname" in the AUTH_PROFILE_MODULE setting will cause Django to blow up with the dreaded "too many values to unpack" error, so make sure you've put "appname.modelname", and nothing else, in the value of AUTH_PROFILE_MODULE.
If the OP had copied more of the traceback I would expect to see something like the one below which I was able to duplicate by adding "models" to my AUTH_PROFILE_MODULE setting.
TemplateSyntaxError at /
Caught an exception while rendering: too many values to unpack
Original Traceback (most recent call last):
File "/home/brandon/Development/DJANGO_VERSIONS/Django-1.0/django/template/debug.py", line 71, in render_node
result = node.render(context)
File "/home/brandon/Development/DJANGO_VERSIONS/Django-1.0/django/template/debug.py", line 87, in render
output = force_unicode(self.filter_expression.resolve(context))
File "/home/brandon/Development/DJANGO_VERSIONS/Django-1.0/django/template/__init__.py", line 535, in resolve
obj = self.var.resolve(context)
File "/home/brandon/Development/DJANGO_VERSIONS/Django-1.0/django/template/__init__.py", line 676, in resolve
value = self._resolve_lookup(context)
File "/home/brandon/Development/DJANGO_VERSIONS/Django-1.0/django/template/__init__.py", line 711, in _resolve_lookup
current = current()
File "/home/brandon/Development/DJANGO_VERSIONS/Django-1.0/django/contrib/auth/models.py", line 291, in get_profile
app_label, model_name = settings.AUTH_PROFILE_MODULE.split('.')
ValueError: too many values to unpack
This I think is one of the few cases where Django still has a bit of import magic that tends to cause confusion when a small error doesn't throw the expected exception.
You can see at the end of the traceback that I posted how using anything other than the form "appname.modelname" for the AUTH_PROFILE_MODULE would cause the line "app_label, model_name = settings.AUTH_PROFILE_MODULE.split('.')" to throw the "too many values to unpack" error.
I'm 99% sure that this was the original problem encountered here.

Most likely there is an error somewhere in the get_profile() call. In your view, before you return the request object, put this line:
request.user.get_profile()
It should raise the error, and give you a more detailed traceback, which you can then use to further debug.

This happens to me when I'm using Jinja2 for templates. The problem can be solved by running the development server using the runserver_plus command from django_extensions.
It uses the werkzeug debugger which also happens to be a lot better and has a very nice interactive debugging console. It does some ajax magic to launch a python shell at any frame (in the call stack) so you can debug.

Forgetting enumerate in attempt to access index in a loop
Throws ValueError: too many values to unpack (expected 2):
for index, value in your_list:
assert value is your_list[index] # this line not reached
No Exception thrown:
for index, value enumerate(in your_list):
assert value is your_list[index]

Related

how to use trigger.adddependencies in pyzabbix

i'm a newbie in python and coding,i'm trying to use pyzabbix to add trigger dependecies,but some error occusrs.
When i run
zapi.trigger.addDependencies(triggerid, dependsOnTriggerid)
an error occurs
pyzabbix.ZabbixAPIException: ('Error -32500: Application error., No permissions to referred object or it does not exist!', -32500)
i get the "triggerid" and "dependsOnTriggerid" by trigger.get:
triggerid_info = zapi.trigger.get(filter={'host': 'xx','description': 'xx'},output=['triggerid'], selectDependencies=['description'])
triggerid = triggerid_info[0]['triggerid']
dependsOnTriggerid = trigger_info[0]['dependencies'][0]['triggerid']
The results are as follws:
Traceback (most recent call last): File "E:/10.python/2019-03-07/1.py", line 14, in zapi.trigger.addDependencies(triggerid, dependsOnTriggerid) File "D:\Program Files\Python37\lib\site-packages\pyzabbix__init__.py", line 166, in fn args or kwargs File "D:\Program Files\Python37\lib\site-packages\pyzabbix__init__.py", line 143, in do_request raise ZabbixAPIException(msg, response_json['error']['code']) pyzabbix.ZabbixAPIException: ('Error -32500: Application error., No permissions to referred object or it does not exist!', -32500)
Did i get the wrong triggerid? or the i use the method in a wrong way? Thanks so much
To add a dependancy means that you need to link two different triggers (from the same host or from another one) with a master-dependent logic.
You are trying to add the dependancy triggerid -> dependsOnTriggerid, which is obtained from a supposed existing dependancy (trigger_info[0]['dependencies'][0]['triggerid']), and this makes little sense and I suppose it's the cause of the error.
You need to get both trigger's triggerid and then add the dependancy:
masterTriggerObj = zapi.trigger.get( /* filter to get your master trigger here */ )
dependentTriggerObj = zapi.trigger.get( /* filter to get your dependent trigger here */)
result = zapi.trigger.adddependencies(triggerid=dependentTriggerObj[0]['triggerid'], dependsOnTriggerid=masterTriggerObj[0]['triggerid'])
The method "trigger.addDependencies" need only one parameter,and it should be a dict or some other object/array.The following code solves the problem.
trigger_info = zapi.trigger.get(filter={xx},output=['triggerid'])
trigger_depends_info_193 = zapi.trigger.get(filter={xx},output=['triggerid'])
trigger_dependson_193 = {"triggerid": trigger_info[0]['triggerid'], "dependsOnTriggerid": trigger_depends_info_193[0]['triggerid']}
zapi.trigger.adddependencies(trigger_dependson_193)

Python 3.6.3: Multiple "Exception ignored in: <generator object..." in flask app

I'm running a flask app, upgraded everything from Python 2.7 to 3 about 5 months ago.
Most things have gone smooth enough, other than this one that's consistently bugging me locally. I'm on a MacBook on OSX 10.12.6, and a brew install of Python 3.6.3 under a virtualenv.
When a request comes in from a page that seemingly has multiple static requests (.css, .js, and image files mainly), I seem to be able to get this error just about anywhere that's using generators anywhere in my code.
Some examples (request is a flask.request object):
A place that checks to see if a path starts with '/static' of '/admin/static' (my code),
any(request.path.startswith(k) for k in self._static_paths)
.
Exception ignored in: <generator object CustomPrincipal._is_static_route.<locals>.<genexpr> at 0x11450f3b8>
Traceback (most recent call last):
File "/Developer/repos/git/betapilibs/lbbsports/flask_monkeypatches.py", line 22, in <genexpr>
any(_checker(request.path, k) for k in self._static_paths)
SystemError: error return without exception set
If a url path is restricted, check if the logged in user has the proper permissions / role,
return role in (role.name for role in self.roles)
.
Exception ignored in: <generator object UserMixin.has_role.<locals>.<genexpr> at 0x1155a7e08>
Traceback (most recent call last):
File "/Developer/virtualenvs/lbb3/lib/python3.6/site-packages/flask_security/core.py", line 386, in <genexpr>
SystemError: error return without exception set
A custom bit of code to ensure their "sub" account id is valid,
(not any(ident == account_id for ident in account_ids))
.
Exception ignored in: <generator object CustomSession.get_set_accounts.<locals>.<genexpr> at 0x115ff4fc0>
Traceback (most recent call last):
File "/Developer/customflask/flasklogin.py", line 168, in <genexpr>
SystemError: error return without exception set
Now, nothing seems to break in the system, I just get these error messages, and not consistently, only sometimes. If I set a breakpoint anywhere these errors are being reported to be happening, they don't error any more.
If I do something like, in the first example, break it into request.path.startswith('/static') or request.path.startswith('/admin/static'), I no longer get the error message, and in general, I never have a problem using request all over the place in the rest of the app.
A thing that was wrong in my local development setup was that I was serving all the /static and /admin/static through the flask app, instead of serving them through the web-server (in my case, nginx). So for some of the urls I was hitting, there might have been 10 requests come in basically at the same time, with Flask in debug mode, and a debugger connected as well (via PyCharm).
When I went through the trouble to ensure that all '/static' and '/admin/static' get served from there, instead of via flask, and flask was only getting 1 request per url, this problem went away.
I won't mark this as the answer, because there is still an underlying issue, but in case others have the same problem as me, this was a solution for my situation.

openwhisk error: "The action did not return a dictionary."

when trying to invoke an openwhisk action, I'm getting a 400 error with the following result and log:
Results:
114492bd33e444c88492bd33e4a4c8a8
{
"error": "The action did not return a dictionary."
}
Logs
[
"2018-02-12T20:20:27.224409701Z stderr: Traceback (most recent call
last):",
"2018-02-12T20:20:27.224534535Z stderr: File \"pythonrunner.py\", line
88, in run",
"2018-02-12T20:20:27.224550304Z stderr: exec('fun = %s(param)' %
self.mainFn, self.global_context)",
"2018-02-12T20:20:27.224559746Z stderr: File \"<string>\", line 1, in
<module>",
"2018-02-12T20:20:27.224578509Z stderr: File \"__main__.py\", line 308,
in main",
"2018-02-12T20:20:27.224587541Z stderr: if
datos_usuario[\"__ow_method\"]
== \"get\":",
"2018-02-12T20:20:27.224596543Z stderr: KeyError: '__ow_method'"
]
The action used to work correctly until now, which makes me think that the error could be related to specific issues accessing the API. Any ideas on how I could get around this issue?
Thanks!
You'll need to create that action as a webaction. The error hints to the fact that __ow_method is not present, which is only present if your action is a webaction.
Does your action do anything with that field? If you want to write your action conditionally (as in: detect if it's actually a webaction) you'll need to check if the field is actually present. In python, you'd use get() to either get the key or None.
In terms of not returning anything meaningful: Seems like your action crashes randomly without doing anything with that error. Potentially the runtime itself could be updated to catch any uncaught errors and return something more meaningful. An issue against the repository might be warranted in that case.

Beaker Cache complains TypeError

Beaker cache complains a TypeError. I've searched on Google, even tracked beaker's issue tracker but couldn't find anything.
I cache the queries like the following method
#staticmethod
def get_queries(query):
#cache.cache(query, type = 'file', expire = 300)
def load(query):
entries = db.get_expensive_query(query)
return entries
return load(query)
However when I run the program, this is what I receive;
File "/Users/ivan/project/controller/caching.py", line 15, in get_queries
return load(query)
File "/Library/Python/2.6/site-packages/Beaker-1.5.4-py2.6.egg/beaker/cache.py", line 417, in cached
return cache[0].get_value(cache_key, createfunc=go)
File "/Library/Python/2.6/site-packages/Beaker-1.5.4-py2.6.egg/beaker/cache.py", line 214, in get
return self._get_value(key, **kw).get_value()
File "/Library/Python/2.6/site-packages/Beaker-1.5.4-py2.6.egg/beaker/container.py", line 256, in get_value
if not self._is_expired(stored, expired):
File "/Library/Python/2.6/site-packages/Beaker-1.5.4-py2.6.egg/beaker/container.py", line 245, in _is_expired
time.time() >= expiretime + storedtime
TypeError: cannot concatenate 'str' and 'float' objects
Am I doing something wrong or is this a beaker's bug?
Your code calls cache.cache with an integer for expire, which is correct, but clearly either expiretime or storedtime is winding up with a string. [From the error message it has to be expiretime. --ed] So here's what I think happened:
(1) You called cache.cache with a string expire at some point. [Maybe even from the default cache.expire in the CacheManager opts, not sure.]
(2) You fixed the bug, producing the code you submitted (which works for me).
(3) You reran the code without deleting the cache directory, and so somehow it picked up the previous state.
I can reproduce your error by following the above prescription. Could you delete your cache (everything in cache.data_dir and cache.lock_dir) and try again?

Error Handling in Python with SUDS

I have been trying to control a camera through a wsdl file using SUDS. I have got the code working but I want to place error handling into the script. I have tried different exceptions but am unable to get the script working. When I enter an invalid coordinate I get an error. The code I am using is below followed by the error I am recieving.
#!/home/build/Python-2.6.4/python
import suds
from suds.client import Client
####################################################################
#
# Python SUDS Script that controls movement of Camera
#
####################################################################
#
# Absolute Move Function
#
####################################################################
def absoluteMove():
# connects to WSDL file and stores location in variable 'client'
client = Client('http://file.wsdl')
# Create 'token' object to pass as an argument using the 'factory' namespace
token = client.factory.create('ns4:ReferenceToken')
print token
# Create 'dest' object to pass as an argument and values passed to this object
dest = client.factory.create('ns4:PTZVector')
dest.PanTilt._x=400
dest.PanTilt._y=0
dest.Zoom._x=1
print dest
# Create 'speed' object to pass as an argument and values passed to this object
speed = client.factory.create('ns4:PTZSpeed')
speed.PanTilt._x=0
speed.PanTilt._y=0
speed.Zoom._x=1
print speed
# 'AbsoluteMove' method invoked passing in the new values entered in the above objects
try:
result = client.service.AbsoluteMove(token, dest, speed)
except RuntimeError as detail:
print 'Handling run-time error:', detail
print "absoluteMove result ", result
result = absoluteMove()
The error is below:
No handlers could be found for logger "suds.client"
Traceback (most recent call last):
File "ptztest.py", line 48, in <module>
if __name__ == '__main__': result = absoluteMove()
File "ptztest.py", line 42, in absoluteMove
result = client.service.AbsoluteMove(token, dest, speed)
File "build/bdist.linux-i686/egg/suds/client.py", line 537, in __call__
File "build/bdist.linux-i686/egg/suds/client.py", line 597, in invoke
File "build/bdist.linux-i686/egg/suds/client.py", line 632, in send
File "build/bdist.linux-i686/egg/suds/client.py", line 683, in failed
File "build/bdist.linux-i686/egg/suds/bindings/binding.py", line 235, in get_fault
suds.WebFault: Server raised fault: 'Error setting requested pan'
I am not sure which exception I should be using here. Does anyone know how to catch this error. The x coordinate with the value 400 is in degree's that is why the error happens.
Thanks
Okay I have found the solution. In SUDS if you enter:
faults=False
into the client definition, this catches faults and gives the reason why the fault happened. The line should read:
client = Client('http://file.wsdl', faults=False)
The post that I have marked as the correct answer also is able to catch that a problem has happened.
Thanks all
If you handled all exceptions and errors in your code and your code is working fine but still you are getting below message with your correct output.
Msg : "No handlers could be found for logger suds.client "
Then a simple solution is to add this line
logging.getLogger('suds.client').setLevel(logging.CRITICAL)
in yourclient.py file just after all import statement.
If you want to catch that exception you should put
try:
result = client.service.AbsoluteMove(token, dest, speed)
except suds.WebFault as detail:
...
You need to catch suds.WebFault by the looks of that traceback. The error itself seems legitimate, IE, your requests are being executed correctly, but perhaps your parameters are wrong in the given context.
I believe you refer to a harmless diagnostic message in your comment. I could suppress messages from suds calling logging.error() by assigning logging.INFO to basicConfig and logging.CRITICAL to suds.client.
https://fedorahosted.org/suds/wiki/Documentation

Categories

Resources