-
Notifications
You must be signed in to change notification settings - Fork 0
/
base_model.py
83 lines (73 loc) · 2.72 KB
/
base_model.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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
#!/usr/bin/python3
"""This is the base model class for AirBnB"""
from sqlalchemy.ext.declarative import declarative_base
import uuid
import models
from datetime import datetime
from sqlalchemy import Column, Integer, String, DateTime
Base = declarative_base()
class BaseModel:
"""This class will defines all common attributes/methods
for other classes
"""
id = Column(String(60), unique=True, nullable=False, primary_key=True)
created_at = Column(DateTime, nullable=False, default=(datetime.utcnow()))
updated_at = Column(DateTime, nullable=False, default=(datetime.utcnow()))
def __init__(self, *args, **kwargs):
"""Instantiation of base model class
Args:
args: it won't be used
kwargs: arguments for the constructor of the BaseModel
Attributes:
id: unique id generated
created_at: creation date
updated_at: updated date
"""
if kwargs:
for key, value in kwargs.items():
if key == "created_at" or key == "updated_at":
value = datetime.strptime(value, "%Y-%m-%dT%H:%M:%S.%f")
if key != "__class__":
setattr(self, key, value)
if "id" not in kwargs:
self.id = str(uuid.uuid4())
if "created_at" not in kwargs:
self.created_at = datetime.now()
if "updated_at" not in kwargs:
self.updated_at = datetime.now()
else:
self.id = str(uuid.uuid4())
self.created_at = self.updated_at = datetime.now()
def __str__(self):
"""returns a string
Return:
returns a string of class name, id, and dictionary
"""
return "[{}] ({}) {}".format(
type(self).__name__, self.id, self.__dict__)
def __repr__(self):
"""return a string representaion
"""
return self.__str__()
def save(self):
"""updates the public instance attribute updated_at to current
"""
self.updated_at = datetime.now()
models.storage.new(self)
models.storage.save()
def to_dict(self):
"""creates dictionary of the class and returns
Return:
returns a dictionary of all the key values in __dict__
"""
my_dict = dict(self.__dict__)
my_dict["__class__"] = str(type(self).__name__)
my_dict["created_at"] = self.created_at.isoformat()
my_dict["updated_at"] = self.updated_at.isoformat()
if '_sa_instance_state' in my_dict.keys():
del my_dict['_sa_instance_state']
return my_dict
def delete(self):
""" delete object
"""
models.storage.delete(self)