Skip to content

Commit

Permalink
Merge pull request #11 from miztch:refactor
Browse files Browse the repository at this point in the history
some refactoring with query matches and logging
  • Loading branch information
miztch authored Oct 7, 2023
2 parents 1523f1a + c0de522 commit 48d4020
Show file tree
Hide file tree
Showing 5 changed files with 77 additions and 46 deletions.
6 changes: 6 additions & 0 deletions .vscode/settings.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
{
"[python]": {
"editor.defaultFormatter": "ms-python.black-formatter",
"editor.formatOnSave": true
}
}
47 changes: 18 additions & 29 deletions api/app.py
Original file line number Diff line number Diff line change
@@ -1,50 +1,39 @@
import re
from datetime import datetime
from chalice import Chalice
from chalicelib import database
from chalicelib import database, date_format, log

app = Chalice(app_name='dima')
logger = log.getLogger()

app = Chalice(app_name="dima")

@app.route('/')

@app.route("/")
def index():
'''
"""
return fixed response.
'''
return {'status': 200, 'message': 'Remember, bullets hurt.'}
"""
return {"status": 200, "message": "Remember, bullets hurt."}


@app.route('/matches')
@app.route("/matches")
def matches():
'''
"""
return upcoming matches list.
'''
"""
request = app.current_request
app.log.debug('Request: {}'.format(request.to_dict()))
logger.debug("Request: {}".format(request.to_dict()))

# default date for search: today
date = datetime.strftime(datetime.now(), '%Y-%m-%d')
date = date_format.get_default()

if request.query_params:
param = request.query_params.get('date')
param = request.query_params.get("date")

# validate date format of query parameter (YYYY-mm-dd)
# if invalid, parameter date -> today.
pattern = '^(?!([02468][1235679]|[13579][01345789])00-02-29)(([0-9]{4}-(01|03|05|07|08|10|12)-(0[1-9]|[12][0-9]|3[01]))|([0-9]{4}-(04|06|09|11)-(0[1-9]|[12][0-9]|30))|([0-9]{4}-02-(0[1-9]|1[0-9]|2[0-8]))|([0-9]{2}([02468][048]|[13579][26])-02-29))$'

try:
if re.fullmatch(pattern, param) is not None:
app.log.debug(
'Date format in query parameter is valid. input: {}'.format(param))
date = param
else:
app.log.debug(
'Date format in query parameter is invalid or empty. input: {}'.format(param))
except TypeError:
app.log.debug(
'query parameter with invalid format given. input: {}'.format(param))
# if format is valid, overwrite date with parameter
if param and date_format.validate(param):
date = param

matches = database.query(date)
app.log.debug('Return {} items.'.format(len(matches)))
logger.debug("Return {} items.".format(len(matches)))

return matches
32 changes: 15 additions & 17 deletions api/chalicelib/database.py
Original file line number Diff line number Diff line change
@@ -1,35 +1,33 @@
import logging
import os

import boto3
from boto3.dynamodb.conditions import Key, Attr
from chalicelib import log

logger = logging.getLogger()
logger.setLevel(logging.INFO)
logger = log.getLogger()


def _get_table():
dynamodb = boto3.resource('dynamodb')
table = dynamodb.Table(os.environ['TABLE_NAME'])
dynamodb = boto3.resource("dynamodb")
table = dynamodb.Table(os.environ["TABLE_NAME"])

return table


def query(date):
'''
"""
scan DynamoDB table by following condition.
- 'startTime' begins with $date
'''
"""
table = _get_table()

logger.info('Query table. date: {}'.format(date))
response = table.scan(
FilterExpression=Attr('startTime').begins_with(date)
)
logger.info("Query table. date: {}".format(date))
response = table.scan(FilterExpression=Attr("startTime").begins_with(date))

if response['Items']:
for item in response['Items']:
item['id'] = int(item['id'])
item['bestOf'] = int(item['bestOf'])
if response["Items"]:
for item in response["Items"]:
item["id"] = int(item["id"])
item["bestOf"] = int(item["bestOf"])

logger.info('Found {} items.'.format(len(response['Items'])))
return response['Items']
logger.info("Found {} items.".format(len(response["Items"])))
return response["Items"]
27 changes: 27 additions & 0 deletions api/chalicelib/date_format.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
import re
from datetime import datetime

from chalicelib import log

logger = log.getLogger()


def validate(date):
"""
Validate date format (YYYY-mm-dd).
"""
pattern = "^(?!([02468][1235679]|[13579][01345789])00-02-29)(([0-9]{4}-(01|03|05|07|08|10|12)-(0[1-9]|[12][0-9]|3[01]))|([0-9]{4}-(04|06|09|11)-(0[1-9]|[12][0-9]|30))|([0-9]{4}-02-(0[1-9]|1[0-9]|2[0-8]))|([0-9]{2}([02468][048]|[13579][26])-02-29))$"

if re.fullmatch(pattern, date) is not None:
logger.debug("Date format is valid. input: {}".format(date))
return True
else:
logger.debug("Date format is invalid or empty. input: {}".format(date))
return False


def get_default():
"""
Get the default date for search: today.
"""
return datetime.strftime(datetime.now(), "%Y-%m-%d")
11 changes: 11 additions & 0 deletions api/chalicelib/log.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
import logging


def getLogger():
"""
init logger.
"""
logger = logging.getLogger()
logger.setLevel(logging.INFO)

return logger

0 comments on commit 48d4020

Please sign in to comment.