Lambda causing AttributeError - python

I have this piece of code that fetches an id of a sale team if the person is in one, else it returns None.
class AccountInvoice(models.Model):
_inherit = 'account.invoice'
xx_section_id = fields.Many2one('crm.case.section', string='Invoice template', required=True,
default=lambda self: self._get_sales_team())
#api.model
def _get_sales_team(self):
ids = self.env['crm.case.section'].search([('member_ids', 'in', self._uid)])
if len(ids) != 1:
# Has no sales team or more than one
return None
return ids[0]
For some reason this works in my local environment but not on the server. The error occurs when I try to install the module. The server gives me the following error:
AttributeError: 'NoneType' object has no attribute 'id'
And in the logging it states:
2016-12-06 19:39:06,662 2005 ERROR None openerp.http: Exception during JSON request handling.
Traceback (most recent call last):
File "/Users/glenn/Documents/Work/odoo80_vzwwebcrm_tst/openerp/http.py", line 537, in _handle_exception
return super(JsonRequest, self)._handle_exception(exception)
File "/Users/glenn/Documents/Work/odoo80_vzwwebcrm_tst/openerp/http.py", line 1415, in _dispatch_nodb
func, arguments = self.nodb_routing_map.bind_to_environ(request.httprequest.environ).match()
File "/Users/glenn/.virtualenvs/odoo8/lib/python2.7/site-packages/werkzeug/routing.py", line 1430, in match
raise NotFound()
NotFound: 404: Not Found
What am I doing wrong?

For the case len(ids) == 0, the script tries to 'return ids[0]'.
Depending on the result value of 'ids', you condition should be:
if ids:
or
if len(ids) > 0:

Related

Error when create new payment method in Odoo 15

I want to create new method payment but it gives me this error in Odoo V15.
` File
"/cityvape/cityvape-server/addons/account/models/account_payment_method.py",
line 28, in create
if information.get('mode') == 'multi': Exception
The above exception was the direct cause of the following exception:
Traceback (most recent call last): File
"/cityvape/cityvape-server/odoo/http.py", line 643, in
_handle_exception
return super(JsonRequest, self)._handle_exception(exception) File "/cityvape/cityvape-server/odoo/http.py", line 301, in
_handle_exception
raise exception.with_traceback(None) from new_cause AttributeError: 'NoneType' object has no attribute 'get'`
This is the code
#api.model_create_multi
def create(self, vals_list):
payment_methods = super().create(vals_list)
methods_info = self._get_payment_method_information()
for method in payment_methods:
information = methods_info.get(method.code)
if information.get('mode') == 'multi':
method_domain = method._get_payment_method_domain()
journals = self.env['account.journal'].search(method_domain)
self.env['account.payment.method.line'].create([{
'name': method.name,
'payment_method_id': method.id,
'journal_id': journal.id
} for journal in journals])
return payment_methods
I installed third party module but it gave me same error.
information = methods_info.get(method.code) this line has error... It is returning None Value because it seems either methods_info.get(method.code) is returning an empty dictionary or information.get('mode') sometimes returns an empty dictionary.
Use Logger info to trace the value of both or use print function to print the value in terminal to check whether the correct value is passed or not

Well i am facing a 'attribute error: test' while trying to run wolfram alpha in python

When i am executing it the following is showing up
File "C:\users\vasu\anaconda3_\lib\site-packages\wolframalpha__init__.py", line 86, in getattr
val = self[name] if name in self else self[attr_name]
KeyError: '#test'
During handling of above exception, another exception occurred:
Traceback(most recent call last);
File "C:\Users\VASU\anaconda3_\lib\site-packages\wolframalpha__init__.py", line 88, in getattr
raise AttributeError(name)
AttributeError: test
Below is the code I used
import wolframalpha
question = input('Question: ')
app_id = ‘Your app_id’
client = wolframalpha.Client(app_id)
res = client.query(question)
answer = next(res.results).text
print(answer)
I hope You can help me out in this

