-
Notifications
You must be signed in to change notification settings - Fork 1
/
app.py
62 lines (53 loc) · 1.31 KB
/
app.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
import boto3
import chalice
import os
import secrets
BUCKET_NAME = os.getenv("BUCKET_NAME") or "bytebin"
RESERVED_KEYS = ["demo", "post"]
app = chalice.Chalice(app_name="bytebin")
def token():
s3 = boto3.client("s3")
n = 2
t = 0
while True:
k = secrets.token_urlsafe(n)
if k not in RESERVED_KEYS:
try:
s3.head_object(Bucket=BUCKET_NAME, Key=k)
except:
return k
if t > 2:
n += 1
t = 0
else:
t += 1
@app.route("/post", methods=["POST"])
def post():
s3 = boto3.resource("s3")
d = app.current_request.raw_body
k = token()
try:
s3.Object(BUCKET_NAME, k).put(Body=d)
except:
r = chalice.Response("", status_code=503)
else:
r = chalice.Response({"key": k},
status_code=201,
headers={"Location": k})
return r
@app.route("/{key}", methods=["GET"])
def object(key):
s3 = boto3.resource("s3")
o = s3.Object(BUCKET_NAME, key)
try:
o.load()
except:
r = chalice.Response("", status_code=404)
else:
try:
r = o.get()
except:
r = chalice.Response("", status_code=404)
else:
r = r["Body"].read()
return r