PonyORM with mixins with custom hash - ponyorm

I have a (in this case) mixin class that defines its own hash and eq. When mixing this into a Pony Entity evil things happen:
from pony.orm import Database, Optional, Required
db = Database()
class RoleMixin:
def __hash__(self):
return hash(self.name)
def __eq__(self, other):
return self.name == other or self.name == getattr(other, "name", None)
def get_permissions(self):
if self.permissions:
return self.permissions
return set()
class Role(db.Entity, RoleMixin):
name = Required(str, unique=True)
description = Optional(str, nullable=True)
permissions = Optional(str, nullable=True)
db.bind("sqlite", ":memory:", create_db=True)
db.generate_mapping(create_tables=True)
role = Role(name="admin")
print(role)
And when running this:
File "/Users/jwag/fs/py3.7env/lib/python3.7/site-packages/pony/utils/utils.py", line 78, in cut_traceback
reraise(exc_type, exc, full_tb)
File "/Users/jwag/fs/py3.7env/lib/python3.7/site-packages/pony/utils/utils.py", line 95, in reraise
try: raise exc.with_traceback(tb)
File "/Users/jwag/fs/py3.7env/lib/python3.7/site-packages/pony/utils/utils.py", line 61, in cut_traceback
try: return func(*args, **kwargs)
File "/Users/jwag/fs/py3.7env/lib/python3.7/site-packages/pony/orm/core.py", line 4721, in __init__
entity._get_from_identity_map_(pkval, 'created', undo_funcs=undo_funcs, obj_to_init=obj)
File "/Users/jwag/fs/py3.7env/lib/python3.7/site-packages/pony/orm/core.py", line 4416, in _get_from_identity_map_
cache.objects.add(obj)
File "/Users/jwag/fs/flask-security/flask_security/ponydbg.py", line 8, in __hash__
return hash(self.name)
File "<string>", line 2, in __get__
File "/Users/jwag/fs/py3.7env/lib/python3.7/site-packages/pony/utils/utils.py", line 78, in cut_traceback
reraise(exc_type, exc, full_tb)
File "/Users/jwag/fs/py3.7env/lib/python3.7/site-packages/pony/utils/utils.py", line 95, in reraise
try: raise exc.with_traceback(tb)
File "/Users/jwag/fs/py3.7env/lib/python3.7/site-packages/pony/utils/utils.py", line 61, in cut_traceback
try: return func(*args, **kwargs)
File "/Users/jwag/fs/py3.7env/lib/python3.7/site-packages/pony/orm/core.py", line 2278, in __get__
value = attr.get(obj)
File "/Users/jwag/fs/py3.7env/lib/python3.7/site-packages/pony/orm/core.py", line 2286, in get
vals = obj._vals_
AttributeError: _vals_
Since Pony is using meta-programming - I can't really figure out where/why it is using hash and why defining it confuses it so much.
Any thoughts?

You may have an '#classmethod' decorator before your mixin class methods.
class RoleMixin:
#classmethod
def __hash__(cls):
return hash(cls.name)
#classmethod
def __eq__(cls, other):
return cls.name == other or cls.name == getattr(other, "name", None)
#classmethod
def get_permissions(cls):
if cls.permissions:
return cls.permissions
return set()

Related

DRF - Getting 'NoneType object is not callable' error on delete instance from ModelViewSet