Python: 'int' object is not iterable in map.Pool

For some reason,
result = pool.map(_delete_load_log,list(logs_to_delete))
is now giving me an 'int' object is not iterable error.
as per the screenshot, logs_to_delete is clearly an array (added list() to see if it changed anything, and nope). This worked earlier, but I can't track back what changed to make it not work. Any ideas?
mapping function:
def _delete_load_log(load_log_id):
logging.debug('** STARTING API CALL FOR: ' + get_function_name())
input_args = "/15/" + str(load_log_id)
logging.debug('url: ' + podium_url + '\nusername: ' + podium_username)
podium = podiumapi.Podium('https://xx/podium','podium','podium')
#podium = podiumapi.Podium(podium_url,podium_username,podium_password)
data = None
response_code = 0
try:
api_url = PodiumApiUrl(podium_url,input_args)
(response_code,data) = podium._podium_curl_setopt_put(api_url)
if not data[0]['hasErrors']:
return data[0]['id']
elif data[0]['hasErrors']:
raise Exception("Errors detected on delete")
else:
raise Exception('Unmanaged exception while retrieving entity load status.')
except Exception as err:
raise Exception(str(err))
File "c:\Repos\Tools\podium-dataload\scripts\podiumlogdelete.py", line 69, in _delete_source_load_logs_gte_epoch
deleted_load_ids = _delete_logs_in_parallel(load_logs_to_delete)
File "c:\Repos\Tools\podium-dataload\scripts\podiumlogdelete.py", line 85, in _delete_logs_in_parallel
result = pool.map(_delete_load_log,logs_to_delete)
File "C:\Python27\lib\multiprocessing\pool.py", line 253, in map
return self.map_async(func, iterable, chunksize).get()
File "C:\Python27\lib\multiprocessing\pool.py", line 572, in get
raise self._value
Exception: 'int' object is not iterable
output of list:
[154840, 154841, 154842, 154843, 154844, 154845, 154846, 154847, 154848, 154849, 154850, 154851, 154852, 154853, 154854, 154855, 154856, 154857, 154858, 154859, 154860, 154861, 154862, 154863, 154864, 154865, 154866, 154867, 154868, 154869, 154870, 154871, 154872, 154873, 154874, 154875, 154876, 154877, 154878, 154879, 154880, 154881, 154882, 154883, 154884, 154885, 154886, 154887, 154888, 154889, 154890, 154891, 154892, 154893, 154894, 154895, 154896, 154897, 154898, 154899, 154900, 154901, 154902, 154903, 154904, 154905, 154906, 154907, 154908, 154909, 154910, 154911, 154912, 154913, 154914, 154915, 154916, 154917, 154918, 154919, 154920, 154921, 154922, 154923, 154924, 154925, 154926, 154927, 154928, 154929, 154930, 154931, 154932, 154933, 154934, 154935, 154936, 154937, 154938, 154939]
Your problem is clear from the traceback. It's not caused by the iterable in Pool.map(), otherwise the exception would be raised from Python source code line
iterable = list(iterable)
Here the exception is raised from
File "C:\Python27\lib\multiprocessing\pool.py", line 253, in map
return self.map_async(func, iterable, chunksize).get()
File "C:\Python27\lib\multiprocessing\pool.py", line 572, in get
raise self._value
This is because your _delete_load_log() raised some exception, and Pool.map re-raise it. See https://github.com/python/cpython/blob/2.7/Lib/multiprocessing/pool.py
In other words, Exception: 'int' object is not iterable is not from the python library part, it's from your own function _delete_load_log().
In all honesty, just take a close look at
#podium = podiumapi.Podium(podium_url,podium_username,podium_password)
data = None
response_code = 0
try:
The response code is equivalent to 0, although the traceback function isn't inputted as "invalid", it makes you have to re-patch a lot afterwards.

Mock gives "raise except" error

