The code below (and linked in full here) is attempting to read from a .csv uploaded to Google Sheets, however I cannot get past the following error:
Traceback (most recent call last):
File "import_report.py", line 211, in <module>
main()
File "import_report.py", line 163, in main
all_trackings.extend(objects_to_sheet.download_from_sheet(from_personal_row, sheet_id, tab_name))
File "C:\Users\xxx\AppData\Local\Programs\Python\Python38\lib\site-packages\tenacity\__init__.py", line 329, in wrapped_f
return self.call(f, *args, **kw)
File "C:\Users\xxx\AppData\Local\Programs\Python\Python38\lib\site-packages\tenacity\__init__.py", line 409, in call
do = self.iter(retry_state=retry_state)
File "C:\Users\xxx\AppData\Local\Programs\Python\Python38\lib\site-packages\tenacity\__init__.py", line 368, in iter
raise retry_exc.reraise()
File "C:\Users\xxx\AppData\Local\Programs\Python\Python38\lib\site-packages\tenacity\__init__.py", line 186, in reraise
raise self.last_attempt.result()
File "C:\Users\xxx\AppData\Local\Programs\Python\Python38\lib\concurrent\futures\_base.py", line 432, in result
return self.__get_result()
File "C:\Users\xxx\AppData\Local\Programs\Python\Python38\lib\concurrent\futures\_base.py", line 388, in __get_result
raise self._exception
File "C:\Users\xxx\AppData\Local\Programs\Python\Python38\lib\site-packages\tenacity\__init__.py", line 412, in call
result = fn(*args, **kwargs)
File "C:\Users\xxx\Documents\GitHub\order-tracking\lib\objects_to_sheet.py", line 26, in download_from_sheet
return [from_row_fn(header, value) for value in values]
File "C:\Users\xxx\Documents\GitHub\order-tracking\lib\objects_to_sheet.py", line 26, in <listcomp>
return [from_row_fn(header, value) for value in values]
TypeError: from_personal_row() takes 1 positional argument but 2 were given
I've read a lot of threads regarding similar errors other posters have encountered, but I can't figure out how to apply the advice here.
Google Sheet CSV:
Code:
def from_personal_row(row: Dict[str, str]) -> Optional[Tracking]:
tracking_col = row['Carrier Name & Tracking Number']
if not tracking_col:
return None
tracking = tracking_col.split('(')[1].replace(')', '')
orders = {row['Order ID'].upper()}
price_str = str(row['Subtotal']).replace(',', '').replace('$', '').replace('N/A', '0.0')
price = float(price_str) if price_str else 0.0
to_email = row['Ordering Customer Email']
ship_date = get_ship_date(str(row["Shipment Date"]))
street_1 = row['Shipping Address Street 1']
city = row['Shipping Address City']
state = row['Shipping Address State']
address = f"{street_1} {city}, {state}"
group, reconcile = get_group(address)
if group is None:
return None
tracked_cost = 0.0
items = price_str
merchant = 'Amazon'
return Tracking(
tracking,
group,
orders,
price,
to_email,
ship_date=ship_date,
tracked_cost=tracked_cost,
items=items,
merchant=merchant,
reconcile=reconcile)
Related
I have 375000 items in my table.
I am doing a loop to obtain all id of all items, with API limit set to 20000 items per api call.
After 200000 I always start to get httpx.ReadTimeout: The read operation timed out sometime it may reach 240000 but never go ahead.
I have tried to have different wait time after each loop.
I have tried to change api limit to 10000 as well as increase it to 30000 or 50000 make less calls but in all cases it get's stuck at around 150000 or 200000.
existing_search_result = supabase.table('vehicles').select('ref_id', count='exact').order('id', desc=False).execute()
existing_items = []
range_step = len(existing_search_result.data)
total_existing_items = existing_search_result.count
print(total_existing_items)
while len(existing_items) < total_existing_items:
try:
existing_items += (
supabase.table(
'vehicles'
).select('ref_id')
.order('id', desc=False)
.range(range_start, range_start + range_step)
.execute()
).data
range_start += range_step
except Exception as e:
logging.exception(e)
print(range_start, len(existing_items))
time.sleep(0.30)
Error log:
2022-10-23 21:04:14,168:ERROR - The read operation timed out
Traceback (most recent call last):
File "/Users/ak4zh/updater/venv/lib/python3.9/site-packages/httpcore/_exceptions.py", line 8, in map_exceptions
yield
File "/Users/ak4zh/updater/venv/lib/python3.9/site-packages/httpcore/backends/sync.py", line 26, in read
return self._sock.recv(max_bytes)
File "/Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.9/lib/python3.9/ssl.py", line 1226, in recv
return self.read(buflen)
File "/Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.9/lib/python3.9/ssl.py", line 1101, in read
return self._sslobj.read(len)
socket.timeout: The read operation timed out
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/Users/ak4zh/updater/venv/lib/python3.9/site-packages/httpx/_transports/default.py", line 60, in map_httpcore_exceptions
yield
File "/Users/ak4zh/updater/venv/lib/python3.9/site-packages/httpx/_transports/default.py", line 204, in handle_request
resp = self._pool.handle_request(req)
File "/Users/ak4zh/updater/venv/lib/python3.9/site-packages/httpcore/_sync/connection_pool.py", line 253, in handle_request
raise exc
File "/Users/ak4zh/updater/venv/lib/python3.9/site-packages/httpcore/_sync/connection_pool.py", line 237, in handle_request
response = connection.handle_request(request)
File "/Users/ak4zh/updater/venv/lib/python3.9/site-packages/httpcore/_sync/connection.py", line 90, in handle_request
return self._connection.handle_request(request)
File "/Users/ak4zh/updater/venv/lib/python3.9/site-packages/httpcore/_sync/http11.py", line 102, in handle_request
raise exc
File "/Users/ak4zh/updater/venv/lib/python3.9/site-packages/httpcore/_sync/http11.py", line 81, in handle_request
) = self._receive_response_headers(**kwargs)
File "/Users/ak4zh/updater/venv/lib/python3.9/site-packages/httpcore/_sync/http11.py", line 143, in _receive_response_headers
event = self._receive_event(timeout=timeout)
File "/Users/ak4zh/updater/venv/lib/python3.9/site-packages/httpcore/_sync/http11.py", line 172, in _receive_event
data = self._network_stream.read(
File "/Users/ak4zh/updater/venv/lib/python3.9/site-packages/httpcore/backends/sync.py", line 26, in read
return self._sock.recv(max_bytes)
File "/Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.9/lib/python3.9/contextlib.py", line 135, in __exit__
self.gen.throw(type, value, traceback)
File "/Users/ak4zh/updater/venv/lib/python3.9/site-packages/httpcore/_exceptions.py", line 12, in map_exceptions
raise to_exc(exc)
httpcore.ReadTimeout: The read operation timed out
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/Users/ak4zh/updater/main.py", line 278, in job
supabase.table(
File "/Users/ak4zh/updater/venv/lib/python3.9/site-packages/postgrest/_sync/request_builder.py", line 53, in execute
r = self.session.request(
File "/Users/ak4zh/updater/venv/lib/python3.9/site-packages/httpx/_client.py", line 802, in request
return self.send(request, auth=auth, follow_redirects=follow_redirects)
File "/Users/ak4zh/updater/venv/lib/python3.9/site-packages/httpx/_client.py", line 889, in send
response = self._send_handling_auth(
File "/Users/ak4zh/updater/venv/lib/python3.9/site-packages/httpx/_client.py", line 917, in _send_handling_auth
response = self._send_handling_redirects(
File "/Users/ak4zh/updater/venv/lib/python3.9/site-packages/httpx/_client.py", line 954, in _send_handling_redirects
response = self._send_single_request(request)
File "/Users/ak4zh/updater/venv/lib/python3.9/site-packages/httpx/_client.py", line 990, in _send_single_request
response = transport.handle_request(request)
File "/Users/ak4zh/updater/venv/lib/python3.9/site-packages/httpx/_transports/default.py", line 204, in handle_request
resp = self._pool.handle_request(req)
File "/Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.9/lib/python3.9/contextlib.py", line 135, in __exit__
self.gen.throw(type, value, traceback)
File "/Users/ak4zh/updater/venv/lib/python3.9/site-packages/httpx/_transports/default.py", line 77, in map_httpcore_exceptions
raise mapped_exc(message) from exc
httpx.ReadTimeout: The read operation timed out
I had the same problem, so I create a function to get 1000 item and merge it!
this is my code:
def count_data(tb_name: str, field_name: str):
return supabase.table(tb_name).select(field_name, count='exact').execute().count
def get_field_data(tb_name: str, src_field: str, len_record: int, id_field: str = 'id'):
if len_record <= 1000:
field_data = supabase.table(tb_name).select(id_field, src_field).order(
column=id_field).execute().data
else:
rnk = int(len_record / 1000)
field_data = []
for i in range(rnk):
min_rg = (i * 1000) + 1
max_rg = (i + 1) * 1000
field_data = field_data + supabase.table(tb_name).select(id_field, src_field).order(
column=id_field).range(min_rg - 1, max_rg).execute().data
field_data = field_data + supabase.table(tb_name).select(id_field, src_field).order(
column=id_field).range(max_rg, len_record).execute().data
return field_data
I'm trying to pass a variable as a keyword argument like this:
#receiver(post_save, sender=BudgetTransaction)
def create_forecasted(sender, instance, created, **kwargs):
if instance.transaction_type == "EC":
return True
if created:
today = instance.next_date
last_day = date(today.year, 12, 31)
this_month = today.month
weeks_left = int((last_day - today).days / 7)
fortnights_left = int(weeks_left / 2)
months_left = 12 - this_month
if instance.frequency == 'weeks':
create_range = weeks_left
elif instance.frequency == 'fort':
create_range = fortnights_left
else:
create_range = months_left
loop = 1
for i in range(create_range):
if instance.frequency == 'fort':
true_frequency = 'weeks'
true_loop = loop * 2
elif instance.frequency == '4week':
true_frequency = 'weeks'
true_loop = loop * 4
else:
true_frequency = instance.frequency
true_loop = loop
### PASSING VARIABLE HERE ###
next_month = today + relativedelta(**{true_frequency: true_loop})
date_string = next_month.strftime("%Y-%m-%d")
BudgetTransaction.objects.bulk_create([BudgetTransaction(
owner=instance.owner,
transaction_amount=instance.transaction_amount,
transaction_name=instance.transaction_name,
transaction_type=instance.transaction_type,
next_date=date_string,
frequency=instance.frequency,
)])
loop += 1
This is for a django site and it doesn't error when I run this through the site. However, when I run a test I'm getting this error:
Error
Traceback (most recent call last):
File "C:\Users\Mitchell\PycharmProjects\BudgieFinance_TW\bf_app\tests\test_models.py", line 26, in test_transaction_has_owner
transaction = TransactionFactory(owner=user)
File "C:\Users\Mitchell\PycharmProjects\BudgieFinance_TW\venv\lib\site-packages\factory\base.py", line 40, in __call__
return cls.create(**kwargs)
File "C:\Users\Mitchell\PycharmProjects\BudgieFinance_TW\venv\lib\site-packages\factory\base.py", line 528, in create
return cls._generate(enums.CREATE_STRATEGY, kwargs)
File "C:\Users\Mitchell\PycharmProjects\BudgieFinance_TW\venv\lib\site-packages\factory\django.py", line 117, in _generate
return super()._generate(strategy, params)
File "C:\Users\Mitchell\PycharmProjects\BudgieFinance_TW\venv\lib\site-packages\factory\base.py", line 465, in _generate
return step.build()
File "C:\Users\Mitchell\PycharmProjects\BudgieFinance_TW\venv\lib\site-packages\factory\builder.py", line 262, in build
instance = self.factory_meta.instantiate(
File "C:\Users\Mitchell\PycharmProjects\BudgieFinance_TW\venv\lib\site-packages\factory\base.py", line 317, in instantiate
return self.factory._create(model, *args, **kwargs)
File "C:\Users\Mitchell\PycharmProjects\BudgieFinance_TW\venv\lib\site-packages\factory\django.py", line 166, in _create
return manager.create(*args, **kwargs)
File "C:\Users\Mitchell\PycharmProjects\BudgieFinance_TW\venv\lib\site-packages\django\db\models\manager.py", line 85, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "C:\Users\Mitchell\PycharmProjects\BudgieFinance_TW\venv\lib\site-packages\django\db\models\query.py", line 514, in create
obj.save(force_insert=True, using=self.db)
File "C:\Users\Mitchell\PycharmProjects\BudgieFinance_TW\venv\lib\site-packages\django\db\models\base.py", line 806, in save
self.save_base(
File "C:\Users\Mitchell\PycharmProjects\BudgieFinance_TW\venv\lib\site-packages\django\db\models\base.py", line 872, in save_base
post_save.send(
File "C:\Users\Mitchell\PycharmProjects\BudgieFinance_TW\venv\lib\site-packages\django\dispatch\dispatcher.py", line 176, in send
return [
File "C:\Users\Mitchell\PycharmProjects\BudgieFinance_TW\venv\lib\site-packages\django\dispatch\dispatcher.py", line 177, in <listcomp>
(receiver, receiver(signal=self, sender=sender, **named))
File "C:\Users\Mitchell\PycharmProjects\BudgieFinance_TW\bf_app\models.py", line 82, in create_forecasted
next_month = next_date + relativedelta(**{true_frequency: true_loop})
TypeError: keywords must be strings
I'm not entirely sure how to solve this as I've never passed a keyword as a variable before so I'm not overly familiar with the process. This is happening on a receiver object.
Thanks
The issue here was that occasionally I was passing None as the variable which was returning the error. In the test I added in a proper string parameter and all was fine!
I am using Django-import-export for importing data but facing an error given below.
i am using django 4.0.6 python 3.10.5 with PostgreSql and most latest version of django import export
Code settings i tried to import data to postgresql database by django-import-export
class MemberResource(resources.ModelResource):
Brand=Field()
class Meta:
model = model
fields=('id','title','Model_code','Chipset','chipset_description','image','Brand','Cat')
export_order=('id','title','Model_code','Chipset','chipset_description','image','Brand','Cat')
def dehydrate_Brand(self, obj):
return str(obj.Brand.title)
class modelAdmin(ImportExportModelAdmin):
resource_class = MemberResource
list_display=['id','title','Model_code','Chipset','chipset_description','Brand','categories']
search_fields = ['title','Model_code','Chipset',]
fields=('title','Model_code','Chipset','chipset_description','image','Brand','Cat')
admin.site.register(model,modelAdmin)
and got below error also attached the image where i exported the data from app and then edited the same and tried to import and stuck with below error.
[Line number: 1 - Field 'id' expected a number but got ''.
2, f9, sd, gf, kjkj, images/sample_3pahsfV.jfif, 1, 1
Traceback (most recent call last):
File "C:\Users\gsminfinity\Desktop\Master\venv\lib\site-packages\django\db\models\fields\related_descriptors.py", line 187, in _get_
rel_obj = self.field.get_cached_value(instance)
File "C:\Users\gsminfinity\Desktop\Master\venv\lib\site-packages\django\db\models\fields\mixins.py", line 15, in get_cached_value
return instance._state.fields_cache\[cache_name\]
KeyError: 'Brand'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "C:\Users\gsminfinity\Desktop\Master\venv\lib\site-packages\django\db\models\fields\_init_.py", line 1988, in get_prep_value
return int(value)
ValueError: invalid literal for int() with base 10: ''
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\gsminfinity\Desktop\Master\venv\lib\site-packages\import_export\resources.py", line 707, in import_row
diff = self.get_diff_class()(self, original, new)
File "C:\Users\gsminfinity\Desktop\Master\venv\lib\site-packages\import_export\resources.py", line 241, in _init_
self.left = self._export_resource_fields(resource, instance)
File "C:\Users\gsminfinity\Desktop\Master\venv\lib\site-packages\import_export\resources.py", line 262, in _export_resource_fields
return \[resource.export_field(f, instance) if instance else "" for f in resource.get_user_visible_fields()\]
File "C:\Users\gsminfinity\Desktop\Master\venv\lib\site-packages\import_export\resources.py", line 262, in <listcomp>
return \[resource.export_field(f, instance) if instance else "" for f in resource.get_user_visible_fields()\]
File "C:\Users\gsminfinity\Desktop\Master\venv\lib\site-packages\import_export\resources.py", line 919, in export_field
return method(obj)
File "C:\Users\gsminfinity\Desktop\Master\admin\firmApp\admin.py", line 20, in dehydrate_Brand
return str(obj.Brand.title)
File "C:\Users\gsminfinity\Desktop\Master\venv\lib\site-packages\django\db\models\fields\related_descriptors.py", line 205, in _get_
rel_obj = self.get_object(instance)
File "C:\Users\gsminfinity\Desktop\Master\venv\lib\site-packages\django\db\models\fields\related_descriptors.py", line 168, in get_object
return qs.get(self.field.get_reverse_related_filter(instance))
File "C:\Users\gsminfinity\Desktop\Master\venv\lib\site-packages\django\db\models\query.py", line 482, in get
clone = self._chain() if self.query.combinator else self.filter(*args, **kwargs)
File "C:\Users\gsminfinity\Desktop\Master\venv\lib\site-packages\django\db\models\query.py", line 1071, in filter
return self._filter_or_exclude(False, args, kwargs)
File "C:\Users\gsminfinity\Desktop\Master\venv\lib\site-packages\django\db\models\query.py", line 1089, in _filter_or_exclude
clone._filter_or_exclude_inplace(negate, args, kwargs)
File "C:\Users\gsminfinity\Desktop\Master\venv\lib\site-packages\django\db\models\query.py", line 1096, in _filter_or_exclude_inplace
self._query.add_q(Q(*args, **kwargs))
File "C:\Users\gsminfinity\Desktop\Master\venv\lib\site-packages\django\db\models\sql\query.py", line 1502, in add_q
clause, _ = self._add_q(q_object, self.used_aliases)
File "C:\Users\gsminfinity\Desktop\Master\venv\lib\site-packages\django\db\models\sql\query.py", line 1532, in _add_q
child_clause, needed_inner = self.build_filter(
File "C:\Users\gsminfinity\Desktop\Master\venv\lib\site-packages\django\db\models\sql\query.py", line 1358, in build_filter
return self._add_q(
File "C:\Users\gsminfinity\Desktop\Master\venv\lib\site-packages\django\db\models\sql\query.py", line 1532, in _add_q
child_clause, needed_inner = self.build_filter(
File "C:\Users\gsminfinity\Desktop\Master\venv\lib\site-packages\django\db\models\sql\query.py", line 1448, in build_filter
condition = self.build_lookup(lookups, col, value)
File "C:\Users\gsminfinity\Desktop\Master\venv\lib\site-packages\django\db\models\sql\query.py", line 1273, in build_lookup
lookup = lookup_class(lhs, rhs)
File "C:\Users\gsminfinity\Desktop\Master\venv\lib\site-packages\django\db\models\lookups.py", line 27, in _init_
self.rhs = self.get_prep_lookup()
File "C:\Users\gsminfinity\Desktop\Master\venv\lib\site-packages\django\db\models\lookups.py", line 85, in get_prep_lookup
return self.lhs.output_field.get_prep_value(self.rhs)
File "C:\Users\gsminfinity\Desktop\Master\venv\lib\site-packages\django\db\models\fields\_init_.py", line 1990, in get_prep_value
raise e._class_(
ValueError: Field 'id' expected a number but got ''.][1]
the issue was dehydrating foreign key gives only read-only data which was for the purpose of export only to import we need to use the widgets which will resolve the foreign keys and import the data to database.
Link to Documentation
class MemberResource(resources.ModelResource):
Brand = fields.Field(
column_name='Brand',
attribute='Brand',
widget=ForeignKeyWidget(brand, 'title'))
class Meta:
model = model
fields=('id','title','Model_code','Chipset','chipset_description','image','Brand','Cat')
That means that there are missing values in the "id" column.
I don't know "Django import / export", sounds very good. An old way of mine with any import/export is to export some sample data and then open it in excel or pandas. Because of the following:
You have all the required columns.
The columns are in the correct order.
And if you have test data you can see the data-types of each column.
Take care using Excel because it changes True into TRUE and generates weird date formats.
Another issue is that after importing django u must also be aware of the last "id" number in order to give the correct AutoIncrement for a new record. That's usually corrected with SQL, but maybe "Django-import-export" corrects this automatically.
I've migrated a module which can create stock.inventory movements, by uploading csv's.
It's functioning quite good, but sometimes, when I upload certain csv's, it throws me this error:
Odoo
Odoo Server Error
Traceback (most recent call last):
File "/usr/lib/python2.7/dist-packages/openerp/http.py", line 648, in _handle_exception
return super(JsonRequest, self)._handle_exception(exception)
File "/usr/lib/python2.7/dist-packages/openerp/http.py", line 685, in dispatch
result = self._call_function(**self.params)
File "/usr/lib/python2.7/dist-packages/openerp/http.py", line 321, in _call_function
return checked_call(self.db, *args, **kwargs)
File "/usr/lib/python2.7/dist-packages/openerp/service/model.py", line 118, in wrapper
return f(dbname, *args, **kwargs)
File "/usr/lib/python2.7/dist-packages/openerp/http.py", line 314, in checked_call
result = self.endpoint(*a, **kw)
File "/usr/lib/python2.7/dist-packages/openerp/http.py", line 964, in __call__
return self.method(*args, **kw)
File "/usr/lib/python2.7/dist-packages/openerp/http.py", line 514, in response_wrap
response = f(*args, **kw)
File "/usr/lib/python2.7/dist-packages/openerp/addons/web/controllers/main.py", line 892, in call_button
action = self._call_kw(model, method, args, {})
File "/usr/lib/python2.7/dist-packages/openerp/addons/web/controllers/main.py", line 880, in _call_kw
return getattr(request.registry.get(model), method)(request.cr, request.uid, *args, **kwargs)
File "/usr/lib/python2.7/dist-packages/openerp/api.py", line 250, in wrapper
return old_api(self, *args, **kwargs)
File "/usr/lib/python2.7/dist-packages/openerp/api.py", line 421, in old_api
result = new_api(recs, *args, **kwargs)
File "/usr/lib/python2.7/dist-packages/openerp/api.py", line 425, in new_api
result = [method(rec, *args, **kwargs) for rec in self]
File "/usr/lib/python2.7/dist-packages/openerp/custom_addons/stock_inventory_import/wizard/import_inventory.py", line 85, in action_import
val['location_id'] = prod_location.id
AttributeError: 'int' object has no attribute 'id'
The code is this:
#api.one
def action_import(self):
"""Load Inventory data from the CSV file."""
ctx = self._context
stloc_obj = self.env['stock.location']
inventory_obj = self.env['stock.inventory']
inv_imporline_obj = self.env['stock.inventory.import.line']
product_obj = self.env['product.product']
if 'active_id' in ctx:
inventory = inventory_obj.browse(ctx['active_id'])
if not self.data:
raise exceptions.Warning(_("You need to select a file!"))
# Decode the file data
data = base64.b64decode(self.data)
file_input = cStringIO.StringIO(data)
file_input.seek(0)
location = self.location
reader_info = []
if self.delimeter:
delimeter = str(self.delimeter)
else:
delimeter = ','
reader = csv.reader(file_input, delimiter=delimeter,
lineterminator='\r\n')
try:
reader_info.extend(reader)
except Exception:
raise exceptions.Warning(_("Not a valid file!"))
keys = reader_info[0]
# check if keys exist
if not isinstance(keys, list) or ('code' not in keys or
'quantity' not in keys):
raise exceptions.Warning(
_("Not 'code' or 'quantity' keys found"))
del reader_info[0]
values = {}
actual_date = fields.Date.today()
inv_name = self.name + ' - ' + actual_date
inventory.write({'name': inv_name,
'date': fields.Datetime.now(),
'imported': True, 'state': 'confirm'})
for i in range(len(reader_info)):
val = {}
field = reader_info[i]
values = dict(zip(keys, field))
prod_location = location.id
if 'location' in values and values['location']:
locat_lst = stloc_obj.search([('name', '=',
values['location'])])
if locat_lst:
prod_location = locat_lst[0]
prod_lst = product_obj.search([('default_code', '=',
values['code'])])
if prod_lst:
val['product'] = prod_lst[0].id
if 'lot' in values and values['lot']:
val['lot'] = values['lot']
val['code'] = values['code']
val['quantity'] = values['quantity']
val['location_id'] = prod_location.id
val['inventory_id'] = inventory.id
val['fail'] = True
val['fail_reason'] = _('No processed')
inv_imporline_obj.create(val)
And the csv's look like this:
id product_id reference code combinacion avanzadastock location quantity qty
2780 Piloto trasero Recambio Ecológico Original M0002780 gsx 600 f 600 1988-1991/4316/A8I 1
This error appears from time to time, often it just works without problems, but some other times throws this error.
It is exactly on location column.
I have csv's with more than 5k items, so it's difficult for me to track the error.
Is this csv related? Or it is a matter of code?
Issue is your logic
prod_location = location.id
Then the following if statement is never entered, and you move to
val['location_id'] = prod_location.id
And the error is thrown
Yes correct. Some location don't exist on the system. That's it throws error. To avoid such error, you can use following trick.
prod_location = self.location and self.location.id or False
Means if system has location then prod_location variable set value with id of location otherwise False
NOTE:
In model declaration, location_id field set with required=False otherwise you can not create record with location_id=False It will give you integrity error.
Actually the problem was the csv content
Because some locations don't exist on the system, then it throws out that error.
So, need to check for locations that do exist before continuing with the process.
Thank You.
I have problrem with my code.
class SiteTrip(models.Model):
_name = 'vips_vc.site_trip'
name = fields.Char()
session_ids = fields.One2many('vips_vc.session', 'site_trip_id', string='Session ID', index=True)
url_prevouse_ids = fields.Many2one('vips_vc.url_list', string='Prevouse URL', index=True)
url_current_ids = fields.Many2one('vips_vc.url_list', string='Current URL', index=True)
class URLList(models.Model):
_name = 'vips_vc.url_list'
name = fields.Char(string="URL", required=True)
url_parametes = fields.Char(string="URL parameters")
target_session_id = fields.One2many('vips_vc.session', 'target_url_ids', string='Target URL')
site_trip_prevouse_id = fields.One2many('vips_vc.site_trip', 'url_prevouse_ids', string='Prevouse URL')
site_trip_current_id = fields.One2many('vips_vc.site_trip', 'url_current_ids', string='Current URL')
remote_sites_id = fields.One2many('vips_vc.remote_sites', 'site_url_ids', string='Remote site page with URL')
remote_sites_target_url_id = fields.One2many('vips_vc.remote_sites', 'target_url_ids', string='URL on remote site page')
My controller:
def register_trip(self, currentURLid, prevouseURLid, sessionID):
currentURLid = int(currentURLid)
prevouseURLid = int(prevouseURLid)
result = None
### something
_logger.info("CREATE -----> session_ids: %r url_prevouse_ids: %r url_current_ids: %r",
sessionID, prevouseURLid, currentURLid)
result = table.create({'session_ids': sessionID, 'url_prevouse_ids': prevouseURLid,
'url_current_ids': currentURLid})
### something
return result.id
And error is:
2016-08-04 17:20:52,931 24261 INFO odoov8 openerp.addons.vips_vc.controllers: CREATE -----> session_ids: 59 url_prevouse_ids: 8 url_current_ids: 1
2016-08-04 17:20:52,938 24261 ERROR odoov8 openerp.http: Exception during JSON request handling.
Traceback (most recent call last):
File "/home/skif/odoo/openerp/http.py", line 540, in _handle_exception
return super(JsonRequest, self)._handle_exception(exception)
File "/home/skif/odoo/openerp/http.py", line 577, in dispatch
result = self._call_function(**self.params)
File "/home/skif/odoo/openerp/http.py", line 313, in _call_function
return checked_call(self.db, *args, **kwargs)
File "/home/skif/odoo/openerp/service/model.py", line 118, in wrapper
return f(dbname, *args, **kwargs)
File "/home/skif/odoo/openerp/http.py", line 310, in checked_call
return self.endpoint(*a, **kw)
File "/home/skif/odoo/openerp/http.py", line 806, in __call__
return self.method(*args, **kw)
File "/home/skif/odoo/openerp/http.py", line 406, in response_wrap
response = f(*args, **kw)
File "/home/skif/odoo/my-modules/vips_vc/controllers.py", line 194, in register_session
self.register_trip(currentURLid, prevouseURLid, sessionID)
File "/home/skif/odoo/my-modules/vips_vc/controllers.py", line 375, in register_trip
'url_current_ids': currentURLid})
File "/home/skif/odoo/openerp/api.py", line 266, in wrapper
return new_api(self, *args, **kwargs)
File "/home/skif/odoo/openerp/models.py", line 4094, in create
record = self.browse(self._create(old_vals))
File "/home/skif/odoo/openerp/api.py", line 266, in wrapper
return new_api(self, *args, **kwargs)
File "/home/skif/odoo/openerp/api.py", line 508, in new_api
result = method(self._model, cr, uid, *args, **old_kwargs)
File "/home/skif/odoo/openerp/models.py", line 4279, in _create
result += self._columns[field].set(cr, self, id_new, field, vals[field], user, rel_context) or []
File "/home/skif/odoo/openerp/osv/fields.py", line 795, in set
for act in values:
TypeError: 'int' object is not iterable
As you see when I'm trying to add record in vips_vc.site_trip i receive error. And error only for currentURLid. It has integer value. prevouseURLid has integer value too. prevouseURLid and currentURLid have similar relation One2Many/Many2One.
prevouseURLid is working. currentURLid isn't.
In this line I checked all param(logger output):
2016-08-04 17:20:52,931 24261 INFO odoov8 openerp.addons.vips_vc.controllers: CREATE -----> session_ids: 59 url_prevouse_ids: 8 url_current_ids: 1
url_prevouse_ids and url_current_ids have type is integer. They have defined value. They have similar relation. And insert url_current_ids return error.
Why is it happening?
Tomorrow all worked fine !
I did not touch relation. I did not touch type of variables...
UPD: After all manipulation I have this: If i'm trying to create record with any param (sessionID, prevouseURLid, currentURLid) I receiving same error: TypeError: 'int' object is not iterable
I found error.
I don't know how it working early...
result = table.create({'session_ids': sessionID, 'url_prevouse_ids': prevouseURLid,
'url_current_ids': currentURLid})
Here present ID record from other tables(models). When I removed all data (module was remove and install again).
After that step by step i check all data what received variables and stored in DB. I founded that vips_vc.url_list and vips_vc.session had not data.
after that i placed such code after create all records:
_logger.info(".....> Commit record ID %r", result.id)
table.env.cr.commit()
I have no idea why it code work early without commit().