I am getting TypeError, when I try to delete Warehouse instance.
Note: If I delete Shop instance, Warehouse under that Shop needs be deleted, that's why I used on_delete=models.CASCADE.
class Warehouse(models.Model):
"""Warehouse model"""
name = models.CharField(max_length=255)
shop = models.ForeignKey(Shop, on_delete=models.CASCADE)
class WarehouseViewSet(viewsets.ModelViewSet):
"""Viewset"""
queryset = models.Warehouse.objects.all()
serializer_class = serializers.WarehouseSerializer
Error:
TypeError: 'NoneType' object is not callable
[14/Feb/2021 22:10:46] "DELETE /api/v1/shop/warehouse/2/ HTTP/1.1" 500 113266
Internal Server Error: /api/v1/shop/warehouse/2/
Traceback (most recent call last):
File "C:\Python38\lib\site-packages\django\core\handlers\exception.py", line 34, in inner
response = get_response(request)
File "C:\Python38\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response
response = self.process_exception_by_middleware(e, request)
File "C:\Python38\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Python38\lib\site-packages\django\views\decorators\csrf.py", line 54, in wrapped_view
return view_func(*args, **kwargs)
File "C:\Python38\lib\site-packages\rest_framework\viewsets.py", line 114, in view
return self.dispatch(request, *args, **kwargs)
File "C:\Python38\lib\site-packages\rest_framework\views.py", line 505, in dispatch
response = self.handle_exception(exc)
File "C:\Python38\lib\site-packages\rest_framework\views.py", line 465, in handle_exception
self.raise_uncaught_exception(exc)
File "C:\Python38\lib\site-packages\rest_framework\views.py", line 476, in raise_uncaught_exception
raise exc
File "C:\Python38\lib\site-packages\rest_framework\views.py", line 502, in dispatch
response = handler(request, *args, **kwargs)
File "C:\Python38\lib\site-packages\rest_framework\mixins.py", line 91, in destroy
self.perform_destroy(instance)
File "C:\Python38\lib\site-packages\rest_framework\mixins.py", line 95, in perform_destroy
instance.delete()
File "C:\Python38\lib\site-packages\django\db\models\base.py", line 921, in delete
collector.collect([self], keep_parents=keep_parents)
File "C:\Python38\lib\site-packages\django\db\models\deletion.py", line 224, in collect
field.remote_field.on_delete(self, field, sub_objs, self.using)
Found the solution. I did not handle on_delete for Children model.
SOLUTION
class WarehouseChildren(models.Model):
data = models.PositiveIntegerField(default=0)
warehouse = models.ForeignKey(Warehouse, on_delete=models.SET_NULL, null=True)
or
class WarehouseChildren(models.Model):
data = models.PositiveIntegerField(default=0)
warehouse = models.ForeignKey(Warehouse, on_delete=models.CASCADE)

Integrate djongo (Mongo ORM) into Django Rest Framework

