forked from sanjaysiddhanti/s3_testing
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrecipe.py
64 lines (48 loc) · 1.6 KB
/
recipe.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
64
from dataclasses import dataclass
import json
import boto3
S3_BUCKET = "recipes"
def get_s3():
return boto3.client("s3")
@dataclass
class Recipe:
name: str
instructions: str
@classmethod
def get_by_name(cls, name: str):
"""Looks up a Recipe by name
Args:
name (str): Recipe name
Returns a Recipe object
"""
response = get_s3().get_object(Bucket=S3_BUCKET, Key=name)
response = json.loads(response["Body"].read())
return cls(response["name"], response["instructions"])
@classmethod
def update_instructions(cls, name: str, new_instructions: str):
"""Updates the instructions for a recipe
Args:
name (str): Name of the recipe to update
new_instructions (str): New instructions
"""
recipe = cls.get_by_name(name)
recipe.instructions = new_instructions
return recipe
@classmethod
def delete(cls, name: str):
"""Deletes a recipe
Args:
name (str): Name of the recipe to delete
"""
get_s3().delete_object(Bucket=S3_BUCKET, Key=name)
def to_json(self):
"""Serialize the recipe to json
Returns:
str: JSON representation of the Recipe
"""
return json.dumps({"name": self.name, "instructions": self.instructions})
def save(self):
"""Persists a recipe to S3
"""
serialized_recipe = self.to_json().encode("utf-8")
get_s3().put_object(Bucket=S3_BUCKET, Key=self.name, Body=serialized_recipe)