Skip to content

Commit

Permalink
add db port to connection url
Browse files Browse the repository at this point in the history
  • Loading branch information
MJedr committed Oct 6, 2023
1 parent bf87f5a commit 0a25e38
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 1 deletion.
27 changes: 26 additions & 1 deletion matomo-api/src/api.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ def __init__(
db_password: str = None,
db_host: str = None,
db_name: str = None,
db_port: int = None
) -> None:
self.base_url = base_url or os.environ.get("MATOMO_BASE_URL")
self.auth_token = auth_token or os.environ.get("MATOMO_AUTH_TOKEN")
Expand All @@ -25,6 +26,7 @@ def __init__(
self.db_password = db_password or os.environ.get("DB_PASSWORD")
self.db_host = db_host or os.environ.get("DB_HOST")
self.db_name = db_name or os.environ.get("DB_NAME")
self.db_port = db_port or os.environ.get("DB_PORT")
if not all(
[
self.base_url,
Expand All @@ -39,7 +41,7 @@ def __init__(
raise ValueError("All the required attributes must be passed!")

def create_session(self):
database_url = f"postgresql://{self.db_name}:{self.db_password}@{self.db_host}:5432/{self.db_name}" # noqa: E501
database_url = f"postgresql://{self.db_name}:{self.db_password}@{self.db_host}:{self.db_port}/{self.db_name}" # noqa: E501
engine = create_engine(database_url)
Session = sessionmaker(bind=engine)
session = Session()
Expand Down Expand Up @@ -99,3 +101,26 @@ def fetch_inspire_statistics(self, date: date) -> None:
session.add(data_entry)
session.commit()
session.close()

from sqlalchemy import create_engine
from sqlalchemy.exc import OperationalError

def test_connection(db_name, db_password, db_host):
try:
# Construct the database URL
database_url = f"postgresql://{db_name}:{db_password}@{db_host}:5432"

# Create the engine
engine = create_engine(database_url)

# Try to connect to the database
engine.connect()

# Connection successful
return True
except OperationalError as e:
# Connection failed
print(f"Connection error: {e}")
return False

# Example usage:
1 change: 1 addition & 0 deletions matomo-api/tests/conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,7 @@ def updated_env(monkeypatch):
DB_NAME="matomo",
DB_PASSWORD="matomo",
DB_USER="matomo",
DB_PORT=5432
)
for env_name, env_value in matomo_api_kwargs.items():
monkeypatch.setenv(env_name, env_value)
Expand Down

0 comments on commit 0a25e38

Please sign in to comment.