Actually I am developping a POC on which we want an app which has a REST API and discuss with MongoDB in Python.
For this we found several techs, such as Django-rest-framework for the API side and djongo for the ORM side. Nevertheless, I scan lots of tutos on how to implement djongo ORM in DRF, no way there is nothing BUT apparently it's possible, can someone confirm?
My main problem is my POC does absolutely not work, indeed, in used djongo models in my DRF Serializers but it does not work at all, I dont understand, can someone figure it out whats going on?:
models.py:
from djongo import models
class Channel(models.Model):
sourceId = models.IntegerField(default=-1)
usageId = models.IntegerField(default=0)
channelId = models.IntegerField(default=0)
cabinetId = models.IntegerField(default=0)
zoneId = models.IntegerField(default=0)
class Product(models.Model):
dateCreation = models.DateTimeField(auto_now=True)
dateUpdate = models.DateTimeField(auto_now=True)
name = models.CharField(max_length=50, default="Unknown product name")
channels = models.EmbeddedModelField(
model_container=Channel,
)
objects = models.DjongoManager()
views.py:
from django.http import HttpResponse, JsonResponse
from django.views.decorators.csrf import csrf_exempt
from rest_framework.parsers import JSONParser
from Api.models import Product
from Api.serializers import ProductSerializer
#csrf_exempt
def ProductList(aRequest):
"""
#brief List all products, or create a new product.
"""
if aRequest.method == 'GET':
wProducts = Product.objects.all()
wSerializer = ProductSerializer(wProducts, many=True)
return JsonResponse(wSerializer.data, safe=False)
elif aRequest.method == 'POST':
data = JSONParser().parse(aRequest)
wSerializer = ProductSerializer(data=data)
if wSerializer.is_valid():
wSerializer.save()
return JsonResponse(wSerializer.data, status=201)
return JsonResponse(wSerializer.errors, status=400)
#csrf_exempt
def ProductDetail(aRequest, pk):
"""
#brief Retrieve, update or delete a product.
"""
try:
wProducts = Product.objects.get(pk=pk)
except Product.DoesNotExist:
return HttpResponse(status=404)
if aRequest.method == 'GET':
wSerializer = ProductSerializer(wProducts)
return JsonResponse(wSerializer.data)
elif aRequest.method == 'PUT':
data = JSONParser().parse(aRequest)
wSerializer = ProductSerializer(wProducts, data=data)
if wSerializer.is_valid():
wSerializer.save()
return JsonResponse(wSerializer.data)
return JsonResponse(wSerializer.errors, status=400)
elif aRequest.method == 'DELETE':
Product.delete()
return HttpResponse(status=204)
serializers.py:
from rest_framework import serializers
from Api.models import Product, Channel
class ChannelSerializer(serializers.ModelSerializer):
class Meta:
model = Channel
fields = ('sourceId', 'usageId', 'channelId', 'cabinetId', 'zoneId')
def create(self, validated_data):
wChannel = Channel.objects.create(**validated_data)
return wChannel
class ProductSerializer(serializers.ModelSerializer):
channels = ChannelSerializer(many=True)
class Meta:
model = Product
fields = ('dateCreation', 'dateUpdate', 'name', 'channels')
def create(self, validated_data):
wChannels = validated_data.pop("channels")
wProduct = Product.objects.create(**validated_data)
for wChannel in wChannels:
Channel.objects.create(product=wProduct, **wChannel)
return wProduct
When I run my server with this POST request:
{
"dateCreation": "2018-07-20 12:00:00.000",
"dateUpdate": "2018-07-20 12:00:00.000",
"name": "post_test_channel_1",
"channels": [{
"sourceId": -1,
"usageId": 100,
"channelId": 0,
"cabinetId": 0,
"zoneId": 1
}]
}
I obtain that stacktrace:
Internal Server Error: /products/
Traceback (most recent call last):
File "/home/soulasb/projects/POC/venv-app/lib/python3.6/site-packages/django/core/handlers/exception.py", line 35, in inner
response = get_response(request)
File "/home/soulasb/projects/POC/venv-app/lib/python3.6/site-packages/django/core/handlers/base.py", line 128, in _get_response
response = self.process_exception_by_middleware(e, request)
File "/home/soulasb/projects/POC/venv-app/lib/python3.6/site-packages/django/core/handlers/base.py", line 126, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/home/soulasb/projects/POC/venv-app/lib/python3.6/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view
return view_func(*args, **kwargs)
File "/home/soulasb/projects/POC/PocEms/Api/views.py", line 25, in ProductList
wSerializer.save()
File "/home/soulasb/projects/POC/venv-app/lib/python3.6/site-packages/rest_framework/serializers.py", line 214, in save
self.instance = self.create(validated_data)
File "/home/soulasb/projects/POC/PocEms/Api/serializers.py", line 29, in create
wProduct = Product.objects.create(**validated_data)
File "/home/soulasb/projects/POC/venv-app/lib/python3.6/site-packages/django/db/models/manager.py", line 82, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "/home/soulasb/projects/POC/venv-app/lib/python3.6/site-packages/django/db/models/query.py", line 417, in create
obj.save(force_insert=True, using=self.db)
File "/home/soulasb/projects/POC/venv-app/lib/python3.6/site-packages/django/db/models/base.py", line 729, in save
force_update=force_update, update_fields=update_fields)
File "/home/soulasb/projects/POC/venv-app/lib/python3.6/site-packages/django/db/models/base.py", line 759, in save_base
updated = self._save_table(raw, cls, force_insert, force_update, using, update_fields)
File "/home/soulasb/projects/POC/venv-app/lib/python3.6/site-packages/django/db/models/base.py", line 842, in _save_table
result = self._do_insert(cls._base_manager, using, fields, update_pk, raw)
File "/home/soulasb/projects/POC/venv-app/lib/python3.6/site-packages/django/db/models/base.py", line 880, in _do_insert
using=using, raw=raw)
File "/home/soulasb/projects/POC/venv-app/lib/python3.6/site-packages/django/db/models/manager.py", line 82, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "/home/soulasb/projects/POC/venv-app/lib/python3.6/site-packages/django/db/models/query.py", line 1125, in _insert
return query.get_compiler(using=using).execute_sql(return_id)
File "/home/soulasb/projects/POC/venv-app/lib/python3.6/site-packages/django/db/models/sql/compiler.py", line 1284, in execute_sql
for sql, params in self.as_sql():
File "/home/soulasb/projects/POC/venv-app/lib/python3.6/site-packages/django/db/models/sql/compiler.py", line 1237, in as_sql
for obj in self.query.objs
File "/home/soulasb/projects/POC/venv-app/lib/python3.6/site-packages/django/db/models/sql/compiler.py", line 1237, in <listcomp>
for obj in self.query.objs
File "/home/soulasb/projects/POC/venv-app/lib/python3.6/site-packages/django/db/models/sql/compiler.py", line 1236, in <listcomp>
[self.prepare_value(field, self.pre_save_val(field, obj)) for field in fields]
File "/home/soulasb/projects/POC/venv-app/lib/python3.6/site-packages/django/db/models/sql/compiler.py", line 1176, in prepare_value
value = field.get_db_prep_save(value, connection=self.connection)
File "/home/soulasb/projects/POC/venv-app/lib/python3.6/site-packages/django/db/models/fields/__init__.py", line 767, in get_db_prep_save
return self.get_db_prep_value(value, connection=connection, prepared=False)
File "/home/soulasb/projects/POC/venv-app/lib/python3.6/site-packages/djongo/models/fields.py", line 461, in get_db_prep_value
model=Model
ValueError: Value: None must be instance of Model: <class 'django.db.models.base.Model'>
This usually happens when you have added an EmbeddedModelField in your model and not passing an object to this field while creating an entry to this model.
I didnt find an option to add an EmbeddedModelField with null=True option.
Hope this helps someone
It could be the ENFORCE_SCHEMA set to true in settings.py. Maybe change it to "ENFORCE_SCHEMA: false".

