My schedule action does not work Odoo 13 why? - cron
I don't understand :
scheduler_demo/data/sheduler_data.xml :
<?xml version="1.0" encoding="UTF-8" ?>
<odoo>
<data noupdate="1">
<record id="ir_cron_scheduler_demo_action" model="ir.cron">
<field name="name">Demo scheduler</field>
<field name="model_id" ref="model_scheduler_demo"></field>
<field name="state">code</field>
<field name="code">model.process_demo_scheduler_queue()</field>
<field name="active" eval="True"></field>
<field name="user_id" ref="base.user_root"></field>
<field name="interval_number">1</field>
<field name="interval_type">days</field>
<field name="numbercall">-1</field>
</record>
</data>
</odoo>
scheduler_demo/models/init.py :
from . import scheduler_demo
scheduler_demo/models/sheduler_demo.py :
# -*- coding: utf-8 -*-
from odoo import models, fields, api
class SchedulerDemo(models.Model):
_name = 'scheduler.demo'
name = fields.Char(required=True)
number_of_updates = fields.Integer('Number of updates')
#api.model
def _process_demo_scheduler_queue(self):
# Contains all records for the model scheduler.demo
scheduler_demo_records = self.env['scheduler.demo'].search([])
# Loop over the records one by one
for demo_record in scheduler_demo_records:
number_of_updates = demo_record.number_of_updates + 1
# Update the record with the new number of updates
demo_record.write({
'number_of_updates': number_of_updates
})
scheduler_demo/security/ir.model.access.csv :
id,name,model_id:id,group_id:id,perm_read,perm_write,perm_create,perm_unlink
access_scheduler_demo,access_scheduler_demo,model_scheduler_demo,base.group_user,1,1,1,1
scheduler_demo/views/menu.xml :
<?xml version="1.0" encoding="UTF-8" ?>
<odoo>
<menuitem id="scheduler_demo_menu_root"
name="Scheduler tutorial"
sequence="98"></menuitem>
<menuitem id="menu_scheduler_demo"
name="Scheduler records"
parent="scheduler_demo_menu_root"
action="action_scheduler_demo_records"
sequence="1"></menuitem>
<record id="action_scheduler_demo_records" model="ir.actions.act_window">
<field name="name">Scheduler records</field>
<field name="type">ir.actions.act_window</field>
<field name="res_model">scheduler.demo</field>
<field name="search_view_id" ref="scheduler_demo_search_view"></field>
<field name="view_mode">tree,form</field>
<field name="help" type="html">
<p class="o_view_nocontent_smiling_face">
Create a new scheduler record by clicking on 'Create'.
</p>
</field>
</record>
</odoo>
scheduler_demo/scheduler_demo.xml :
<?xml version="1.0" encoding="UTF-8" ?>
<odoo>
<record id="scheduler_demo_tree_view" model="ir.ui.view">
<field name="name">scheduler.demo.tree</field>
<field name="model">scheduler.demo</field>
<field name="arch" type="xml">
<tree string="Scheduler records">
<field name="name"></field>
<field name="number_of_updates"></field>
</tree>
</field>
</record>
<record id="scheduler_demo_form_view" model="ir.ui.view">
<field name="name">scheduler.demo.form</field>
<field name="model">scheduler.demo</field>
<field name="arch" type="xml">
<form string="Scheduler record">
<sheet>
<group name="main_info">
<field name="name"></field>
<field name="number_of_updates"></field>
<field name="write_date"></field>
</group>
</sheet>
</form>
</field>
</record>
<record id="scheduler_demo_search_view" model="ir.ui.view">
<field name="name">scheduler.demo.search</field>
<field name="model">scheduler.demo</field>
<field name="arch" type="xml">
<search string="Scheduler records">
<field name="name"></field>
<field name="number_of_updates"></field>
</search>
</field>
</record>
</odoo>
scheduler_demo/__init__py :
from . import models
scheduler_demo/manifest.py :
{
'name': "scheduler_demo",
'depends': ['base', 'web'],
'data': [
'security/ir.model.access.csv',
'data/scheduler_data.xml',
'views/scheduler_demo.xml',
'views/menu.xml',
],
'installable': True,
'application': False,
'auto_install': False,
}
ERROR :
Odoo server error
psycopg2.IntegrityError: ERREUR: une valeur NULL viole la contrainte NOT NULL de la colonne « activity_user_type »
DETAIL: La ligne en échec contient (586, Demo scheduler, ir.actions.server, null, null, action, list,form, 1, 2020-09-25 13:32:44.223276, 1, 2020-09-25 13:32:44.223276, ir_cron, code, 5, 394, null, model.process_demo_scheduler_queue(), null, null, null, null, null, null, null, null, null, null, null, null, null, null, null)
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/opt/odoo/odoo/http.py", line 624, in _handle_exception
return super(JsonRequest, self)._handle_exception(exception)
File "/opt/odoo/odoo/http.py", line 310, in _handle_exception
raise pycompat.reraise(type(exception), exception, sys.exc_info()[2])
File "/opt/odoo/odoo/tools/pycompat.py", line 14, in reraise
raise value
File "/opt/odoo/odoo/http.py", line 669, in dispatch
result = self._call_function(**self.params)
File "/opt/odoo/odoo/http.py", line 350, in _call_function
return checked_call(self.db, *args, **kwargs)
File "/opt/odoo/odoo/service/model.py", line 94, in wrapper
return f(dbname, *args, **kwargs)
File "/opt/odoo/odoo/http.py", line 339, in checked_call
result = self.endpoint(*a, **kw)
File "/opt/odoo/odoo/http.py", line 915, in __call__
return self.method(*args, **kw)
File "/opt/odoo/odoo/http.py", line 515, in response_wrap
response = f(*args, **kw)
File "/opt/odoo/addons/web/controllers/main.py", line 1326, in call_button
action = self._call_kw(model, method, args, kwargs)
File "/opt/odoo/addons/web/controllers/main.py", line 1314, in _call_kw
return call_kw(request.env[model], method, args, kwargs)
File "/opt/odoo/odoo/api.py", line 387, in call_kw
result = _call_kw_multi(method, model, args, kwargs)
File "/opt/odoo/odoo/api.py", line 374, in _call_kw_multi
result = method(recs, *args, **kwargs)
File "<decorator-gen-65>", line 2, in button_immediate_upgrade
File "/opt/odoo/odoo/addons/base/models/ir_module.py", line 72, in check_and_log
return method(self, *args, **kwargs)
File "/opt/odoo/odoo/addons/base/models/ir_module.py", line 634, in button_immediate_upgrade
return self._button_immediate_function(type(self).button_upgrade)
File "/opt/odoo/odoo/addons/base/models/ir_module.py", line 573, in _button_immediate_function
modules.registry.Registry.new(self._cr.dbname, update_module=True)
File "/opt/odoo/odoo/modules/registry.py", line 86, in new
odoo.modules.load_modules(registry._db, force_demo, status, update_module)
File "/opt/odoo/odoo/modules/loading.py", line 419, in load_modules
force, status, report, loaded_modules, update_module, models_to_check)
File "/opt/odoo/odoo/modules/loading.py", line 315, in load_marked_modules
perform_checks=perform_checks, models_to_check=models_to_check
File "/opt/odoo/odoo/modules/loading.py", line 225, in load_module_graph
load_data(cr, idref, mode, kind='data', package=package, report=report)
File "/opt/odoo/odoo/modules/loading.py", line 68, in load_data
tools.convert_file(cr, package.name, filename, idref, mode, noupdate, kind, report)
File "/opt/odoo/odoo/tools/convert.py", line 736, in convert_file
convert_xml_import(cr, module, fp, idref, mode, noupdate, report)
File "/opt/odoo/odoo/tools/convert.py", line 803, in convert_xml_import
obj.parse(doc.getroot())
File "/opt/odoo/odoo/tools/convert.py", line 721, in parse
exc_info[2]
File "/opt/odoo/odoo/tools/pycompat.py", line 13, in reraise
raise value.with_traceback(tb)
File "/opt/odoo/odoo/tools/convert.py", line 712, in parse
self._tag_root(de)
File "/opt/odoo/odoo/tools/convert.py", line 674, in _tag_root
f(rec)
File "/opt/odoo/odoo/tools/convert.py", line 674, in _tag_root
f(rec)
File "/opt/odoo/odoo/tools/convert.py", line 577, in _tag_record
record = model._load_records([data], self.mode == 'update')
File "/opt/odoo/odoo/models.py", line 4084, in _load_records
records = self._load_records_create([data['values'] for data in to_create])
File "/opt/odoo/odoo/models.py", line 3998, in _load_records_create
return self.create(values)
File "<decorator-gen-40>", line 2, in create
File "/opt/odoo/odoo/api.py", line 317, in _model_create_single
return self.browse().concat(*(create(self, vals) for vals in arg))
File "/opt/odoo/odoo/api.py", line 317, in <genexpr>
return self.browse().concat(*(create(self, vals) for vals in arg))
File "/opt/odoo/odoo/addons/base/models/ir_cron.py", line 71, in create
return super(ir_cron, self).create(values)
File "<decorator-gen-3>", line 2, in create
File "/opt/odoo/odoo/api.py", line 335, in _model_create_multi
return create(self, [arg])
File "/opt/odoo/odoo/models.py", line 3740, in create
for data in parent_data_list
File "<decorator-gen-34>", line 2, in create
File "/opt/odoo/odoo/api.py", line 336, in _model_create_multi
return create(self, arg)
File "/opt/odoo/odoo/addons/base/models/ir_actions.py", line 59, in create
res = super(IrActions, self).create(vals_list)
File "<decorator-gen-3>", line 2, in create
File "/opt/odoo/odoo/api.py", line 336, in _model_create_multi
return create(self, arg)
File "/opt/odoo/odoo/models.py", line 3746, in create
records = self._create(data_list)
File "/opt/odoo/odoo/models.py", line 3832, in _create
cr.execute(query, params)
File "/opt/odoo/odoo/sql_db.py", line 168, in wrapper
return f(self, *args, **kwargs)
File "/opt/odoo/odoo/sql_db.py", line 245, in execute
res = self._obj.execute(query, params)
odoo.tools.convert.ParseError: "ERREUR: une valeur NULL viole la contrainte NOT NULL de la colonne « activity_user_type »
DETAIL: La ligne en échec contient (586, Demo scheduler, ir.actions.server, null, null, action, list,form, 1, 2020-09-25 13:32:44.223276, 1, 2020-09-25 13:32:44.223276, ir_cron, code, 5, 394, null, model.process_demo_scheduler_queue(), null, null, null, null, null, null, null, null, null, null, null, null, null, null, null)
" while parsing /home/brenda/Code/app_odoo/scheduler_demo/data/scheduler_data.xml:2, near
<odoo>
<data noupdate="1">
<record id="ir_cron_scheduler_demo_action" model="ir.cron">
<field name="name">Demo scheduler</field>
<field name="model_id" ref="model_scheduler_demo"/>
<field name="state">code</field>
<field name="code">model.process_demo_scheduler_queue()</field>
<field name="active" eval="True"/>
<field name="user_id" ref="base.user_root"/>
<field name="interval_number">1</field>
<field name="interval_type">days</field>
<field name="numbercall">-1</field>
</record>
</data>
</odoo>
I do not understand the error, I tested a lot of modification without success, could someone help me please.
Odoo defines ir_actions_server_id field (in ir.crom model) and set delegate attribute to True (corresponds to _inherits) which means that ir.actions.server fields are available in the ir.cron model.
The activity_user_type field is defined in mail (add it to module dependency) module as required field set by default to specific, so you can't have the above error using the default implementation.
You can reproduce a similar error by inheriting the ir.actions.server model and altering the default attribute (set it to False) of a required field.
The folowing code will raise an odoo.tools.convert.ParseError
class IrActionsServer(models.Model):
_inherit = 'ir.actions.server'
usage = fields.Selection(default=False)
It could also be the result of overriding the create method and setting the value of activity_user_type to another field value which is finally evaluated to False.
Related
How to resolve the 'can't pickle lxml.etree.QName objects ' when using zeep library with python for a SOAP API request?
I am trying to post a SOAP API request using zeep library + python. But it fails with some error. The SOAP request looks like this. <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:att="http://www.front.com/front/attributes" xmlns:web="http://webservices.front.trapedza.com"> <soapenv:Header> <web:soapheader> <!--Optional:--> <web:authentication> <web:userName>user1</web:userName> <web:password>password1</web:password> <!--Optional:--> <web:RestUrl></web:RestUrl> </web:authentication> <web:SHeader> <!--Optional:--> <att:correlationID></att:correlationID> <!--Optional:--> <att:zone>SAFE</att:zone> <att:autoAuthorize></att:autoAuthorize> </web:SHeader> </web:soapheader> </soapenv:Header> <soapenv:Body> <web:USERDETAILS_SRV> <web:requestPayload> <!--Optional:--> <generalParam>'UNIQUEID=TID123; FIRSTNAME= JOHNNY; LASTNAME= DEP' </generalParam> <!--Optional:--> <configParam>CHECK_REQD=N;ACTION=A</configParam> </web:requestPayload> </web:USERDETAILS_SRV> </soapenv:Body> </soapenv:Envelope> The code that I written for the sending the request is : from zeep import Client,Settings from zeep import xsd def callMethod(): url="http://10.111.3.112:8080/services/USERDETAILS_SRVWS?wsdl" settings = Settings(strict=False, xml_huge_tree=True) client = Client(url, settings=settings) header = zeep.xsd.Element( 'soapheader', zeep.xsd.ComplexType([ zeep.xsd.Element( 'authentication', zeep.xsd.ComplexType([ zeep.xsd.Element('userName',zeep.xsd.String()), zeep.xsd.Element('password',zeep.xsd.String()) ]) ), zeep.xsd.Element( 'SHeader', zeep.xsd.ComplexType([ zeep.xsd.Element('zone',zeep.xsd.String()) ]) ) ]) ) header_value = header(authentication={'userName':'user1','password':'password1'},SHeader={'zone': 'SAFE'}) request ={'generalParam': 'UNIQUEID=TID123; FIRSTNAME= JOHNNY; LASTNAME= DEP'},{'configParam': 'CHECK_REQD=N;ACTION=A'} with client.settings(raw_response=True): client.set_default_soapheaders(header) res = client.service.USERDETAILS_SRV(requestData) print(res) callMethod() On executing the above code it gives me the below error. res = client.service.USERDETAILS_SRV(requestData) File "C:\Python3\lib\site-packages\zeep\proxy.py", line 45, in __call__ kwargs, File "C:\Python3\lib\site-packages\zeep\wsdl\bindings\soap.py", line 119, in send operation, args, kwargs, client=client, options=options File "C:\Python3\lib\site-packages\zeep\wsdl\bindings\soap.py", line 68, in _create serialized = operation_obj.create(*args, **kwargs) File "C:\Python3\lib\site-packages\zeep\wsdl\definitions.py", line 215, in create return self.input.serialize(*args, **kwargs) File "C:\Python3\lib\site-packages\zeep\wsdl\messages\soap.py", line 59, in serialize header = self._serialize_header(headers_value, nsmap) File "C:\Python3\lib\site-packages\zeep\wsdl\messages\soap.py", line 326, in _serialize_header headers_value = copy.deepcopy(headers_value) File "C:\Python3\lib\copy.py", line 180, in deepcopy y = _reconstruct(x, memo, *rv) File "C:\Python3\lib\copy.py", line 280, in _reconstruct state = deepcopy(state, memo) File "C:\Python3\lib\copy.py", line 150, in deepcopy y = copier(x, memo) File "C:\Python3\lib\copy.py", line 240, in _deepcopy_dict y[deepcopy(key, memo)] = deepcopy(value, memo) File "C:\Python3\lib\copy.py", line 169, in deepcopy rv = reductor(4) TypeError: can't pickle lxml.etree.QName objects I believe the code isn't correct. Please help me in fixing the code, and to add the header along with request so that I get a response for the same.
TypeError: _bulk_create() got an unexpected keyword argument 'ignore_conflicts'
While adding groups with permission from Django Admin Panel and adding other M2M relationships too. I got this error!! It says : TypeError: _bulk_create() got an unexpected keyword argument 'ignore_conflicts' I can't find the error, Probably a noob mistake. class GroupSerializer(serializers.ModelSerializer): permissions = PermissionSerializerGroup(many=True, required=False) class Meta: model = Group fields = ('id', 'name', 'permissions') extra_kwargs = { 'name': {'validators': []}, } def create(self, validated_data): print(validated_data) permissions_data = validated_data.pop("permissions") obj, group = Group.objects.update_or_create(name=validated_data["name"]) obj.permissions.clear() for permission in permissions_data: per = Permission.objects.get(codename=permission["codename"]) obj.permissions.add(per) obj.save() return obj Here is the Traceback: File "/home/suman/Desktop/suman1234/myvenv/lib/python3.6/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/home/suman/Desktop/suman1234/myvenv/lib/python3.6/site-packages/django/core/handlers/base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "/home/suman/Desktop/suman1234/myvenv/lib/python3.6/site-packages/django/core/handlers/base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/suman/Desktop/suman1234/myvenv/lib/python3.6/site-packages/django/contrib/admin/options.py", line 607, in wrapper return self.admin_site.admin_view(view)(*args, **kwargs) File "/home/suman/Desktop/suman1234/myvenv/lib/python3.6/site-packages/django/utils/decorators.py", line 130, in _wrapped_view response = view_func(request, *args, **kwargs) File "/home/suman/Desktop/suman1234/myvenv/lib/python3.6/site-packages/django/views/decorators/cache.py", line 44, in _wrapped_view_func response = view_func(request, *args, **kwargs) File "/home/suman/Desktop/suman1234/myvenv/lib/python3.6/site-packages/django/contrib/admin/sites.py", line 231, in inner return view(request, *args, **kwargs) File "/home/suman/Desktop/suman1234/myvenv/lib/python3.6/site-packages/django/contrib/admin/options.py", line 1638, in add_view return self.changeform_view(request, None, form_url, extra_context) File "/home/suman/Desktop/suman1234/myvenv/lib/python3.6/site-packages/django/utils/decorators.py", line 43, in _wrapper return bound_method(*args, **kwargs) File "/home/suman/Desktop/suman1234/myvenv/lib/python3.6/site-packages/django/utils/decorators.py", line 130, in _wrapped_view response = view_func(request, *args, **kwargs) File "/home/suman/Desktop/suman1234/myvenv/lib/python3.6/site-packages/django/contrib/admin/options.py", line 1522, in changeform_view return self._changeform_view(request, object_id, form_url, extra_context) File "/home/suman/Desktop/suman1234/myvenv/lib/python3.6/site-packages/django/contrib/admin/options.py", line 1566, in _changeform_view self.save_related(request, form, formsets, not add) File "/home/suman/Desktop/suman1234/myvenv/lib/python3.6/site-packages/django/contrib/admin/options.py", line 1107, in save_related form.save_m2m() File "/home/suman/Desktop/suman1234/myvenv/lib/python3.6/site-packages/django/forms/models.py", line 442, in _save_m2m f.save_form_data(self.instance, cleaned_data[f.name]) File "/home/suman/Desktop/suman1234/myvenv/lib/python3.6/site-packages/django/db/models/fields/related.py", line 1618, in save_form_data getattr(instance, self.attname).set(data) File "/home/suman/Desktop/suman1234/myvenv/lib/python3.6/site-packages/django/db/models/fields/related_descriptors.py", line 1008, in set self.add(*new_objs, through_defaults=through_defaults) File "/home/suman/Desktop/suman1234/myvenv/lib/python3.6/site-packages/django/db/models/fields/related_descriptors.py", line 946, in add through_defaults=through_defaults, File "/home/suman/Desktop/suman1234/myvenv/lib/python3.6/site-packages/django/db/models/fields/related_descriptors.py", line 1129, in _add_items ], ignore_conflicts=True) TypeError: _bulk_create() got an unexpected keyword argument 'ignore_conflicts'
I solved this issue by downgrading Django version to 2.2.12 It seems that Django v3.0+ has this issue
This has been fixed in github: https://github.com/martinphellwig/django-query-signals/commit/a3ed59614287f1ef9e7398d325a8bbcc11bf0b3c but it's not in pypi, you need to install django-query-signals from git
flask_restful - TypeError: Object of type Record is not JSON serializable
I try to provide a custom object inside a rest api, created with flask_restful. Object: Record import json class Record(): #CLASS RECORD def __init__(self, DateTime, DateTimeText, Status, Icon, Temp): #INITIALIZE self.DateTime = DateTime self.DateTimeText = DateTimeText self.Status = Status self.Icon = Icon self.Temp = Temp def __repr__(self): return json.dumps(self, default=lambda o: o.__dict__, sort_keys=False, indent=4) Result: print(record) { "DateTime": 1583949600, "DateTimeText": "2020-03-11 18:00:00", "Status": "Clouds", "Icon": "04n", "Temp": 280.57 } Rest API: from flask_restful import Resource, Api, reqparse class _Weather(Resource): #WEATHER def get(self): #GET WEATHER return {'value': Weather.Record} self.Api.add_resource(_Weather, '/api/weather') Error: all other calls works fine, only me custom object (http://localhost:80/api/weather) returns the following error stack: File "C:\Users\Martin\AppData\Local\Programs\Python\Python38-32\Lib\site-packages\flask\app.py", line 2463, in __call__ return self.wsgi_app(environ, start_response) File "C:\Users\Martin\AppData\Local\Programs\Python\Python38-32\Lib\site-packages\flask\app.py", line 2449, in wsgi_app response = self.handle_exception(e) File "C:\Users\Martin\AppData\Local\Programs\Python\Python38-32\Lib\site-packages\flask_restful\__init__.py", line 272, in error_router return original_handler(e) File "C:\Users\Martin\AppData\Local\Programs\Python\Python38-32\Lib\site-packages\flask_cors\extension.py", line 161, in wrapped_function return cors_after_request(app.make_response(f(*args, **kwargs))) File "C:\Users\Martin\AppData\Local\Programs\Python\Python38-32\Lib\site-packages\flask\app.py", line 1866, in handle_exception reraise(exc_type, exc_value, tb) File "C:\Users\Martin\AppData\Local\Programs\Python\Python38-32\Lib\site-packages\flask\_compat.py", line 38, in reraise raise value.with_traceback(tb) File "C:\Users\Martin\AppData\Local\Programs\Python\Python38-32\Lib\site-packages\flask\app.py", line 2446, in wsgi_app response = self.full_dispatch_request() File "C:\Users\Martin\AppData\Local\Programs\Python\Python38-32\Lib\site-packages\flask\app.py", line 1951, in full_dispatch_request rv = self.handle_user_exception(e) File "C:\Users\Martin\AppData\Local\Programs\Python\Python38-32\Lib\site-packages\flask_restful\__init__.py", line 272, in error_router return original_handler(e) File "C:\Users\Martin\AppData\Local\Programs\Python\Python38-32\Lib\site-packages\flask_cors\extension.py", line 161, in wrapped_function return cors_after_request(app.make_response(f(*args, **kwargs))) File "C:\Users\Martin\AppData\Local\Programs\Python\Python38-32\Lib\site-packages\flask\app.py", line 1820, in handle_user_exception reraise(exc_type, exc_value, tb) File "C:\Users\Martin\AppData\Local\Programs\Python\Python38-32\Lib\site-packages\flask\_compat.py", line 38, in reraise raise value.with_traceback(tb) File "C:\Users\Martin\AppData\Local\Programs\Python\Python38-32\Lib\site-packages\flask\app.py", line 1949, in full_dispatch_request rv = self.dispatch_request() File "C:\Users\Martin\AppData\Local\Programs\Python\Python38-32\Lib\site-packages\flask\app.py", line 1935, in dispatch_request return self.view_functions[rule.endpoint](**req.view_args) File "C:\Users\Martin\AppData\Local\Programs\Python\Python38-32\Lib\site-packages\flask_restful\__init__.py", line 472, in wrapper return self.make_response(data, code, headers=headers) File "C:\Users\Martin\AppData\Local\Programs\Python\Python38-32\Lib\site-packages\flask_restful\__init__.py", line 501, in make_response resp = self.representations[mediatype](data, *args, **kwargs) File "C:\Users\Martin\AppData\Local\Programs\Python\Python38-32\Lib\site-packages\flask_restful\representations\json.py", line 21, in output_json dumped = dumps(data, **settings) + "\n" File "C:\Users\Martin\AppData\Local\Programs\Python\Python38-32\Lib\json\__init__.py", line 234, in dumps return cls( File "C:\Users\Martin\AppData\Local\Programs\Python\Python38-32\Lib\json\encoder.py", line 201, in encode chunks = list(chunks) File "C:\Users\Martin\AppData\Local\Programs\Python\Python38-32\Lib\json\encoder.py", line 431, in _iterencode yield from _iterencode_dict(o, _current_indent_level) File "C:\Users\Martin\AppData\Local\Programs\Python\Python38-32\Lib\json\encoder.py", line 405, in _iterencode_dict yield from chunks File "C:\Users\Martin\AppData\Local\Programs\Python\Python38-32\Lib\json\encoder.py", line 438, in _iterencode o = _default(o) File "C:\Users\Martin\AppData\Local\Programs\Python\Python38-32\Lib\json\encoder.py", line 179, in default raise TypeError(f'Object of type {o.__class__.__name__} ' TypeError: Object of type Record is not JSON serializable I try a lot of different approaches, found here on stack. Non of these works for my. Python 3.8.2
You have a couple of options here. Make a tojson() method for your Record class and call that for your return value. It will basically just return the underlying __dict__ for your object. def tojson(self): return self.__dict__ Pass Weather.Record.__dict__ directly as your return value So your return statement will look like one of these: return {'value': Weather.Record.__dict__} Or, using jsonify from Flask: return jsonify({'value': 'Weather.Record.__dict__}) Or replace Weather.Record.__dict__ with Weather.Record.tojson() if you add that method to the class.
connection error when a URL is down
Traceback (most recent call last): File "C:\Users\SD37561\AppData\Local\Continuum\Anaconda3\lib\site-packages\requests\packages\urllib3\connectionpool.py", line 544, in urlopen body=body, headers=headers) File "C:\Users\SD37561\AppData\Local\Continuum\Anaconda3\lib\site-packages\requests\packages\urllib3\connectionpool.py", line 349, in _make_request conn.request(method, url, **httplib_request_kw) File "C:\Users\SD37561\AppData\Local\Continuum\Anaconda3\lib\http\client.py", line 1088, in request self._send_request(method, url, body, headers) File "C:\Users\SD37561\AppData\Local\Continuum\Anaconda3\lib\http\client.py", line 1126, in _send_request self.endheaders(body) File "C:\Users\SD37561\AppData\Local\Continuum\Anaconda3\lib\http\client.py", line 1084, in endheaders self._send_output(message_body) File "C:\Users\SD37561\AppData\Local\Continuum\Anaconda3\lib\http\client.py", line 922, in _send_output self.send(msg) File "C:\Users\SD37561\AppData\Local\Continuum\Anaconda3\lib\http\client.py", line 857, in send self.connect() File "C:\Users\SD37561\AppData\Local\Continuum\Anaconda3\lib\site-packages\requests\packages\urllib3\connection.py", line 155, in connect conn = self._new_conn() File "C:\Users\SD37561\AppData\Local\Continuum\Anaconda3\lib\site-packages\requests\packages\urllib3\connection.py", line 134, in _new_conn (self.host, self.port), self.timeout, **extra_kw) File "C:\Users\SD37561\AppData\Local\Continuum\Anaconda3\lib\site-packages\requests\packages\urllib3\util\connection.py", line 88, in create_connection raise err File "C:\Users\SD37561\AppData\Local\Continuum\Anaconda3\lib\site-packages\requests\packages\urllib3\util\connection.py", line 78, in create_connection sock.connect(sa) ConnectionRefusedError: [WinError 10061] No connection could be made because the target machine actively refused it During handling of the above exception, another exception occurred: Traceback (most recent call last): File "C:\Users\SD37561\AppData\Local\Continuum\Anaconda3\lib\site-packages\requests\adapters.py", line 370, in send timeout=timeout File "C:\Users\SD37561\AppData\Local\Continuum\Anaconda3\lib\site-packages\requests\packages\urllib3\connectionpool.py", line 597, in urlopen _stacktrace=sys.exc_info()[2]) File "C:\Users\SD37561\AppData\Local\Continuum\Anaconda3\lib\site-packages\requests\packages\urllib3\util\retry.py", line 245, in increment raise six.reraise(type(error), error, _stacktrace) File "C:\Users\SD37561\AppData\Local\Continuum\Anaconda3\lib\site-packages\requests\packages\urllib3\packages\six.py", line 309, in reraise raise value.with_traceback(tb) File "C:\Users\SD37561\AppData\Local\Continuum\Anaconda3\lib\site-packages\requests\packages\urllib3\connectionpool.py", line 544, in urlopen body=body, headers=headers) File "C:\Users\SD37561\AppData\Local\Continuum\Anaconda3\lib\site-packages\requests\packages\urllib3\connectionpool.py", line 349, in _make_request conn.request(method, url, **httplib_request_kw) File "C:\Users\SD37561\AppData\Local\Continuum\Anaconda3\lib\http\client.py", line 1088, in request self._send_request(method, url, body, headers) File "C:\Users\SD37561\AppData\Local\Continuum\Anaconda3\lib\http\client.py", line 1126, in _send_request self.endheaders(body) File "C:\Users\SD37561\AppData\Local\Continuum\Anaconda3\lib\http\client.py", line 1084, in endheaders self._send_output(message_body) File "C:\Users\SD37561\AppData\Local\Continuum\Anaconda3\lib\http\client.py", line 922, in _send_output self.send(msg) File "C:\Users\SD37561\AppData\Local\Continuum\Anaconda3\lib\http\client.py", line 857, in send self.connect() File "C:\Users\SD37561\AppData\Local\Continuum\Anaconda3\lib\site-packages\requests\packages\urllib3\connection.py", line 155, in connect conn = self._new_conn() File "C:\Users\SD37561\AppData\Local\Continuum\Anaconda3\lib\site-packages\requests\packages\urllib3\connection.py", line 134, in _new_conn (self.host, self.port), self.timeout, **extra_kw) File "C:\Users\SD37561\AppData\Local\Continuum\Anaconda3\lib\site-packages\requests\packages\urllib3\util\connection.py", line 88, in create_connection raise err File "C:\Users\SD37561\AppData\Local\Continuum\Anaconda3\lib\site-packages\requests\packages\urllib3\util\connection.py", line 78, in create_connection sock.connect(sa) requests.packages.urllib3.exceptions.ProtocolError: ('Connection aborted.', ConnectionRefusedError(10061, 'No connection could be made because the target machine actively refused it', None, 10061, None)) During handling of the above exception, another exception occurred: Traceback (most recent call last): File "C:\Users\SD37561\Desktop\python scripts\link_monitor.py", line 50, in mail_alert = validate_sites(sample_dict) File "C:\Users\SD37561\Desktop\python scripts\link_monitor.py", line 20, in validate_sites for _site, _auth in sample_dict.items()] File "C:\Users\SD37561\Desktop\python scripts\link_monitor.py", line 20, in for _site, _auth in sample_dict.items()] File "C:\Users\SD37561\Desktop\python scripts\link_monitor.py", line 14, in site_is_reachable response = requests.get(site_url, auth=authentication) File "C:\Users\SD37561\AppData\Local\Continuum\Anaconda3\lib\site-packages\requests\api.py", line 69, in get return request('get', url, params=params, **kwargs) File "C:\Users\SD37561\AppData\Local\Continuum\Anaconda3\lib\site-packages\requests\api.py", line 50, in request response = session.request(method=method, url=url, **kwargs) File "C:\Users\SD37561\AppData\Local\Continuum\Anaconda3\lib\site-packages\requests\sessions.py", line 465, in request resp = self.send(prep, **send_kwargs) File "C:\Users\SD37561\AppData\Local\Continuum\Anaconda3\lib\site-packages\requests\sessions.py", line 573, in send r = adapter.send(request, **kwargs) File "C:\Users\SD37561\AppData\Local\Continuum\Anaconda3\lib\site-packages\requests\adapters.py", line 415, in send raise ConnectionError(err, request=request) requests.exceptions.ConnectionError: ('Connection aborted.', ConnectionRefusedError(10061, 'No connection could be made because the target machine actively refused it', None, 10061, None))
the error was catched by adding the except Exception for the dict traverse and now its getting handled and printing user friendly message
unit testing for unverified user trying to login
I've been trying to test for a user that hasn't been verified. class TestLoginApi(TestCase): URL = '/rest-auth/login/' EMAIL = 'testuser#test PASSWORD = 'password' DATA = {'email': EMAIL, 'password': PASSWORD} #classmethod def setUpTestData(cls): cls.user = get_user_model().objects.create_user(username='testuser', email=cls.EMAIL, password=cls.PASSWORD) def test_login_api_without_verification(self): response = self.client.post(self.URL, self.DATA, format='json') The "response" line throws the following error Error Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/unittest/case.py", line 59, in testPartExecutor yield File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/unittest/case.py", line 601, in run testMethod() File "/Users/docdocengineering3/GitHub/website/project/authorization/Tests/test_login.py", line 34, in test_login_api_without_verification response = self.client.post(self.URL, self.DATA, format='json') File "/Users/docdocengineering3/.virtualenvs/docdoc/lib/python3.6/site-packages/django/test/client.py", line 548, in post secure=secure, **extra) File "/Users/docdocengineering3/.virtualenvs/docdoc/lib/python3.6/site-packages/django/test/client.py", line 350, in post secure=secure, **extra) File "/Users/docdocengineering3/.virtualenvs/docdoc/lib/python3.6/site-packages/django/test/client.py", line 416, in generic return self.request(**r) File "/Users/docdocengineering3/.virtualenvs/docdoc/lib/python3.6/site-packages/django/test/client.py", line 501, in request six.reraise(*exc_info) File "/Users/docdocengineering3/.virtualenvs/docdoc/lib/python3.6/site-packages/django/utils/six.py", line 686, in reraise raise value File "/Users/docdocengineering3/.virtualenvs/docdoc/lib/python3.6/site-packages/django/core/handlers/exception.py", line 41, in inner response = get_response(request) File "/Users/docdocengineering3/.virtualenvs/docdoc/lib/python3.6/site-packages/django/core/handlers/base.py", line 187, in _get_response response = self.process_exception_by_middleware(e, request) File "/Users/docdocengineering3/.virtualenvs/docdoc/lib/python3.6/site-packages/django/core/handlers/base.py", line 185, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/Users/docdocengineering3/.virtualenvs/docdoc/lib/python3.6/site-packages/django/views/decorators/csrf.py", line 58, in wrapped_view return view_func(*args, **kwargs) File "/Users/docdocengineering3/.virtualenvs/docdoc/lib/python3.6/site-packages/django/views/generic/base.py", line 68, in view return self.dispatch(request, *args, **kwargs) File "/Users/docdocengineering3/.virtualenvs/docdoc/lib/python3.6/site-packages/django/utils/decorators.py", line 67, in _wrapper return bound_func(*args, **kwargs) File "/Users/docdocengineering3/.virtualenvs/docdoc/lib/python3.6/site-packages/django/views/decorators/debug.py", line 76, in sensitive_post_parameters_wrapper return view(request, *args, **kwargs) File "/Users/docdocengineering3/.virtualenvs/docdoc/lib/python3.6/site-packages/django/utils/decorators.py", line 63, in bound_func return func.get(self, type(self))(*args2, **kwargs2) File "/Users/docdocengineering3/.virtualenvs/docdoc/lib/python3.6/site-packages/rest_auth/views.py", line 49, in dispatch return super(LoginView, self).dispatch(*args, **kwargs) File "/Users/docdocengineering3/.virtualenvs/docdoc/lib/python3.6/site-packages/rest_framework/views.py", line 489, in dispatch response = self.handle_exception(exc) File "/Users/docdocengineering3/.virtualenvs/docdoc/lib/python3.6/site-packages/rest_framework/views.py", line 449, in handle_exception self.raise_uncaught_exception(exc) File "/Users/docdocengineering3/.virtualenvs/docdoc/lib/python3.6/site-packages/rest_framework/views.py", line 486, in dispatch response = handler(request, *args, **kwargs) File "/Users/docdocengineering3/.virtualenvs/docdoc/lib/python3.6/site-packages/rest_auth/views.py", line 92, in post self.serializer.is_valid(raise_exception=True) File "/Users/docdocengineering3/.virtualenvs/docdoc/lib/python3.6/site-packages/rest_framework/serializers.py", line 237, in is_valid self._validated_data = self.run_validation(self.initial_data) File "/Users/docdocengineering3/.virtualenvs/docdoc/lib/python3.6/site-packages/rest_framework/serializers.py", line 435, in run_validation value = self.validate(value) File "/Users/docdocengineering3/.virtualenvs/docdoc/lib/python3.6/site-packages/rest_auth/serializers.py", line 105, in validate email_address = user.emailaddress_set.get(email=user.email) File "/Users/docdocengineering3/.virtualenvs/docdoc/lib/python3.6/site-packages/django/db/models/manager.py", line 85, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "/Users/docdocengineering3/.virtualenvs/docdoc/lib/python3.6/site-packages/django/db/models/query.py", line 380, in get self.model._meta.object_name Exception: EmailAddress matching query does not exist. I have no idea why this is happening. It isn't a setup problem as I've tried actually running the system, creating a user (not verifying) and when I "PostMan" the same link, I get the correct error back {"non_field_errors": [ "E-mail is not verified." ] } So it works in the actual product but not when testing. Anyone know why? Any help is greatly appreciated. This is the only test that I can't get to work, all the rest runs correctly.
You probably have your setting EMAIL_VERIFICATION set to mandatory. So you either change it to none in tests or manually create EmailAddress object (it's required by django-allauth when mandatory verification is on)