How to replace a python open command with uploaded file

I am adapting a requests based code to streamlit. In one portion of the code, they use the python open command:

# upload a file to a particular folder. Becareful that the file name fields and the model/weather fields must match!
files = [
    ('file', ('5ZoneAirCooled-v93.idf', open('job_example\\5ZoneAirCooled-v93.idf', 'rb'), 'text/plain')),
    ('file', ('in.epw', open('job_example\\in.epw', 'rb'), 'text/plain')),
    ('title', 'Python test case'),
    ('desc', 'This is test submission made from the API example for Python'),
    ('split', 'FALSE')
]

# POST with files
r = requests.post(JessApi + 'job', files=files, cookies=cookies)

In my streamlit app, I get these two files using st.file_uploader as in:

idf_uploaded_file = st.file_uploader('Upload IDF File', type='idf')
idf_name = idf_uploaded_file.name
epw_uploaded_file = st.file_uploader('Upload EPW File', type='epw')
epw_name = epw_uploaded_file.name

I tried to replace the open command with just the uploaded files, but it is not working:

# upload a file to a particular folder. Be careful that the file name fields and the model/weather fields must match!
    files = [
        ('file', (idf_name, idf_uploaded_file)),
        ('file', (epw_name, epw_uploaded_file)),
        ('title', 'Python test case'),
        ('desc', 'This is test submission made from the API example for Streamlit'),
        ('split', 'FALSE')
    ]

    # POST with files
    r = requests.post(JessApi + 'job', files=files, cookies=cookies)

What should I do to replace the python open command with the uploaded files? Thank you.

It seems I answered my own question. After a few tests, it turns out to be quite simple.

# upload a file to a particular folder. Be careful that the file name fields and the model/weather fields must match!
    files = [
        ('file', (idf_name, idf_uploaded_file, 'text/plain')),
        ('file', (epw_name, epw_uploaded_file, 'text/plain')),
        ('title', 'Python test case'),
        ('desc', 'This is test submission made from the API example for Streamlit'),
        ('split', 'FALSE')
    ]

    # POST with files
    r = requests.post(JessApi + 'job', files=files, cookies=cookies)
2 Likes

Hi @Wassim_Jabi ,

Thanks for posting this example :slight_smile: Can you share how you access the files inside the POST request function? I am having trouble with that. Thanks in advance.