简体   繁体   中英

Python API Upload file Post

I am trying too upload a file through an API with Python. I have almost got it but i cant seem to get the data part right. The link shows how it works and my code is under. https://bimsync.com/developers/reference/api/v2#create-revision

How i should write the code to send the data?

  def create_new_revision(self, project_id, model_id, filepath):
    with open("API_INFO.json", "r") as jsonFile:
        info = json.load(jsonFile)

    headers = {
        'Authorization': 'Bearer {}'.format(info["access_token"]),
        'Content-Type': 'application/ifc',
        "Bimsync-Params": {"callbackUri": "https://example.com",
                           "comment": "added some windows",
                           "filename": "mk.ifc",
                           "model": "{}".format(model_id)}}

    files = open("mk.ifc", "rb")
    data = {files, "mk.ifc"}

    print(headers)
    print("Createing new revision for model:")
    requests.post(r'https://api.bimsync.com/v2/projects/{}/revisions'.format(project_id), headers=headers, data=data)

2 issues:

  1. Requests needs the headers to be carefully crafted. JSON needs to be string-ified thanks to json.dumps():
    headers = { 
      'Authorization': 'Bearer {}'.format(info['access_token']),
      'Content-Type': 'application/ifc',
      'Bimsync-Params': json.dumps({'callbackUri': 'https://example.com',
          'comment': 'added some windows',
          'filename': 'NURBS.ifc',
          'model': '{}'.format(model_id)
      })
    }
  1. TheBimsync API documentation states that the IFC file content will be posted in the request body, not the file name:
    ifcfile = open("{}".format(filepath), 'r')
    data= ifcfile.read()
    ...
    result = requests.post(r'https://api.bimsync.com/v2/projects/{}/revisions'.format(project_id), headers=headers, data=data)

And voilà.

It's a bit tough to test your exact service since I don't have a token. I think you are close though. How about passing the files key?

files = {'filename': open('mk.ifc','rb')}

and then adding this to the POST

    requests.post(r'https://api.bimsync.com/v2/projects/{}/revisions'.format(project_id), headers=headers, files=files)

Hope this helps!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM