Home > front end >  Python f-string not formatted correctly for dict with variables
Python f-string not formatted correctly for dict with variables

Time:05-04

I have a payload for an API call, like so:

start_period = "2022-05-02"
end_period = "2022-05-02"

payload = {"period": f"{{'p1': [{{'type': 'D', 'start': '{start_period}', 'end': '{end_period}'}}]}}",
               "max-results": 50,
               "page-num": 1,
               "options": {}
               }

When I send this payload, I retrieve a HTTP 403 error. The payload's period when debugging in PyCharm looks like:

'{\'p1\': [{\'type\': \'D\', \'start\': \'2022-05-02\', \'end\': \'2022-05-02\'}]}'

or within the dict itself (again in PyCharm Debugger):

{'period': "{'p1': [{'type': 'D', 'start': '2022-05-02', 'end': '2022-05-02'}]}", 'max-results': 50, 'page-num': 1, 'options': {}}

It should look like this:

{"period": {"p1": [{"type": "D", "start": "2022-05-02", "end": "2022-05-02"}]}, "max-results": 50, "page-num": 1, 'options': {}}

(note the extra quotation marks wrapping around the entire period). I'm not sure if the single quotations are throwing this error. Is my current f-string correct?

CodePudding user response:

Those quotes indicate it's a string. It's appearing as a string in the transfer data because it's a string in payload.

If you're using something to convert the payload to JSON for transfer, don't pre-encode the "period" portion. If you do, the JSON formatter will then encode that entire portion as a string, rather than as objects & arrays. Instead, use Python dicts & arrays and let the JSON formatter handle the conversion.

payload = {
    "period": {
        'p1': [{
            'type': 'D',
            'start': start_period,
            'end': end_period
        }]
    },
    "max-results": 50,
    "page-num": 1,
    "options": {},
}

json.dumps(payload)
  • Related