Skip to content

Commit

Permalink
Merge pull request fdegrave#2 from tvanesse/master
Browse files Browse the repository at this point in the history
Move from auth.User to the more generic settings.AUTH_USER_MODEL
  • Loading branch information
fdegrave authored Jul 5, 2016
2 parents 52f0f92 + bbeb09e commit bcbbab1
Show file tree
Hide file tree
Showing 4 changed files with 88 additions and 14 deletions.
2 changes: 1 addition & 1 deletion README.rst
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ Quick start

INSTALLED_APPS = (
...
'Djangodoo',
'djangodoo',
)

2. Include the Odoo host configuration in your project settings like this::
Expand Down
88 changes: 78 additions & 10 deletions djangodoo/__init__.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,14 @@
# -*- coding: utf-8 -*-
from django.conf import settings
from django.db.models.signals import class_prepared
from django.core.mail import send_mail
import erppeek
from .fields import convert_field
import logging

from time import sleep
import traceback

logger = logging.getLogger(__name__)


Expand All @@ -16,16 +20,79 @@ def set_auth_cache():

def set_odoo_client():
config = getattr(settings, "ODOO_HOST", False)
try:
settings.odoo = erppeek.Client("%s:%d" % (config['HOST'], config['PORT']), db=config['DB'],
user=config['USER'], password=config['PASSWORD'], verbose=False)
settings.odoo.context = {"lang": settings.LANGUAGE_CODE}
settings.odoo_models = {}
settings.deferred_m2o = {}
settings.deferred_o2m = {}
except:
logger.error('Unable to connect to a running Odoo server')
raise

logger.info("Setting up the Odoo client...")
max_retry_attempts = getattr(settings, "ODOO_MAX_RETRY_ATTEMPTS", 3)
retry_delay = getattr(settings, "ODOO_RETRY_DELAY", 5)

def _connect(retry_cnt):
try:
settings.odoo = erppeek.Client("%s:%d" % (config['HOST'], config['PORT']), db=config['DB'],
user=config['USER'], password=config['PASSWORD'], verbose=False)
settings.odoo.context = {"lang": settings.LANGUAGE_CODE}
settings.odoo_models = {}
settings.deferred_m2o = {}
settings.deferred_o2m = {}
except:
logger.warn('Failed to connect to a running Odoo server.')
logger.warn('Waiting {} [s] before the next attempt...'.format(retry_delay))
logger.warn('{} trials left...'.format(max_retry_attempts-retry_cnt))
sleep(retry_delay)
if retry_cnt < max_retry_attempts:
_connect(retry_cnt + 1)
else:
logger.error('Unable to connect to a running Odoo server. Aborting.')
mail_config = getattr(settings, "ODOO_EMAIL_NOTIFICATION", False)
mail_content = """Unable to connect to a running Odoo server. Your application may have failed to start up due to a connection problem with an Odoo instance.
Djangodoo tried to reconnect {} times, waiting {} seconds between each attempt. Still, the server could not be reached.
The problem occured with the following host configuration:
USER: {}
HOST: {}
PORT: {}
DB: {}
And here is the traceback of the exception raised during the last attempt:
{}
""".format(max_retry_attempts, retry_delay, config['USER'], config['HOST'], config['PORT'], config['DB'], traceback.format_exc())
html_content = """<p>Unable to connect to a running Odoo server. Your application may have failed to start up due to a connection problem with an Odoo instance.</p>
<p>Djangodoo tried to reconnect <b>{} times</b>, waiting <b>{} seconds</b> between each attempt. Still, the server could not be reached.</p>
<p>The problem occured with the following host configuration:</p>
<div style="border-left: 1px solid gray; padding-left: 10px;">
USER: {}<br>
HOST: {}<br>
PORT: {}<br>
DB: {}<br>
</div>
<p>And here is the traceback of the exception raised during the last attempt:</p>
<pre>
{}
</pre>
""".format(max_retry_attempts, retry_delay, config['USER'], config['HOST'], config['PORT'], config['DB'], traceback.format_exc())
if mail_config:
logger.info('Sending an email notification to the administrator...')
send_mail("APPLICATION FAILURE - DJANGODOO",
mail_content,
getattr(settings, "DEFAULT_FROM_EMAIL", "[email protected]"),
mail_config["RECIPIENTS"],
html_message=html_content,
fail_silently=False)
raise

_connect(0)


def add_extra_model_fields(sender, **kwargs):
Expand Down Expand Up @@ -57,3 +124,4 @@ def add_field(django_model, field_details):
set_auth_cache()
set_odoo_client()
class_prepared.connect(add_extra_model_fields, dispatch_uid="FQFEQ#rfq3r")
logger.info("Done initializing Djangodoo.")
10 changes: 8 additions & 2 deletions djangodoo/models.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
# -*- coding: utf-8 -*-
from django.conf import settings
from django.db import models
from django.contrib.auth.models import User
from django.core.cache import caches
import erppeek

Expand Down Expand Up @@ -37,6 +36,13 @@ def _get_odoo_fields(cls):
res = cls._odoo_fields or settings.odoo.model(cls._odoo_model).fields()
return [f for f in res if not(f in (cls._odoo_ignore_fields or []))]

@classmethod
def odoo_get_all_ids(cls, client=None):
odoo_model = cls._odoo_model
client = client or settings.odoo
ans = client.model(odoo_model).keys()
return ans

@classmethod
def odoo_load(cls, odoo_ids, client=None):
"""Loads records from Odoo
Expand Down Expand Up @@ -158,7 +164,7 @@ def odoo_push(self, fieldnames=None, client=None):


class OdooUser(models.Model):
user = models.OneToOneField(User, blank=False, related_name='odoo_user')
user = models.OneToOneField(settings.AUTH_USER_MODEL, blank=False, related_name='odoo_user')

def __init__(self, *args, **kwargs):
config = getattr(settings, "ODOO_HOST", False)
Expand Down
2 changes: 1 addition & 1 deletion setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@

setup(
name='djangodoo',
version='0.2.3',
version='0.2.5',
packages=['djangodoo'],
include_package_data=True,
license='MIT License',
Expand Down

0 comments on commit bcbbab1

Please sign in to comment.