0

This function needs to send a JSON dict in python2.7 as a "file" using a post request but the script is running in a container and cannot write to disk.

The endpoint also cannot be changed to accept JSON, rather than a file, as its part of a larger project.

def _json_to_bucket(request_json, thing_id):
    import json
    import requests

    request_url = "https://backend.com/thing/{}".format(thing_id)

    data = {
        'name': 'thing-{}'.format(datetime.isoformat(datetime.now())),
        'url': '/thing_importer/',
        'files': [json.loads(request_json)]
    }
    requests.post(request_url, data=data)

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
  • Welcome. It's not clear what are you trying to do. In your example `data['files']` will contain list with single element which is object parsed from json string passed in `request_json` value. – Olvin Roght Jun 10 '20 at 16:51
  • Hello, sorry for making it not clear. if i used ```files: [open('test.json')]``` I think it would work. Normally I would save the dict "data" as a json file. Then open it using the example line. edit: hit enter by mistake my typing – Stuart Cox Jun 10 '20 at 18:11
  • You can use `json.load(f)` but how do you want to send this data to server? – Olvin Roght Jun 10 '20 at 18:13
  • (made an edit after your reply). So simply put how to I convert a python dict into a python file object without ever writing to a file? I have the dict and need to covert it to a file object that you would normally obtain from doing ```open('test.json', 'r')``` – Stuart Cox Jun 10 '20 at 18:19
  • Let's start from scratch. Why do you need that? – Olvin Roght Jun 10 '20 at 18:32
  • why do you use `json.loads()` ? it converts JSON string to python structure. Maybe you should send `files: request_json` – furas Jun 10 '20 at 19:58
  • BTW: how about `requests.post( ...., files=...)` ? – furas Jun 10 '20 at 20:00
  • BTW: first you could send requests to use http://httpbin.org/post and it will send back all data which it gets - and you can see if you send correctly formated request. – furas Jun 10 '20 at 20:02
  • BTW: you can use `io.String(request_json)` to create file-like object - so maybe you need `"files": [ io.String(request_json) ]` – furas Jun 10 '20 at 20:03
  • `requests` *doesn't need a file*. Nor does the endpoint you are posting to (a remote server can't read your filesystem). It needs data in a certain format; perhaps they are expecting [a `multipart/form-data` post body](https://stackoverflow.com/questions/8659808/how-does-http-file-upload-work)? Then just send a `files=...` mapping with a `io.BytesIO()` object. – Martijn Pieters Jul 09 '20 at 12:00
  • Here is a sample answer that uses that technique: [File-like data sent using python requests](https://stackoverflow.com/a/59483564) – Martijn Pieters Jul 09 '20 at 12:02

0 Answers0