Skip to content

Commit

Permalink
Refactor default database (#16)
Browse files Browse the repository at this point in the history
  • Loading branch information
kmagusiak authored Nov 2, 2022
1 parent 8ab88dd commit 74bc18e
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 18 deletions.
19 changes: 16 additions & 3 deletions odoo_connect/__init__.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import logging
import urllib.parse
from typing import Optional

Expand All @@ -19,6 +20,8 @@ def connect(
password: Optional[str] = None,
infer_parameters: bool = True,
check_connection: bool = True,
monodb: bool = False,
**kw,
) -> OdooClient:
"""Connect to an odoo database.
Expand All @@ -31,18 +34,24 @@ def connect(
Some examples for infered parameters:
- https://user:pwd@hostname/database
- mytest.odoo.com -> https://mytest.odoo.com/mytest
- localhost -> http://localhost/odoo
- mytest.dev.odoo.com -> https://mytest.dev.odoo.com/mytest
- https://admin@myserver:8069 would connect with password "admin" to the default database
:param url: The URL to the server, it may encode other information when infer_parameters is set
:param database: The database name
:param database: The database name (optional)
:param username: The username (when set, we try to authenticate the user during the connection)
:param password: The password
:param infer_paramters: Whether to infer parameters (default: True)
:param check_connection: Try to connect (default: True)
:param monodb: Allow for a db.monodb call to find the default database
(default: set when database == "@monodb")
:return: Connection object to the Odoo instance
"""
if kw:
logging.warning('Unknown connect() paramters: %s', kw.keys())
if database == '@monodb':
monodb = True
database = None
urlx = urllib.parse.urlparse(url)
if infer_parameters:
if not urlx.scheme and not urlx.netloc and urlx.path:
Expand Down Expand Up @@ -81,6 +90,10 @@ def connect(
# Create the connection
try:
client = OdooClient(url=url, database=database)
if not database:
database = client._find_default_database(monodb=monodb)
check_connection = False # no need, we already got a database
client.database = database
if username:
client.authenticate(username, password or '')
elif check_connection:
Expand Down
35 changes: 20 additions & 15 deletions odoo_connect/odoo_rpc.py
Original file line number Diff line number Diff line change
Expand Up @@ -65,10 +65,8 @@ class OdooClient:

def __init__(
self,
*,
url: str,
database: Optional[str] = None,
**_kwargs,
):
"""Create new connection."""
self.url = url
Expand All @@ -79,11 +77,8 @@ def __init__(
self._password = ''
self._uid = None
self._init_session()
if not database:
self._database = self._init_default_database()
assert self._database
logging.getLogger(__name__).info(
"Odoo connection initialized [%s], db: [%s]",
"Odoo initialized %s, db: [%s]",
self.url,
self.database,
)
Expand All @@ -93,21 +88,24 @@ def _init_session(self):
self.__json_url = urljoin(self.url, "jsonrpc")
self.session = requests.Session()

def _init_default_database(self) -> str:
"""Gets the default database from the server"""
def _find_default_database(self, *, monodb=True) -> str:
"""Find the default database from the server or raise an exception"""
log = logging.getLogger(__name__)
log.debug("Lookup the default database for [%s]", self.url)
# Get the default
# Get from monodb
try:
db = self._call("db", "monodb")
db = self._call("db", "monodb") if monodb else None
if isinstance(db, str) and db:
return db
except OdooServerError:
pass
except OdooServerError as e:
log.debug('db.monodb call failed: %s', e)
# Try to list databases
dbs = self.list_databases()
if len(dbs) == 1:
return dbs[0]
try:
dbs = self.list_databases()
if len(dbs) == 1:
return dbs[0]
except OdooServerError as e:
log.debug('db.list call failed: %s', e)
# Fail
raise OdooServerError('Cannot determine the database for [%s]' % self.url)

Expand All @@ -122,6 +120,8 @@ def authenticate(self, username: str, password: str):
if old_username:
log.info('Logged out [%s]' % self.url)
return
if not self._database:
raise OdooServerError('Missing database to connect')
user_agent_env = {} # type: ignore
self._uid = self._call(
"common",
Expand Down Expand Up @@ -277,6 +277,11 @@ def database(self, database: str):
raise ValueError('Cannot set database: None')
self.authenticate('', '') # log out first
self._database = database
logging.getLogger(__name__).info(
"Odoo %s, db: [%s]",
self.url,
self.database,
)

def __getitem__(self, model: str) -> "OdooModel":
"""Alias for get_model"""
Expand Down

0 comments on commit 74bc18e

Please sign in to comment.