I'm new to python and I am sure there's a better way to do this. For my specific issue I have stored an API key. I've given the user means to send an argument with a new API key if needed. Otherwise the argument is set as False
. So if the user sends an API key, I first want to find out if it's different from the one I already have. And if it is different I then want to update it in my secret manager.
There's one addtl layer of possible complication. It's a header in a webhook.
So I'm writing an if
function but it feels very inelegant. This is what I currently have written. I'm also using Flask, hence request
.
This is my code:
if request.headers['x-api-key'] and request.headers['x-api-key'] not in stored_api_key:
# do something
Would love to know how I should be writing this. Thank you.
CodePudding user response:
Flask's request.headers
acts like a dictionary, and so if you do
request.headers['x-api-key']
And the key x-api-key
does not exist in the user's request, this will throw an error. Similar to dict
, you can use the .get()
method to default to a value in the case it does not exist. In this case, your code would look like so:
api_key = request.headers.get('x-api-key')
if api_key and api_key not in stored_api_key:
# do something
Otherwise, you must do the following:
if 'x-api-key' in request.headers and request.headers['x-api-key'] not in stored_api_key:
CodePudding user response:
I wouldn't try to jam this into a single if statement. You have two checks where one check can use the output of the last. IMO it reads much more clearly to me to have two if statements. You could use an assignment expression to help simplify your logic:
if api_key := request.headers.get('x-api-key'):
if api_key not in stored_api_key:
...
The first if
assigns api_key
and checks for truthiness. get
is used to avoid KeyError
s. The second if
uses the value from above where we know api_key
is not None
.
You could also one liner this if you really want to, but is definitely less readable:
if (key := request.headers.get('x-api-key')) and key not in stored_api_key:
...