Reputation: 3028
I have a JSON POST data that a user is going to send me every time to fetch some data from a third party service.I plan to cache the data based on user_id so that I don't keep inserting the data each time the user requests for something.Below is the POST data that user is going to send me everytime
{
"scope_id": "user1",
"tool_id": "appdynamics",
"api_id": "get metrics",
"input_params": {"user": "*********", "pwd": "*********", "acc_id": "**********", "app_id": "TestApp", "metric-path": "ars",
"time-range-type": "BEFORE_NOW", "duration-in-mins": 60},
"output_filters": {}
}
Below is my code snipped to handle the update of the data
def post(self, name):
data = ServiceAPI.parser.parse_args()
print("First data", data)
scope_id = data["scope_id"]
tool_id = data["tool_id"]
api_id = data["api_id"]
input_params = data["input_params"]
output_filter = data["output_filter"]
# if the user passes the credentials, insert it into the database otherwise use the last known credentials
# ensure you only insert valid credentials
if all([scope_id, tool_id, api_id]) and all([input_params.values()]):
users.update({scope_id: [tool_id, api_id, input_params, datetime.now().strftime('%Y-%m-%d %H:%M:%S')]},
{scope_id: [tool_id, api_id, input_params, datetime.now().strftime('%Y-%m-%d %H:%M:%S')]}, upsert=True)
print("Cache", list(users.find({})))
status_code, response = api_executor(scope_id, tool_id, api_id)
if status_code == 200:
return {"message": response}, status_code
return {"message": "Please enter correct credentials"}, status_code
However I keep getting the same data inserted into my database and update doesn't seem to work.How can I fix this?
Note: This is a flask app and I suggest not to get into the details of the implementation.I just need to update the given POST data each time and not insert it.
Upvotes: 0
Views: 44
Reputation: 38982
The selector used in your update query i.e. {'scope_id': [tool_id, api_id, input_params, datetime.now().strftime('%Y-%m-%d %H:%M:%S')]}
never matches any existing documents.
This is because it checks for a document whose scope_id
is an array consisting of the current time.
Use:
selector = {'scope_id': {'$all': [tool_id, api_id, input_params]}}
update = {
'scope_id': [
tool_id, api_id, input_params,
datetime.now().strftime('%Y-%m-%d %H:%M:%S')
]
}
users.update(selector, update, upsert=True)
Upvotes: 1