-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbase_model.py
executable file
·76 lines (65 loc) · 2.68 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
#!/usr/bin/python3
"""
Contains class BaseModel
"""
from datetime import datetime
import models
from sqlalchemy import Column, String, DateTime
from sqlalchemy.ext.declarative import declarative_base
import uuid
from os import getenv
time_fmt = "%Y-%m-%dT%H:%M:%S.%f"
if getenv("HBNB_TYPE_STORAGE") == 'db':
Base = declarative_base()
else:
Base = object
class BaseModel:
"""The BaseModel class from which future classes will be derived"""
if getenv("HBNB_TYPE_STORAGE") == 'db':
id = Column(String(60), 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):
"""Initialization of the base model"""
self.id = str(uuid.uuid4())
self.created_at = datetime.now()
self.updated_at = self.created_at
for key, value in kwargs.items():
if key == '__class__':
continue
setattr(self, key, value)
if type(self.created_at) is str:
self.created_at = datetime.strptime(self.created_at, time_fmt)
if type(self.updated_at) is str:
self.updated_at = datetime.strptime(self.updated_at, time_fmt)
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.now()
models.storage.new(self)
models.storage.save()
def to_dict(self, save_to_disk=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"].isoformat()
if "updated_at" in new_dict:
new_dict["updated_at"] = new_dict["updated_at"].isoformat()
if '_password' in new_dict:
new_dict['password'] = new_dict['_password']
new_dict.pop('_password', None)
if 'amenities' in new_dict:
new_dict.pop('amenities', None)
if 'reviews' in new_dict:
new_dict.pop('reviews', None)
new_dict["__class__"] = self.__class__.__name__
new_dict.pop('_sa_instance_state', None)
if not save_to_disk:
new_dict.pop('password', None)
return new_dict
def delete(self):
"""Delete current instance from storage by calling its delete method"""
models.storage.delete(self)