Exit early after each request check

Keeps the "happy path" on the function's base indentation level.

Avoids carrying status and return value variables, pre-filled in
anticipation of an error, along.
This commit is contained in:
Jochen Kupperschmidt 2020-12-27 14:50:52 +01:00
parent 139ec1670c
commit 78b9533e2b

View file

@ -33,16 +33,19 @@ async def handler(request):
This one handles a POST, checks its content, and forwards it to the matrix room. This one handles a POST, checks its content, and forwards it to the matrix room.
""" """
data = await request.read() data = await request.read()
try: try:
data = json.loads(data.decode()) data = json.loads(data.decode())
status, ret = HTTPStatus.BAD_REQUEST, 'I need a json dict with text & key'
except json.decoder.JSONDecodeError: except json.decoder.JSONDecodeError:
data = {} return create_json_response(HTTPStatus.BAD_REQUEST, 'Invalid JSON')
status, ret = HTTPStatus.BAD_REQUEST, 'This was not valid JSON'
if all(key in data for key in ['text', 'key']): if not all(key in data for key in ['text', 'key']):
status, ret = HTTPStatus.UNAUTHORIZED, 'I need the good "key"' return create_json_response(HTTPStatus.BAD_REQUEST,
if data['key'] == API_KEY: 'Missing text and/or API key property')
status, ret = HTTPStatus.OK, 'OK'
if data['key'] != API_KEY:
return create_json_response(HTTPStatus.UNAUTHORIZED, 'Invalid API key')
room_id = str(request.rel_url)[1:] room_id = str(request.rel_url)[1:]
content = { content = {
"msgtype": "m.text", "msgtype": "m.text",
@ -56,7 +59,7 @@ async def handler(request):
await CLIENT.login(MATRIX_PW) await CLIENT.login(MATRIX_PW)
await send_room_message(room_id, content) await send_room_message(room_id, content)
return create_json_response(status, ret) return create_json_response(HTTPStatus.OK, 'OK')
def create_json_response(status, ret): def create_json_response(status, ret):