I have a Flask API endpoint that receives the following JSON:
{
"domain": "example.com",
"setting": {
"key": "frequency",
"value": 100
}
}
The value of ['setting']['key'] is set to frequency above, but there are going to be dozens of potential values. Instead of constructing a giant if...elif statement that examines the value of ['setting']['key'], I tried to do this:
json_data = request.get_json()
domain = json_data['domain']
setting_key = json_data['setting']['key']
setting_value = json_data['setting']['value']
sql_domains = Domains.query.filter_by(domain=domain).first()
sql_domains.setting_key = setting_value
# ^^^^^^^^^^^
db.session.commit()
As I have highlighted with arrows in the code, I am unable to set the SQLAlchemy key to my custom variable (setting_key). No error messages are returned, but the value in my database is not updated.
EDIT: SOLVED
Figured it out. Changed the JSON:
{
"domain": "example.com",
"settings": {
"frequency": 1000
}
}
And the code:
for key, value in json_data['settings'].items():
setattr(sql_domains, key, value)
db.session.commit()
sql_domains.setting_key = ...instead ofsql_domains.frequency = ...?