scrapy sending mail got an ERROR: Unable to send mail. object of type 'module' has no len()

I wanna send email when spider closed, code is like this:
def close(spider, reason):
# mailer = MailSender.from_settings(self.settings)
from scrapy.mail import MailSender
mailer = MailSender(
smtphost="smtp.163.com",
mailfrom="rhys***#163.com",
smtpuser="rhys***g#163.com",
smtppass="***",
smtpport=25
)
body = u"""
content
"""
subject = u'title'
mailer.send(to=["rhys***#qq.com"],
subject=subject.encode("utf-8"),
body=body.encode("utf-8"),
cc=['12202012**#qq.com'])
But I got an error like this:
[twisted] CRITICAL: Unhandled Error
Traceback (most recent call last):
File "/home/rhys/.pyenv/versions/2.7.5/envs/p2spider/lib/python2.7/site-
packages/twisted/python/log.py", line 103, in callWithLogger
return callWithContext({"system": lp}, func, *args, **kw)
File "/home/rhys/.pyenv/versions/2.7.5/envs/p2spider/lib/python2.7/site-
packages/twisted/python/log.py", line 86, in callWithContext
return context.call({ILogContext: newCtx}, func, *args, **kw)
File "/home/rhys/.pyenv/versions/2.7.5/envs/p2spider/lib/python2.7/site-
packages/twisted/python/context.py", line 122, in callWithContext
return self.currentContext().callWithContext(ctx, func, *args, **kw)
File "/home/rhys/.pyenv/versions/2.7.5/envs/p2spider/lib/python2.7/site-
packages/twisted/python/context.py", line 85, in callWithContext
return func(*args,**kw)
--- <exception caught here> ---
File "/home/rhys/.pyenv/versions/2.7.5/envs/p2spider/lib/python2.7/site-
packages/twisted/internet/posixbase.py", line 597, in _doReadOrWrite
why = selectable.doRead()
File "/home/rhys/.pyenv/versions/2.7.5/envs/p2spider/lib/python2.7/site-
packages/twisted/internet/tcp.py", line 208, in doRead
return self._dataReceived(data)
File "/home/rhys/.pyenv/versions/2.7.5/envs/p2spider/lib/python2.7/site-
packages/twisted/internet/tcp.py", line 214, in _dataReceived
packages/twisted/internet/tcp.py", line 214, in _dataReceived
rval = self.protocol.dataReceived(data)
File "/home/rhys/.pyenv/versions/2.7.5/envs/p2spider/lib/python2.7/site-
packages/twisted/protocols/tls.py", line 330, in dataReceived
self._flushReceiveBIO()
File "/home/rhys/.pyenv/versions/2.7.5/envs/p2spider/lib/python2.7/site-
packages/twisted/protocols/tls.py", line 295, in _flushReceiveBIO
ProtocolWrapper.dataReceived(self, bytes)
File "/home/rhys/.pyenv/versions/2.7.5/envs/p2spider/lib/python2.7/site-
packages/twisted/protocols/policies.py", line 120, in dataReceived
self.wrappedProtocol.dataReceived(data)
File "/home/rhys/.pyenv/versions/2.7.5/envs/p2spider/lib/python2.7/site-
packages/twisted/protocols/basic.py", line 571, in dataReceived
why = self.lineReceived(line)
File "/home/rhys/.pyenv/versions/2.7.5/envs/p2spider/lib/python2.7/site-
packages/twisted/mail/smtp.py", line 995, in lineReceived
why = self._okresponse(self.code, b'\n'.join(self.resp))
File "/home/rhys/.pyenv/versions/2.7.5/envs/p2spider/lib/python2.7/site-
packages/twisted/mail/smtp.py", line 1044, in smtpState_to
return self.smtpState_toOrData(0, b'')
File "/home/rhys/.pyenv/versions/2.7.5/envs/p2spider/lib/python2.7/site-
packages/twisted/mail/smtp.py", line 1062, in smtpState_toOrData
self.sendLine(b'RCPT TO:' + quoteaddr(self.lastAddress))
File "/home/rhys/.pyenv/versions/2.7.5/envs/p2spider/lib/python2.7/site-
packages/twisted/mail/smtp.py", line 179, in quoteaddr
res = email.utils.parseaddr(addr)
File "/home/rhys/.pyenv/versions/2.7.5/lib/python2.7/email/utils.py", li
ne 215, in parseaddr
addrs = _AddressList(addr).addresslist
File "/home/rhys/.pyenv/versions/2.7.5/lib/python2.7/email/_parseaddr.py
", line 457, in __init__
self.addresslist = self.getaddrlist()
File "/home/rhys/.pyenv/versions/2.7.5/lib/python2.7/email/_parseaddr.py
", line 217, in getaddrlist
while self.pos < len(self.field):
exceptions.TypeError: object of type 'module' has no len()
anybody can explain why?
I use python2.7 and scapy1.4. if I comment the code mentioned above everything is just ok
thanks
I bumped to twisted 17.9 and the problem went away.

