Skip to content

Commit

Permalink
Project dependencies update (#70)
Browse files Browse the repository at this point in the history
* Migrated Python version to 3.10

* Cleaned up and restructured dependencies

* Added pre commit hooks

* Ran black formatter

* Made setting up MySQLConnector optional

* Updated project requirements

* updated python version in references

* Incremented subversion
  • Loading branch information
NeonKirill authored Sep 30, 2023
1 parent 020ccd7 commit b7ec0c3
Show file tree
Hide file tree
Showing 77 changed files with 3,446 additions and 2,347 deletions.
4 changes: 2 additions & 2 deletions .github/workflows/publish_release.yml
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ jobs:
- name: Setup Python
uses: actions/setup-python@v1
with:
python-version: 3.8
python-version: '3.10'
- name: Install Build Tools
run: |
python -m pip install build wheel
Expand All @@ -37,4 +37,4 @@ jobs:
- name: Publish to Test PyPI
uses: pypa/gh-action-pypi-publish@master
with:
password: ${{secrets.PYPI_TOKEN}}
password: ${{secrets.PYPI_TOKEN}}
2 changes: 1 addition & 1 deletion .github/workflows/publish_test_build.yml
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ jobs:
- name: Setup Python
uses: actions/setup-python@v1
with:
python-version: 3.8
python-version: '3.10'
- name: Install Build Tools
run: |
python -m pip install build wheel
Expand Down
5 changes: 3 additions & 2 deletions .github/workflows/unit_tests.yml
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ jobs:
unit_tests:
strategy:
matrix:
python-version: [ '3.8', '3.9' ]
python-version: [ '3.10' ]
max-parallel: 1
runs-on: ubuntu-latest
env:
Expand All @@ -24,6 +24,7 @@ jobs:
python -m pip install --upgrade pip
pip install -r requirements/requirements.txt
pip install -r requirements/test_requirements.txt
pip install -r requirements/legacy_migration_requirements.txt
- name: Get Credential
run: |
mkdir -p ~/.local/share/neon
Expand Down Expand Up @@ -51,7 +52,7 @@ jobs:
- name: Setup Python
uses: actions/setup-python@v1
with:
python-version: 3.8
python-version: '3.10'
- name: Install Build Tools
run: |
python -m pip install build wheel
Expand Down
16 changes: 16 additions & 0 deletions .pre-commit-config.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
repos:
- repo: https://github.com/pre-commit/pre-commit-hooks
rev: v2.3.0
hooks:
- id: check-yaml
- id: check-json
- id: check-symlinks
- id: end-of-file-fixer
- id: trailing-whitespace
- id: pretty-format-json
- id: requirements-txt-fixer
- id: sort-simple-yaml
- repo: https://github.com/psf/black
rev: 22.10.0
hooks:
- id: black
11 changes: 7 additions & 4 deletions chat_client/__main__.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,10 @@
from chat_client.wsgi import app


if __name__ == '__main__':
uvicorn.run(app=app, host=os.environ.get('HOST', '127.0.0.1'),
port=int(os.environ.get('PORT', 8001)),
log_level=os.environ.get('LOG_LEVEL', 'INFO').lower())
if __name__ == "__main__":
uvicorn.run(
app=app,
host=os.environ.get("HOST", "127.0.0.1"),
port=int(os.environ.get("PORT", 8001)),
log_level=os.environ.get("LOG_LEVEL", "INFO").lower(),
)
65 changes: 42 additions & 23 deletions chat_client/app.py
Original file line number Diff line number Diff line change
Expand Up @@ -47,65 +47,84 @@
sys.path.append(os.path.pardir)
sys.path.append(os.path.dirname(os.path.abspath(__file__)))

from .blueprints import base as base_blueprint, \
chat as chat_blueprint, \
components as components_blueprint
from .blueprints import (
base as base_blueprint,
chat as chat_blueprint,
components as components_blueprint,
)


def create_app() -> FastAPI:
"""
Application factory for the Klatchat Client
Application factory for the Klatchat Client
"""
app_version = get_version('chat_client/version.py')
LOG.name = os.environ.get('LOG_NAME', 'client_err')
LOG.base_path = os.environ.get('LOG_BASE_PATH', '.')
LOG.init(config={'level': os.environ.get('LOG_LEVEL', 'INFO'), 'path': os.environ.get('LOG_PATH', os.getcwd())})
logger = LOG.create_logger('chat_client')
app_version = get_version("chat_client/version.py")
LOG.name = os.environ.get("LOG_NAME", "client_err")
LOG.base_path = os.environ.get("LOG_BASE_PATH", ".")
LOG.init(
config={
"level": os.environ.get("LOG_LEVEL", "INFO"),
"path": os.environ.get("LOG_PATH", os.getcwd()),
}
)
logger = LOG.create_logger("chat_client")
logger.addHandler(logging.StreamHandler())
LOG.info(f'Starting Klatchat Client v{app_version}')
chat_app = FastAPI(title="Klatchat Client",
version=app_version)
LOG.info(f"Starting Klatchat Client v{app_version}")
chat_app = FastAPI(title="Klatchat Client", version=app_version)

@chat_app.middleware("http")
async def log_requests(request: Request, call_next):
"""Logs requests and gracefully handles Internal Server Errors"""
idem = ''.join(random.choices(string.ascii_uppercase + string.digits, k=6))
idem = "".join(random.choices(string.ascii_uppercase + string.digits, k=6))
LOG.info(f"rid={idem} start request path={request.url.path}")
start_time = time.time()
try:
response = await call_next(request)
process_time = (time.time() - start_time) * 1000
formatted_process_time = '{0:.2f}'.format(process_time)
LOG.info(f"rid={idem} completed_in={formatted_process_time}ms status_code={response.status_code}")
formatted_process_time = "{0:.2f}".format(process_time)
LOG.info(
f"rid={idem} completed_in={formatted_process_time}ms status_code={response.status_code}"
)
return response
except ConnectionError as ex:
LOG.error(ex)
from .client_config import app_config
return Response(f'Connection error : {app_config["SERVER_URL"]}', status_code=404)

return Response(
f'Connection error : {app_config["SERVER_URL"]}', status_code=404
)
except Exception as ex:
LOG.error(f"rid={idem} received an exception {ex}")
return Response(f'Chat server error occurred', status_code=500)
return Response(f"Chat server error occurred", status_code=500)

# Redirects any not found pages to chats page
@chat_app.exception_handler(StarletteHTTPException)
async def custom_http_exception_handler(request, exc):
if exc.status_code == status.HTTP_404_NOT_FOUND:
return RedirectResponse("/chats")

__cors_allowed_origins = os.environ.get('COST_ALLOWED_ORIGINS', '') or '*'
__cors_allowed_origins = os.environ.get("COST_ALLOWED_ORIGINS", "") or "*"

LOG.info(f'CORS_ALLOWED_ORIGINS={__cors_allowed_origins}')
LOG.info(f"CORS_ALLOWED_ORIGINS={__cors_allowed_origins}")

chat_app.add_middleware(
CORSMiddleware,
allow_origins=__cors_allowed_origins.split(','),
allow_origins=__cors_allowed_origins.split(","),
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
static_suffix = '/build' if os.environ.get('KLAT_ENV', 'dev').upper() == 'PROD' else ''
chat_app.mount("/css", StaticFiles(directory=f"chat_client/static/css{static_suffix}"), name="css")
chat_app.mount("/js", StaticFiles(directory=f"chat_client/static/js{static_suffix}"), name="js")
static_suffix = (
"/build" if os.environ.get("KLAT_ENV", "dev").upper() == "PROD" else ""
)
chat_app.mount(
"/css",
StaticFiles(directory=f"chat_client/static/css{static_suffix}"),
name="css",
)
chat_app.mount(
"/js", StaticFiles(directory=f"chat_client/static/js{static_suffix}"), name="js"
)
chat_app.mount("/img", StaticFiles(directory=f"chat_client/static/img"), name="img")

chat_app.include_router(base_blueprint.router)
Expand Down
61 changes: 28 additions & 33 deletions chat_client/blueprints/auth.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,24 +35,22 @@

router = APIRouter(
prefix="/auth",
responses={'404': {"description": "Unknown endpoint"}},
responses={"404": {"description": "Unknown endpoint"}},
)


@router.post("/login", response_class=JSONResponse)
async def login(username: str = Form(...),
password: str = Form(...)):
async def login(username: str = Form(...), password: str = Form(...)):
"""
Forwards input login data to the Server API endpoint and handles the returned response
Forwards input login data to the Server API endpoint and handles the returned response
:param username: posted Form Data username param
:param password: posted Form Data password param
:param username: posted Form Data username param
:param password: posted Form Data password param
:returns Response object depending on returned status with refreshed session cookies if status_code == 200
:returns Response object depending on returned status with refreshed session cookies if status_code == 200
"""

data = dict(username=username,
password=password)
data = dict(username=username, password=password)

post_response = requests.post(f'{app_config["SERVER_URL"]}/auth/login', data=data)

Expand All @@ -61,38 +59,37 @@ async def login(username: str = Form(...),
response = JSONResponse(content=json_data, status_code=post_response.status_code)

if post_response.status_code == 200:

for cookie in post_response.cookies:

response.delete_cookie('session')
response.delete_cookie("session")

response.set_cookie(key=cookie.name, value=cookie.value, httponly=True)

LOG.info(f'Login response for {username}: {json_data}')
LOG.info(f"Login response for {username}: {json_data}")

return response


@router.post("/signup", response_class=JSONResponse)
async def signup(nickname: str = Form(...),
first_name: str = Form(...),
last_name: str = Form(...),
password: str = Form(...)):
async def signup(
nickname: str = Form(...),
first_name: str = Form(...),
last_name: str = Form(...),
password: str = Form(...),
):
"""
Forwards new user signup data to the Server API endpoint and handles the returned response
Forwards new user signup data to the Server API endpoint and handles the returned response
:param nickname: posted Form Data nickname param
:param first_name: posted Form Data first name param
:param last_name: posted Form Data last name param
:param password: posted Form Data password param
:param nickname: posted Form Data nickname param
:param first_name: posted Form Data first name param
:param last_name: posted Form Data last name param
:param password: posted Form Data password param
:returns Response object depending on returned status with refreshed session cookies if status_code == 200
:returns Response object depending on returned status with refreshed session cookies if status_code == 200
"""

data = dict(nickname=nickname,
first_name=first_name,
last_name=last_name,
password=password)
data = dict(
nickname=nickname, first_name=first_name, last_name=last_name, password=password
)

post_response = requests.post(f'{app_config["SERVER_URL"]}/auth/signup', data=data)

Expand All @@ -101,13 +98,12 @@ async def signup(nickname: str = Form(...),
response = JSONResponse(content=json_data, status_code=post_response.status_code)

if post_response.status_code == 200:

response.delete_cookie('session')
response.delete_cookie("session")

for cookie in post_response.cookies:
response.set_cookie(key=cookie.name, value=cookie.value, httponly=True)

LOG.info(f'Signup response for {nickname}: {json_data}')
LOG.info(f"Signup response for {nickname}: {json_data}")

return response

Expand All @@ -123,12 +119,11 @@ async def logout():
response = JSONResponse(content=json_data, status_code=logout_response.status_code)

if logout_response.status_code == 200:

response.delete_cookie('session')
response.delete_cookie("session")

for cookie in logout_response.cookies:
response.set_cookie(key=cookie.name, value=cookie.value, httponly=True)

LOG.info(f'Logout response: {json_data}')
LOG.info(f"Logout response: {json_data}")

return response
6 changes: 3 additions & 3 deletions chat_client/blueprints/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,16 +33,16 @@

router = APIRouter(
prefix="/base",
responses={'404': {"description": "Unknown endpoint"}},
responses={"404": {"description": "Unknown endpoint"}},
)


@router.get("/runtime_config", response_class=JSONResponse)
async def fetch_runtime_config():
"""Fetches runtime config from local JSON file in provided location"""
try:
runtime_configs = app_config.get('RUNTIME_CONFIG', {})
runtime_configs = app_config.get("RUNTIME_CONFIG", {})
except Exception as ex:
LOG.error(f'Exception while fetching runtime configs: {ex}')
LOG.error(f"Exception while fetching runtime configs: {ex}")
runtime_configs = {}
return JSONResponse(content=runtime_configs)
Loading

0 comments on commit b7ec0c3

Please sign in to comment.