在JSON中指定文件内容

2024-10-03 06:32:49 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在使用一个API,它要求指定要上载到API的文件(在我的例子中是Excel)。文档指定:JSON Property=file,Data Type=FileUpload。我的问题:什么是FileUpload。我试着简单地指定文件名(例如c:\test\数据.xls)但很明显这是行不通的。在

我正在为FastField移动表单使用API(www.fastfield.com网站). 文档显示在屏幕截图中,以及代码和结果。不知何故,我没有正确地将文件数据发布到API。在

API Documentation

这就是我试图运行的Python代码

import requests
import json
from requests.auth import HTTPBasicAuth
import base64

 # Get session token, this must be specified in header of subsequent request and returns a JSON object ready for insertion into header
rqstResponse = requests.post('https://manage.fastfieldforms.com/api/authenticate', auth=HTTPBasicAuth('***', '***'))
jsonObj = json.loads(rqstResponse.content)
sessionToken = jsonObj['data']['sessionToken']
headers = {'X-Gatekeeper-SessionToken': sessionToken}

# run this code to get listIds - which are hard coded further down
rqstResponse = requests.get("https://manage.fastfieldforms.com/api/globallists", headers=headers)
print (rqstResponse.content)
del rqstResponse

# Read file and convert to binary string
filePath = r"J:\Properties\PropGIS\proj\20150820140457_TelecoMapping\data\Survey_Feb17\FastField_Test01.xlsx"
with open(filePath, 'r') as f:
    filecontents = f.read()
fileDataEncoded = base64.b64encode(filecontents)

# create JSON
payloadDictObj = {}
payloadDictObj['file'] = fileDataEncoded
payloadDictObj['id'] = "03c804cb-b983-4e4c-956b-96ac23da16b2"
#payloadDictObj['listname'] = "Test02"
serializedJsonStr = json.dumps(payloadDictObj)
print serializedJsonStr

# Update Global List
rqstResponse = requests.post("https://manage.fastfieldforms.com/api//globallist", data=serializedJsonStr, headers=headers)
print (rqstResponse.content)
del rqstResponse
# --------------------
# Response
{
  "code": 200,
  "data": {
    "searchResults": [
      {
        "id": 7793,
        "accountId": 43600,
        "name": "Test01",
        "active": true,
        "createdAt": "2017-05-24T06:37:28.49Z",
        "updatedAt": "2017-05-24T06:37:28.49Z",
        "version": 1,
        "listId": "03c804cb-b983-4e4c-956b-96ac23da16b2",
        "path": "{ bucket:'fastfield-globallists', key:'43600/ca4b89df75db4ef8b513d15d59f654d8.csv'}"
      }
    ]
  }
}
{"id": "03c804cb-b983-4e4c-956b-96ac23da16b2", "file": "UEsDB...qaJXQ=="}
{
  "code": 403,
  "error": "listname name is required",
  "data": {}
}

Tags: httpsimportcomapijsondatamanagerequests
1条回答
网友
1楼 · 发布于 2024-10-03 06:32:49

好吧。为了它的价值。这就是我最终成功的原因。我现在意识到,这个问题更多的是关于我对Python请求模块的理解,或者缺乏理解。在

import requests
import json
from requests.auth import HTTPBasicAuth
import base64

# Get session token, this must be specified in header of subsequent request and returns a JSON object ready for insertion into header
rqstResponse = requests.post('https://manage.fastfieldforms.com/api/authenticate', auth=HTTPBasicAuth('XXX', 'XXX'))
jsonObj = json.loads(rqstResponse.content)
sessionToken = jsonObj['data']['sessionToken']
headers = {'X-Gatekeeper-SessionToken': sessionToken}

def getGloballistsDetails():
   # run this code to get listIds - which are hard coded further down
   rqstResponse = requests.get("https://manage.fastfieldforms.com/api/globallists", headers=headers)
   print (rqstResponse.content)
   del rqstResponse

def createGloballist(listname, filePath):
   # usage example createGloballist("test01", r"c:\temp\test.xlsx")
   files = {'file': open(filePath, 'rb')}
   data = {'listname': listname}
   rqstResponse = requests.post("https://manage.fastfieldforms.com/api//globallist",  files=files, data=data, headers=headers)
   print (rqstResponse.content)
   del rqstResponse

def updateGloballist(id, filePath):
   # usage example createGloballist("f03c7db1-cfea-4486-8350-53381ac048b4", r"c:\temp\test.xlsx")
   files = files = {'file': open(filePath, 'rb')}
   data = {'id': id}
   rqstResponse = requests.post("https://manage.fastfieldforms.com/api//globallist",  files=files, data=data, headers=headers)
   print (rqstResponse.content)
   del rqstResponse



filePath = r"J:\Properties\PropGIS\proj\20150820140457_TelecoMapping\data\Survey_Feb17\FastField_Test01.xlsx"
getGloballistsDetails()
#createGloballist("Test02", filePath)
updateGloballist('f03c7db1-cfea-4486-8350-53381ac048b4', filePath)

相关问题 更多 >