Odoo - outgoing email KeyError: 'body'

In Odoo 9 community outgoing email used to work (smtp configured, etc.), but now I get the following error when trying to send any email (invoice, internal note, etc.) from any account, for any template.
Things I changed since it worked that might (or might not) be linked to this issue:
I installed and uninstalled the SMTP Server Per User plugin
I changed the "from: " email address in the email templates
Any clue why this occurs? Or any clue what this "body" key is and where it is supposed to be defined? Thanks!
Odoo Server Error
Traceback (most recent call last):
File "/usr/lib/python2.7/dist-packages/openerp/http.py", line 605, in _handle_exception
return super(JsonRequest, self)._handle_exception(exception)
File "/usr/lib/python2.7/dist-packages/openerp/http.py", line 642, in dispatch
result = self._call_function(**self.params)
File "/usr/lib/python2.7/dist-packages/openerp/http.py", line 316, 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 309, in checked_call
result = self.endpoint(*a, **kw)
File "/usr/lib/python2.7/dist-packages/openerp/http.py", line 893, in __call__
return self.method(*args, **kw)
File "/usr/lib/python2.7/dist-packages/openerp/http.py", line 471, in response_wrap
response = f(*args, **kw)
File "/usr/lib/python2.7/dist-packages/openerp/addons/web/controllers/main.py", line 998, in call_button
action = self._call_kw(model, method, args, {})
File "/usr/lib/python2.7/dist-packages/openerp/addons/web/controllers/main.py", line 986, 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 238, in wrapper
return old_api(self, *args, **kwargs)
File "/usr/lib/python2.7/dist-packages/openerp/api.py", line 369, in old_api
result = method(recs, *args, **kwargs)
File "/usr/lib/python2.7/dist-packages/openerp/addons/mail/wizard/mail_compose_message.py", line 191, in send_mail_action
return self.send_mail()
File "/usr/lib/python2.7/dist-packages/openerp/api.py", line 236, in wrapper
return new_api(self, *args, **kwargs)
File "/usr/lib/python2.7/dist-packages/openerp/addons/account/models/account_invoice.py", line 1306, in send_mail
return super(MailComposeMessage, self).send_mail(auto_commit=auto_commit)
File "/usr/lib/python2.7/dist-packages/openerp/api.py", line 236, in wrapper
return new_api(self, *args, **kwargs)
File "/usr/lib/python2.7/dist-packages/openerp/addons/mail/wizard/mail_compose_message.py", line 248, in send_mail
ActiveModel.browse(res_id).message_post(message_type='comment', subtype=subtype, **mail_values)
File "/usr/lib/python2.7/dist-packages/openerp/api.py", line 236, in wrapper
return new_api(self, *args, **kwargs)
File "/usr/lib/python2.7/dist-packages/openerp/addons/mail/models/mail_thread.py", line 1712, in message_post
new_message = MailMessage.create(values)
File "/usr/lib/python2.7/dist-packages/openerp/api.py", line 236, in wrapper
return new_api(self, *args, **kwargs)
File "/usr/lib/python2.7/dist-packages/openerp/addons/mail/models/mail_message.py", line 864, in create
user_signature=self.env.context.get('mail_notify_user_signature', True))
File "/usr/lib/python2.7/dist-packages/openerp/api.py", line 236, in wrapper
return new_api(self, *args, **kwargs)
File "/usr/lib/python2.7/dist-packages/openerp/addons/mail/models/mail_message.py", line 926, in _notify
partners._notify(self, force_send=force_send, user_signature=user_signature)
File "/usr/lib/python2.7/dist-packages/openerp/api.py", line 236, in wrapper
return new_api(self, *args, **kwargs)
File "/usr/lib/python2.7/dist-packages/openerp/addons/mail/models/res_partner.py", line 127, in _notify
('notify_email', '!=', 'none')])._notify_by_email(message, force_send=force_send, user_signature=user_signature)
File "/usr/lib/python2.7/dist-packages/openerp/api.py", line 236, in wrapper
return new_api(self, *args, **kwargs)
File "/usr/lib/python2.7/dist-packages/openerp/addons/mail/models/res_partner.py", line 178, in _notify_by_email
new_emails, new_recipients_nbr = self._notify_send(not_values['body'], not_values['subject'], recipient_template_values['not_followers'], **base_mail_values)
KeyError: 'body'
#v11 odoo community
Solved Error : Odoo - outgoing email KeyError: 'body'
When Other User sends message on contacts page it gives outgoing email KeyError: 'body'.
This Error is occur from Mail Template : [mail module /data/ mail_data.xml]
so change Your Template Body code Or You Can Also inherit Mail Template:
Remove extra content in this mail_data.xml file.
% if ctx.get('website_url'):
% endif
Only This code Work Properly :
<p style="color: #555555;">
Sent by
% if ctx.get('website_url'):
<a href="${ctx['website_url']}" style="text-decoration:none; color: #875A7B;">
% endif
${ctx.get('company_name')}
</a>
using
<a target="_blank" href="https://www.odoo.com" style="text-decoration:none; color: #875A7B;">Odoo</a>.
</p>
Also Reference : https://i.stack.imgur.com/h8yMK.png
I did not solve the issue myself, but the person who did told me it came from a translation file and an "<" sign that was interpreted as a smaller than in the python code. So he changed the translation file to remove the smaller than.

