JSON isn't a type in Python. It is either a string, or a dictionary.
For example, your code works fine when testing a dictionary
def has_attribute(data, attribute):
return (attribute in data) and (data[attribute] is not None)
json_request = {'foo' : None, 'hello' : 'world'}
print("IT IS" if has_attribute(json_request, "foo") else "NO") # NO
print("IT IS" if has_attribute(json_request, "bar") else "NO") # NO
print("IT IS" if has_attribute(json_request, "hello") else "NO") # IT IS
Likewise, it would also work if you did import json; json_request = json.loads(some_json_string)
because that returns you a dictionary.
If you were testing a class, you would need to rewrite this using getattr()
built-in function
class A:
def __init__(self):
self.x = None
self.y = 'a'
def has_attribute(self, attribute):
return getattr(self, attribute, None) is not None
a = A()
print("IT IS" if a.has_attribute("foo") else "NO") # NO
print("IT IS" if a.has_attribute("x") else "NO") # NO
print("IT IS" if a.has_attribute("y") else "NO") # IT IS
This code is in a flask app.
- Print statements end up in the console / server logs, not the web page or in PostMan. You need to
return
a string or response object in Flask.
- See How to get POSTed json in Flask?
Here's a sample Flask app that works.
from flask import Flask, request
app = Flask(__name__)
def has_attribute(data, attribute):
return attribute in data and data[attribute] is not None
@app.route("/postit", methods=["POST"])
def postit():
json_request = request.get_json()
print(has_attribute(json_request, 'offer_id'))
return str(has_attribute(json_request, 'offer_id'))
Logs
$ FLASK_APP=app.py python -m flask run
* Serving Flask app "app"
* Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
False
127.0.0.1 - - [21/Jan/2018 14:19:10] "POST /postit HTTP/1.1" 200 -
True
127.0.0.1 - - [21/Jan/2018 14:19:25] "POST /postit HTTP/1.1" 200 -
Request & Response
$ curl -XPOST -H 'Content-Type:application/json' -d'{"offer_id":null}' http://localhost:5000/postit
False
$ curl -XPOST -H 'Content-Type:application/json' -d'{"offer_id":"data"}' http://localhost:5000/postit
True