I am trying to unit test my program.
I have a side effect in my mock object
from models import MyObject
mock_obj.objects.get.side_effect = mock.Mock(side_effect=MyObject.DoesNotExist)
The test works and passes when I have this in the function that I am testing:
import models
try:
obj = models.MyObject.objects.get(id=1)
except Exception:
return True
However when I change this to:
import models
try:
obj = models.MyObject.objects.get(id=1)
except models.MyObject.DoesNotExist:
return True
It gives me this instead of returning True:
> Traceback (most recent call last):
> File "/home/test/test_my_function.py", line 40, in test_get_job_not_exist
> response = my_function.my_function(request_mock, 1)
> File "/home/handlers/my_function.py", line 35, in get_job_with_id
> obj = MyObject.objects.get(id=id)
> File "/local/lib/python2.7/site-packages/mock/mock.py", line 1062, in __call__
> return _mock_self._mock_call(*args, **kwargs)
> File "/local/lib/python2.7/site-packages/mock/mock.py", line 1118, in _mock_call
> raise effect
> DoesNotExist
Why is this happening? MyObject is a Django model object

Handling exceptions in while loop - Python

Here is my code (almost full version for #cdhowie :)):
def getResult(method, argument=None):
result = None
while True:
print('### loop')
try:
print ('### try hard...')
if argument:
result = method(argument)
else:
result = method()
break
except Exception as e:
print('### GithubException')
if 403 == e.status:
print('Warning: ' + str(e.data))
print('I will try again after 10 minutes...')
else:
raise e
return result
def getUsernames(locations, gh):
usernames = set()
for location in locations:
print location
result = getResult(gh.legacy_search_users, location)
for user in result:
usernames.add(user.login)
print user.login,
return usernames
# "main.py"
gh = Github()
locations = ['Washington', 'Berlin']
# "main.py", line 12 is bellow
usernames = getUsernames(locations, gh)
The problem is, that exception is raised, but I can't handle it. Here is an output:
### loop
### try hard...
Traceback (most recent call last):
File "main.py", line 12, in <module>
usernames = getUsernames(locations, gh)
File "/home/ciembor/projekty/github-rank/functions.py", line 39, in getUsernames
for user in result:
File "/usr/lib/python2.7/site-packages/PyGithub-1.8.0-py2.7.egg/github/PaginatedList.py", line 33, in __iter__
newElements = self.__grow()
File "/usr/lib/python2.7/site-packages/PyGithub-1.8.0-py2.7.egg/github/PaginatedList.py", line 45, in __grow
newElements = self._fetchNextPage()
File "/usr/lib/python2.7/site-packages/PyGithub-1.8.0-py2.7.egg/github/Legacy.py", line 37, in _fetchNextPage
return self.get_page(page)
File "/usr/lib/python2.7/site-packages/PyGithub-1.8.0-py2.7.egg/github/Legacy.py", line 48, in get_page
None
File "/usr/lib/python2.7/site-packages/PyGithub-1.8.0-py2.7.egg/github/Requester.py", line 69, in requestAndCheck
raise GithubException.GithubException(status, output)
github.GithubException.GithubException: 403 {u'message': u'API Rate Limit Exceeded for 11.11.11.11'}
Why it doesn't print ### handling exception?
Take a close look at the stack trace in the exception:
Traceback (most recent call last):
File "main.py", line 12, in <module>
usernames = getUsernames(locations, gh)
File "/home/ciembor/projekty/github-rank/functions.py", line 39, in getUsernames
for user in result:
File "/usr/lib/python2.7/site-packages/PyGithub-1.8.0-py2.7.egg/github/PaginatedList.py", line 33, in __iter__
newElements = self.__grow()
...
The exception is being thrown from code being called by the line for user in result: after getResult finishes executing. This means that the API you're using is using lazy evaluation, so the actual API request doesn't quite happen when you expect it to.
In order to catch and handle this exception, you'll need to wrap the code inside the getUsernames function with a try/except handler.

Categories

Resources