我有一个通过失眠生成的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:DevelopmentTechnologyPythonsmall_utilitiesbarwisrandom-filesfilescsvsabove serious.csv'
感谢
我找到了解决方案。若有人有相同的问题,这里是参考代码。
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
)
另一个选项是使用graphql-python/gql库。它支持上传文件,即使是流媒体!
transport = AIOHTTPTransport(url='YOUR_URL')
# Or transport = RequestsHTTPTransport(url='YOUR_URL')
client = Client(transport=transport)
query = gql('''
mutation($file: Upload!) {
singleUpload(file: $file) {
id
}
}
''')
with open("YOUR_FILE_PATH", "rb") as f:
params = {"file": f}
result = client.execute(
query, variable_values=params, upload_files=True
)