Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: Add PostgreSQL Healtcheck HTTP server #1

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions .env.dist
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
#!/usr/bin/env bash

export DATABASE_HOST="localhost"
export DATABASE_PORT="5432"
export DATABASE_NAME="d4g"
export DATABASE_USER="d4guser"
export DATABASE_PASSWORD="d4gpassword"
4 changes: 3 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -160,4 +160,6 @@ dmypy.json
cython_debug/

# Precommit hooks: ruff cache
.ruff_cache
.ruff_cache
.env*
!.env.dist
18 changes: 18 additions & 0 deletions main.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
from http.server import HTTPServer

from peer_session import upserver

host_name = "localhost"
server_port = 8080

if __name__ == "__main__":
web_server = HTTPServer((host_name, server_port), upserver.UpServer)
print(f"Server listening http://{host_name}:{server_port}")

try:
web_server.serve_forever()
except KeyboardInterrupt:
pass

web_server.server_close()
print("Server stopped.")
File renamed without changes.
50 changes: 50 additions & 0 deletions peer_session/db.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
import logging
import os
import time

import psycopg2


class DB:
def __init__(self) -> None:
self.connection = None
self.configure()
self.connect()

def configure(self) -> None:
"""Configure the connection to the database."""
self.database_host = os.environ.get("DATABASE_HOST")
self.database_port = os.environ.get("DATABASE_PORT")
self.database_name = os.environ.get("DATABASE_NAME")
self.database_user = os.environ.get("DATABASE_USER")
self.database_password = os.environ.get("DATABASE_PASSWORD")

logging.debug(f"Connecting to host {self.database_host}")
logging.debug(f"port : {self.database_port}")
logging.debug(f"database : {self.database_name}")
logging.debug(f"user : {self.database_user}")

def connect(self) -> None:
"""Connect to a PostgreSQL database."""
try:
if self.connection is None:
self.connection = psycopg2.connect(
database=self.database_name,
user=self.database_user,
password=self.database_password,
host=self.database_host,
port=self.database_port,
)
except psycopg2.DatabaseError:
logging.exception
finally:
logging.info("Database connection opened successfully.")

def healthcheck(self) -> float:
"""Make sure the Postgres database is reachable."""
start_time = time.perf_counter()
self.connection.cursor().execute("SELECT 1")
end_time = time.perf_counter()

elapsed_time = round((end_time - start_time) * 1000, 3)
return elapsed_time
32 changes: 32 additions & 0 deletions peer_session/upserver.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
from http.server import BaseHTTPRequestHandler

from peer_session.db import DB


class UpServer(BaseHTTPRequestHandler):
def do_get(self) -> None:
if self.path == "/up":
self.do_UP()
return

self.send_response(420)
self.send_header("Content-type", "text/html")
self.end_headers()
self.wfile.write(
bytes("He who breaks a thing has lost the path of wisdom.", "utf-8"),
)

def do_up(self) -> None:
database = DB()
try:
time_ms = database.healthcheck()
self.send_response(200)
self.send_header("Content-type", "json")
self.end_headers()
self.wfile.write(bytes(f'{{"up": true, "time": "{time_ms}ms"}}', "utf-8"))
except Exception:
self.send_response(500)
self.send_header("Content-type", "json")
self.end_headers()
self.wfile.write(bytes('{"up": false, "time": 0}', "utf-8"))
return
86 changes: 84 additions & 2 deletions poetry.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

11 changes: 4 additions & 7 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -3,19 +3,16 @@ requires = ["poetry-core"]
build-backend = "poetry.core.masonry.api"

[tool.poetry]
name = "python_template"
name = "peer-session"
version = "0.1.0"
description = "Template"
description = "This repository is purely for educational purposes."
authors = ["DataForGood"]
license = " MIT"
license = "MIT"
readme = "README.md"

[tool.poetry.dependencies]
python = "^3.10"
# numpy = "^1.21.1"
# pandas = "^1.1.1"
# jupyter = "^1.0.0"
# ipykernel = "^5.3.4"
psycopg2-binary = "^2.9.9"

[tool.poetry.group.dev.dependencies]
pre-commit = "^2.20.0"
Expand Down
Empty file removed python_template/.empty
Empty file.
Loading