Home > Mobile >  'NoneType' object has no attribute 'get' while serving with Waitress
'NoneType' object has no attribute 'get' while serving with Waitress

Time:10-27

I know there have been posts about this issue before but reading them I am still unable to find a solution. The weird part about this is my app has been working fine for weeks and then I reset my server and I keep getting this error.

I am using Waitress to serve an app that deals with webhooks.

@app.route(f'/outbound', methods=["POST"])
def outbound():
    data = request.json.get('data')
    to_ = data.get('payload').get('to')

The issue is in the line to_ = data.get('payload').get('to')

This exact code has been processing my webhooks for weeks, I can't understand why it just now started throwing this error.

CodePudding user response:

data dictionary doesn't have key payload or data['payload'] is might be None.

If the data dictionary doesn't have the key payload, then can silently avoid errors like this,

to_ = data.get('payload', {}).get('to')

Or a safer option will be

payload = data.get('payload')
if payload:
    to_ = payload.get('to')

CodePudding user response:

I would add input validation. It protects from wrong incoming data that can lead to bugs. From a cybersecurity point of view, it's recommended to always validate all input data, as it's a door open to malicious payload injection.

May be the Waitress framework provides some input validation facilities. Some framework do, e.g. FastAPI.

If it's not the case, you can do it by yourself. It supposes that Waitress, when encountering an exception, will return an HTTP 4xx error code.

@app.route(f'/outbound', methods=["POST"])
def outbound():
    json = request.json
    if json is None:
        raise ValueError("Missing data")
    try:
        to_ = json["payload"]["to"]
    except KeyError:
        raise ValueError("Malformed payload")
    data = request.json.get('data')
    to_ = data.get('payload').get('to')

The solution can still be improved with a function dedicated to the input validation, that eventually can become a decorator to your outbound() function.

CodePudding user response:

So apparently my webhook provider changed the way they send json without notifying anyone through email or on the website. Their docs are still using the old version. Going through all logs now to update my app.

  • Related