【问题标题】:How can use python request to upload file using graphql?如何使用 python 请求使用 graphql 上传文件?
【发布时间】:2021-09-03 02:08:57
【问题描述】:

我有一个通过 Insomnia 生成的 curl 代码,它运行良好。我只是想不出用 python 请求来复制它。

curl --request POST \
  --url MY_SERVER_URL \
  --header 'Accept: application/json' \
  --header 'Content-type: multipart/form-data; boundary=---011000010111000001101001' \
  --header 'Authorization:  AUTH_TOKEN' \
  --form 'operations={
  "query": "mutation($file: Upload!, $path: String!, $private: Boolean) { uploadFile(file: $file, path: $path, private: $private) }",
  "variables": {
    "file": null,
    "path": "test",
    "private": false
  }
}' \
  --form 'map={ "0": ["variables.file"] }' \
  --form '0=@E:\Development\Technology\Python\small_utilities\barwis\random-files\files\csvs\above serious.csv'

谢谢

【问题讨论】:

    标签: python graphql


    【解决方案1】:

    我想出了解决办法。如果有人有同样的问题,这里是参考代码。

    file = open('FILE_PATH', 'rb')
    auth_headers = {
      "Authorization": f"Bearer {token}"
    }
    
    query = """
      mutation($file: Upload!, $path: String!, $private: Boolean) { 
          uploadFile(file: $file, path: $path, private: $private) 
      }
      """
      
    variables = { 
        "file": None,
        "path": 'test',
        "private": True
    }  
    
    operations = json.dumps({
      "query": query,
      "variables": variables
    })
    
    map = json.dumps({ "0": ["variables.file"] })
      
    response = requests.post(graphql_url, data = {
        "operations": operations,
        "map": map
      },
      files = {
        "0" : file
      },
      headers = auth_headers
    )
    

    【讨论】:

      猜你喜欢
      • 2014-04-29
      • 2018-08-28
      • 1970-01-01
      • 2020-11-02
      • 2019-12-13
      相关资源
      最近更新 更多