Se rendre au contenu
Odoo Menu
  • Se connecter
  • Essai gratuit
  • Applications
    Finance
    • Comptabilité
    • Facturation
    • Notes de frais
    • Feuilles de calcul (BI)
    • Documents
    • Signature
    Ventes
    • CRM
    • Ventes
    • PdV Boutique
    • PdV Restaurant
    • Abonnements
    • Location
    Sites web
    • Site Web
    • eCommerce
    • Blog
    • Forum
    • Live Chat
    • eLearning
    Chaîne d'approvisionnement
    • Inventaire
    • Fabrication
    • PLM
    • Achats
    • Maintenance
    • Qualité
    Ressources Humaines
    • Employés
    • Recrutement
    • Congés
    • Évaluations
    • Recommandations
    • Parc automobile
    Marketing
    • Marketing Social
    • E-mail Marketing
    • SMS Marketing
    • Événements
    • Marketing Automation
    • Sondages
    Services
    • Projet
    • Feuilles de temps
    • Services sur Site
    • Assistance
    • Planification
    • Rendez-vous
    Productivité
    • Discussion
    • Validations
    • Internet des Objets
    • VoIP
    • Connaissances
    • WhatsApp
    Applications tierces Odoo Studio Plateforme Cloud d'Odoo
  • Industries
    Commerce de détail
    • Librairie
    • Magasin de vêtements
    • Magasin de meubles
    • Épicerie
    • Quincaillerie
    • Magasin de jouets
    Food & Hospitality
    • Bar et Pub
    • Restaurant
    • Fast-food
    • Maison d’hôtes
    • Distributeur de boissons
    • Hôtel
    Immobilier
    • Agence immobilière
    • Cabinet d'architecture
    • Construction
    • Gestion immobilière
    • Jardinage
    • Association de copropriétaires
    Consultance
    • Cabinet d'expertise comptable
    • Partenaire Odoo
    • Agence Marketing
    • Cabinet d'avocats
    • Aquisition de talents
    • Audit & Certification
    Fabrication
    • Textile
    • Métal
    • Meubles
    • Alimentation
    • Brewery
    • Cadeaux d'entreprise
    Santé & Fitness
    • Club de sports
    • Opticien
    • Salle de fitness
    • Praticiens bien-être
    • Pharmacie
    • Salon de coiffure
    Trades
    • Bricoleur
    • Matériel informatique et support
    • Systèmes photovoltaïques
    • Cordonnier
    • Services de nettoyage
    • Services CVC
    Autres
    • Organisation à but non lucratif
    • Agence environnementale
    • Location de panneaux d'affichage
    • Photographie
    • Leasing de vélos
    • Revendeur de logiciel
    Browse all Industries
  • Communauté
    Apprenez
    • Tutoriels
    • Documentation
    • Certifications
    • Formation
    • Blog
    • Podcast
    Renforcer l'éducation
    • Programme éducatif
    • Business Game Scale-Up!
    • Rendez-nous visite
    Obtenir le logiciel
    • Téléchargement
    • Comparez les éditions
    • Versions
    Collaborer
    • Github
    • Forum
    • Événements
    • Traductions
    • Devenez partenaire
    • Services for Partners
    • Enregistrer votre cabinet comptable
    Nos Services
    • Trouver un partenaire
    • Trouver un comptable
    • Rencontrer un conseiller
    • Services de mise en œuvre
    • Références clients
    • Assistance
    • Mises à niveau
    Github Youtube Twitter Linkedin Instagram Facebook Spotify
    +1 (650) 691-3277
    Obtenir une démonstration
  • Tarification
  • Aide

Odoo is the world's easiest all-in-one management software.
It includes hundreds of business apps:

  • CRM
  • e-Commerce
  • Comptabilité
  • Inventaire
  • PoS
  • Projet
  • MRP
All apps
Vous devez être inscrit pour interagir avec la communauté.
Toutes les publications Personnes Badges
Étiquettes (Voir toutl)
odoo accounting v14 pos v15
À propos de ce forum
Vous devez être inscrit pour interagir avec la communauté.
Toutes les publications Personnes Badges
Étiquettes (Voir toutl)
odoo accounting v14 pos v15
À propos de ce forum
Aide

How to get a new cursor on new api on Thread

S'inscrire

Recevez une notification lorsqu'il y a de l'activité sur ce poste

Cette question a été signalée
environmentapi8.0
2 Réponses
32095 Vues
Avatar
Max

Found from here - http://odoo-new-api-guide-line.readthedocs.org/en/latest/conventions.html:

Using Thread

When using thread you have to create you own cursor and initiate a new environment for each thread. committing is done by committing the cursor:

with Environment.manage(): # class function

               env = Environment(cr, uid, context)

But how to use it?

We have old api code:

 

        with Environment.manage():

            cr = self.pool.cursor()

            dialer = self.pool['asterisk.dialer'].browse(cr, uid, ids, context=context)[0]

 

It works.

Now how to do the same with new api?

 

        with Environment.manage():

            dialer = self.env['asterisk.dialer'].browse([dialer_id])

 

Gives the following error: OperationalError: Unable to use a closed cursor.

 

Tried this:

def run_dialer(self, dialer_id):

        with Environment.manage():

            cr, uid, context = self.env.args

            env = Environment(cr, uid, context)

            dialer = env['asterisk.dialer'].browse([dialer_id])

            domain = [('phone', '!=', None)] + [eval(dialer.dialer_domain)[0]]

            contacts = env[dialer.dialer_model].search(domain)

 

