forked from jono-allen/MQTT-Cam
-
Notifications
You must be signed in to change notification settings - Fork 0
/
upload_image.py
63 lines (52 loc) · 1.99 KB
/
upload_image.py
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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
import json
import logging
import boto3
import requests
from botocore.exceptions import ClientError
file_name = 'latest.jpeg'
key = 'media/login.jpeg'
bucket = 'river-watch'
def create_presigned_post(bucket_name, object_name,
fields=None, conditions=None, expiration=3600):
"""Generate a presigned URL S3 POST request to upload a file
:param bucket_name: string
:param object_name: string
:param fields: Dictionary of prefilled form fields
:param conditions: List of conditions to include in the policy
:param expiration: Time in seconds for the presigned URL to remain valid
:return: Dictionary with the following keys:
url: URL to post to
fields: Dictionary of form fields and values to submit with the POST
:return: None if error.
"""
# Generate a presigned S3 POST URL
s3_client = boto3.client('s3')
try:
response = s3_client.generate_presigned_post(bucket_name,
object_name,
Fields=fields,
Conditions=conditions,
ExpiresIn=expiration)
except ClientError as e:
logging.error(e)
return None
# The response contains the presigned URL and required fields
return response
def upload():
with open('./flowers.jpeg', 'rb') as f:
files = {'file': (file_name, f)}
response = create_presigned_post(bucket, key)
try:
http_response = requests.post(
response['url'], data=response['fields'], files=files,
)
if http_response.status_code == 204:
print('success')
import pdb
pdb.set_trace()
else:
print(http_response.__dict__)
except Exception as e:
# print(http_response.request.__dict__)
print(e)
upload()