Odoo 8 -Browse a model in Object Class

I have Object class and i need to browse the model document.directory in this class. I tried this.
class node_database(object):
obj=openerp.registry(cr.dbname).get('document.directory')
print'obj',obj # it ptints document.directory
datas=obj.browse(cr,uid,ids)
print'datas',datas # Here nothing print
and also tried this:
osv_pool = pooler.get_pool(dbname)
dir_obj=osv_pool.get('document.directory')
Search function works fine but browse not?
Getting this error:
2016-06-24 06:41:52,690 9427 ERROR dms1 openerp.addons.document_ftp.ftpserver: Traceback (most recent call last):
File "/home/kabeer/odoo-8.0-20151229/openerp/addons/document_ftp/ftpserver/ftpserver.py", line 1806, in try_as_current_user
re=self.run_as_current_user(function, *args, **kwargs)
File "/home/kabeer/odoo-8.0-20151229/openerp/addons/document_ftp/ftpserver/ftpserver.py", line 1779, in run_as_current_user
return function(*args, **kwargs)
File "/home/kabeer/odoo-8.0-20151229/openerp/addons/document_ftp/ftpserver/abstracted_fs.py", line 509, in get_list_dir
listing = self.listdir(datacr)
File "/home/kabeer/odoo-8.0-20151229/openerp/addons/document_ftp/ftpserver/abstracted_fs.py", line 377, in listdir
res = node.children(cr)
File "/home/kabeer/odoo-8.0-20151229/openerp/addons/document/document.py", line 981, in children
res = self._child_get(cr, domain=domain) + self._file_get(cr)
File "/home/kabeer/odoo-8.0-20151229/openerp/addons/document/document.py", line 1022, in _child_get
print'cntobj_search_read',cntobj.search_read(cr, uid,[('id','=',1)],['name'],context=ctx)
File "/home/kabeer/odoo-8.0-20151229/openerp/api.py", line 256, in wrapper
return old_api(self, *args, **kwargs)
File "/home/kabeer/odoo-8.0-20151229/openerp/models.py", line 5186, in search_read
result = self.read(cr, uid, record_ids, fields, context=read_ctx)
File "/home/kabeer/odoo-8.0-20151229/openerp/api.py", line 256, in wrapper
return old_api(self, *args, **kwargs)
File "/home/kabeer/odoo-8.0-20151229/openerp/models.py", line 3144, in read
records = self.browse(cr, user, ids, context)
File "/home/kabeer/odoo-8.0-20151229/openerp/api.py", line 256, in wrapper
return old_api(self, *args, **kwargs)
File "/home/kabeer/odoo-8.0-20151229/openerp/models.py", line 5266, in browse
return self._browse(Environment(cr, uid, context or {}), ids)
File "/home/kabeer/odoo-8.0-20151229/openerp/api.py", line 740, in __new__
env, envs = None, cls.envs
File "/home/kabeer/odoo-8.0-20151229/openerp/tools/func.py", line 109, in __get__
return self.fget.__get__(None, owner)()
File "/home/kabeer/odoo-8.0-20151229/openerp/api.py", line 713, in envs
return cls._local.environments
File "/usr/lib/python2.7/dist-packages/werkzeug/local.py", line 71, in __getattr__
raise AttributeError(name)
AttributeError: environments
Any solution pls?
for item in obj.search(cr, uid, []):
obj = self.browse(cr, uid, item)
print obj.name
Resolved this issue by create a new cursor.
new_cr = openerp.sql_db.db_connect(self.context.cr.dbname).cursor()
uid, context = self.context.uid, self.context.context
with api.Environment.manage():
self.env = api.Environment(new_cr, uid, context)
try:
datas=obj.browse(cr,uid,ids)
print'datas',datas # Here print
finally:
self.env.cr.close()