The same:

Exception in thread Thread-7:

Traceback (most recent call last):

  File "/usr/lib/python2.7/threading.py", line 808, in __bootstrap_inner

    self.run()

  File "/usr/lib/python2.7/threading.py", line 761, in run

    self.__target(*self.__args, **self.__kwargs)

  File "/home/max/tmp-work/odoo/odoo.my/openerp/api.py", line 235, in wrapper

    return new_api(self, *args, **kwargs)

  File "/home/max/tmp-work/odoo/myaddons/asterisk_dialer/models/dialer.py", line 98, in run_dialer

    contacts = env[dialer.dialer_model].search(domain)

  File "/home/max/tmp-work/odoo/odoo.my/openerp/api.py", line 235, in wrapper

    return new_api(self, *args, **kwargs)

  File "/home/max/tmp-work/odoo/odoo.my/openerp/api.py", line 464, in new_api

    result = method(self._model, cr, uid, *args, **kwargs)

  File "/home/max/tmp-work/odoo/odoo.my/openerp/models.py", line 1679, in search

    return self._search(cr, user, args, offset=offset, limit=limit, order=order, context=context, count=count)

  File "/home/max/tmp-work/odoo/odoo.my/openerp/api.py", line 237, in wrapper

    return old_api(self, *args, **kwargs)

  File "/home/max/tmp-work/odoo/odoo.my/openerp/addons/base/res/res_partner.py", line 643, in _search

    count=count, access_rights_uid=access_rights_uid)

  File "/home/max/tmp-work/odoo/odoo.my/openerp/api.py", line 237, in wrapper

    return old_api(self, *args, **kwargs)

  File "/home/max/tmp-work/odoo/odoo.my/openerp/models.py", line 4543, in _search

    res = cr.fetchall()

  File "/home/max/tmp-work/odoo/odoo.my/openerp/sql_db.py", line 157, in wrapper

    raise psycopg2.OperationalError(msg)

1
Avatar
Ignorer
Avatar
Moisés Augusto López Calderón
Meilleure réponse

FYI this work for me:

with openerp.api.Environment.manage():
    with openerp.registry(self.env.cr.dbname).cursor() as new_cr:
        # Create a new environment with new cursor database
        new_env = api.Environment(new_cr, self.env.uid, self.env.context)
        # with_env replace original env for this method
        self.with_env(new_env).write({'name': 'hello'})  # isolated transaction to commit
        new_env.cr.commit()  # Don't show a invalid-commit in this case
    # You don't need close your cr because is closed when finish "with"
# You don't need clear caches because is cleared when finish "with"
6
Avatar
Ignorer
PY

What does `Environment.manage()` ?

Avatar
Max
Auteur Meilleure réponse

The following seem to work reliably:

            new_cr = sql_db.db_connect(self.env.cr.dbname).cursor()
            uid, context = self.env.uid, self.env.context
            with api.Environment.manage():
                self.env = api.Environment(new_cr, uid, context)

                try:
                      ....

                finally:
                    self.env.cr.close()
 

2
Avatar
Ignorer
Vous appréciez la discussion ? Ne vous contentez pas de lire, rejoignez-nous !

Créez un compte dès aujourd'hui pour profiter de fonctionnalités exclusives et échanger avec notre formidable communauté !

S'inscrire
Publications associées Réponses Vues Activité
[8.0] New API - Using Domains - ValueError: Invalid leaf Résolu
api method 8.0
Avatar
Avatar
Avatar
5
juil. 18
23288
Error Field is accesed before being computed.
api onchange compute 8.0
Avatar
0
mars 15
7047
Has anyone integrated Helpdesk with Zoom for meeting scheduling?
api
Avatar
Avatar
1
août 25
1309
Using API check if Odoo is using Odoo sh or on-premises hosting. Résolu
api
Avatar
Avatar
1
août 25
1694
External API XMLRPC Authentication Keeps Replying with false
api
Avatar
Avatar
Avatar
2
juil. 25
4593
Communauté
  • Tutoriels
  • Documentation
  • Forum
Open Source
  • Téléchargement
  • Github
  • Runbot
  • Traductions
Services
  • Hébergement Odoo.sh
  • Assistance
  • Migration
  • Développements personnalisés
  • Éducation
  • Trouver un comptable
  • Trouver un partenaire
  • Devenez partenaire
À propos
  • Notre société
  • Actifs de la marque
  • Contactez-nous
  • Emplois
  • Événements
  • Podcast
  • Blog
  • Clients
  • Informations légales • Confidentialité
  • Sécurité.
الْعَرَبيّة Català 简体中文 繁體中文 (台灣) Čeština Dansk Nederlands English Suomi Français Deutsch हिंदी Bahasa Indonesia Italiano 日本語 한국어 (KR) Lietuvių kalba Język polski Português (BR) română русский язык Slovenský jazyk slovenščina Español (América Latina) Español ภาษาไทย Türkçe українська Tiếng Việt

Odoo est une suite d'applications open source couvrant tous les besoins de votre entreprise : CRM, eCommerce, Comptabilité, Inventaire, Point de Vente, Gestion de Projet, etc.

Le positionnement unique d'Odoo est d'être à la fois très facile à utiliser et totalement intégré.

Website made with

Odoo Experience on YouTube

1. Use the live chat to ask your questions.
2. The operator answers within a few minutes.

Live support on Youtube
Watch now