[Tutor] cgi module help

rmlibre at riseup.net rmlibre at riseup.net
Mon Aug 12 18:11:27 EDT 2019


I have a question about the cgi module. 

I'm trying to retrieve post data as a nested dictionary from client
code. 

For instance:



"""client code"""
from requests import sessions
from datetime import datetime

session = sessions.Session()
date = str(datetime.now())
msg_id = 0001
message = {"metadata": {"date": date, "id": msg_id}}
session.post(data=message)



"""server cgi script"""
import cgi

form = cgi.FieldStorage()
metadata = form["metadata"]
print(metadata)
>>> ["date", "id"]

for item in form.list:
    print(f"{item}\n{item.name}\n{item.value}\n")

>>> MiniFieldStorage('metadata', 'date')
>>> metadata 
>>> date
>>> 
>>> MiniFieldStorage('metadata', 'id')
>>> metadata
>>> id
>>> 


My issue is the FieldStorage class doesn't seem to store the values
within metadata, it only stores the key of each element within the
nested dictionary. And it constructs MiniFieldStorage objects with
attributes such as .name == "metadata" and .value == "date". 

But I need the actual values, not just the name of the element. Any idea
how I can maintain this nested structure and retrieve the data within a
nested dictionary in an elegant way?

Constraints: 
For simplicity, I omitted the actual payload which is also a nested
dictionary that goes two levels deep. I'm searching for a solution
that's extensible enough to include such fields as well.


More information about the Tutor mailing list