0

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()
2
  • So you want to do sql_domains.setting_key = ... instead of sql_domains.frequency = ... ? Commented Apr 19, 2020 at 20:57
  • Yes, correct! That why I don't have to know the target setting @GordThompson Commented Apr 20, 2020 at 12:56

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.