forked from alexaorrico/AirBnB_clone_v2
-
Notifications
You must be signed in to change notification settings - Fork 1
/
base_model.py
executable file
·77 lines (67 loc) · 2.73 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
#!/usr/bin/python3
"""
Contains class BaseModel
"""
from datetime import datetime
import models
from os import getenv
import sqlalchemy
from sqlalchemy import Column, String, DateTime
from sqlalchemy.ext.declarative import declarative_base
import uuid
time = "%Y-%m-%dT%H:%M:%S.%f"
if models.storage_t == "db":
Base = declarative_base()
else:
Base = object
class BaseModel:
"""The BaseModel class from which future classes will be derived"""
if models.storage_t == "db":
id = Column(String(60), primary_key=True)
created_at = Column(DateTime, default=datetime.utcnow)
updated_at = Column(DateTime, default=datetime.utcnow)
def __init__(self, *args, **kwargs):
"""Initialization of the base model"""
if kwargs:
for key, value in kwargs.items():
if key != "__class__":
setattr(self, key, value)
if kwargs.get("created_at", None) and type(self.created_at) is str:
self.created_at = datetime.strptime(kwargs["created_at"], time)
else:
self.created_at = datetime.utcnow()
if kwargs.get("updated_at", None) and type(self.updated_at) is str:
self.updated_at = datetime.strptime(kwargs["updated_at"], time)
else:
self.updated_at = datetime.utcnow()
if kwargs.get("id", None) is None:
self.id = str(uuid.uuid4())
else:
self.id = str(uuid.uuid4())
self.created_at = datetime.utcnow()
self.updated_at = self.created_at
def __str__(self):
"""String representation of the BaseModel class"""
return "[{:s}] ({:s}) {}".format(self.__class__.__name__, self.id,
self.__dict__)
def save(self):
"""updates the attribute 'updated_at' with the current datetime"""
self.updated_at = datetime.utcnow()
models.storage.new(self)
models.storage.save()
def to_dict(self, save_check=False):
"""returns a dictionary containing all keys/values of the instance"""
new_dict = self.__dict__.copy()
if "created_at" in new_dict:
new_dict["created_at"] = new_dict["created_at"].strftime(time)
if "updated_at" in new_dict:
new_dict["updated_at"] = new_dict["updated_at"].strftime(time)
new_dict["__class__"] = self.__class__.__name__
if "_sa_instance_state" in new_dict:
del new_dict["_sa_instance_state"]
if "password" in new_dict and save_check is False:
del new_dict["password"]
return new_dict
def delete(self):
"""delete the current instance from the storage"""
models.storage.delete(self)