def execute(conf_attrs, dbname, uid, obj, method, *args, **kwargs): import openerp from openerp.api import Environment from openerp.modules.registry import Registry for attr, value in conf_attrs.items(): openerp.tools.config[attr] = value with Environment.manage(): registry = Registry(dbname) cr = registry.cursor() context = kwargs.get('context') and kwargs.pop('context') or {} env = Environment(cr, uid, context) # openerp.api.Environment._local.environments = env try: getattr(env.registry[obj], method)(cr, uid, *args, **kwargs) # Commit only when function finish env.cr.commit() except Exception as exc: env.cr.rollback() try: raise execute.retry( queue=execute.request.delivery_info['routing_key'], exc=exc, countdown=(execute.request.retries + 1) * 60, max_retries=5) except Exception as retry_exc: raise retry_exc finally: env.cr.close() return True
def abc_confirm_invoice(self, lines, packages, data, params, res): """Confirm invoice. Split into its own function to not lock the invoice sequence.""" invoice = params.get('invoice') if invoice and invoice.state == 'draft': self.env.cr.commit() env = None try: # Ne cursor doesn't time out when requesting lock. # Could be bad I guess? Works for now. # TODO: Look into setting a more reasonable lock wait time. new_cr = Registry(self.env.cr.dbname).cursor() new_cr.autocommit(True) env = api.Environment(new_cr, self.env.uid, self.env.context) # Validate invoice invoice.signal_workflow('invoice_open') res['invoice']['name'] = invoice.number res['messages'].append(u"Created and confirmed invoice %s." % invoice.number) res['results']['invoice'] = 'confirmed' # Commit to unlock the invoice sequence env.cr.commit() except Exception as e: res['warnings'].append( (_(u"Failed to confirm invoice %s!") % (invoice and (invoice.number or invoice.name) or 'Unknown'), '%s\n\nTraceback:\n%s' % (e.message or 'Unknown Error', traceback.format_exc()))) finally: if env: env.cr.close()
def _fcm_send_notification(self, subscription_ids, payload, dbname, uid, fcm_api_key, attempt=1): res = None if not fcm_api_key: _logger.exception("You need a FCM API key to send notification") return headers = { "Content-Type": "application/json", "Authorization": "key=" + fcm_api_key, } data = {'data': payload, 'registration_ids': subscription_ids} res = {} try: response = requests.post(FCM_END_POINT, headers=headers, data=json.dumps(data)) if response.status_code == 200: res = self._fcm_process_response(response, subscription_ids) elif response.status_code == 401: _logger.warning( "FCM Authentication: Provide valid FCM api key") elif response.status_code == 400: _logger.warning("Invalid JSON: Invalid payload format") else: retry = self._fcm_calculate_retry_after(response.headers) if retry and attempt <= FCM_RETRY_ATTEMPT: _logger.warning("FCM Service Unavailable: retrying") time.sleep(retry) attempt = attempt + 1 self._send_fcm_notification(subscription_ids, payload, dbname, uid, fcm_api_key, attempt=attempt) else: _logger.warning( "FCM service not available try after some time") except ConnectionError: _logger.warning("No Internet connection") except Exception: _logger.warning("Failed processing FCM queue") if res.get('errors') or res.get('canonical'): with api.Environment.manage(): with Registry(dbname).cursor() as cr: env = api.Environment(cr, uid, {}) if res.get('errors'): self._fcm_process_errors(res['errors'], env) if res.get('canonical'): self._fcm_process_canonical(res['canonical'], env)
def __new__(cls, cr, uid, context): assert context is not None args = (cr, uid, context) # if env already exists, return it env, envs = None, cls.envs for env in envs: if env.args == args: return env # otherwise create environment, and add it in the set self = object.__new__(cls) self.cr, self.uid, self.context = self.args = (cr, uid, frozendict(context)) self.registry = Registry(cr.dbname) self.cache = defaultdict(dict) # {field: {id: value, ...}, ...} self._protected = defaultdict(frozenset) # {field: ids, ...} self.dirty = defaultdict(set) # {record: set(field_name), ...} self.all = envs envs.add(self) return self