Uh oh!
There was an error while loading. Please reload this page.
- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathupload_file.py
More file actions
Latest commit
44 lines (36 loc) · 1.36 KB
/
Copy pathupload_file.py
File metadata and controls
44 lines (36 loc) · 1.36 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
"""Upload example using curl-compatible multipart encoding from the stdlib."""
importjson
importmimetypes
importos
importsys
importurllib.request
importuuid
frompathlibimportPath
defmain() ->None:
iflen(sys.argv) !=2:
raiseSystemExit("Usage: python3 examples/python/upload_file.py <file>")
api_key=os.getenv("BEATAPI_API_KEY")
ifnotapi_key:
raiseSystemExit("BEATAPI_API_KEY is required.")
path=Path(sys.argv[1])
safe_filename=path.name.replace("\r", "").replace("\n", "").replace('"', "")
boundary=f"beatapi-{uuid.uuid4().hex}"
mime_type=mimetypes.guess_type(path.name)[0] or"application/octet-stream"
body= (
f"--{boundary}\r\n"
f'Content-Disposition: form-data; name="file"; filename="{safe_filename}"\r\n'
f"Content-Type: {mime_type}\r\n\r\n"
).encode() +path.read_bytes() +f"\r\n--{boundary}--\r\n".encode()
request=urllib.request.Request(
f"{os.getenv('BEATAPI_BASE_URL', 'https://api.beatapi.io')}/v1/files",
data=body,
headers={
"Authorization": f"Bearer {api_key}",
"Content-Type": f"multipart/form-data; boundary={boundary}",
},
method="POST",
)
withurllib.request.urlopen(request) asresponse:
print(json.dumps(json.load(response), indent=2))
if__name__=="__main__":
main()