forked from alexaorrico/AirBnB_clone_v2
-
Notifications
You must be signed in to change notification settings - Fork 0
/
base_model.py
executable file
·96 lines (83 loc) · 2.75 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
84
85
86
87
88
89
90
91
92
93
94
95
96
#!/usr/bin/python3
"""
BaseModel Class of Models Module
"""
import os
import json
import models
from uuid import uuid4, UUID
from datetime import datetime
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import Column, Integer, String, Float, DateTime
storage_type = os.environ.get('HBNB_TYPE_STORAGE')
"""
Creates instance of Base if storage type is a database
If not database storage, uses class Base
"""
if storage_type == 'db':
Base = declarative_base()
else:
class Base:
pass
class BaseModel:
"""
attributes and functions for BaseModel class
"""
if storage_type == '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):
"""instantiation of new BaseModel Class"""
self.id = str(uuid4())
self.created_at = datetime.now()
if kwargs:
for key, value in kwargs.items():
setattr(self, key, value)
def __is_serializable(self, obj_v):
"""
private: checks if object is serializable
"""
try:
obj_to_str = json.dumps(obj_v)
return obj_to_str is not None and isinstance(obj_to_str, str)
except:
return False
def bm_update(self, name, value):
"""
updates the basemodel and sets the correct attributes
"""
setattr(self, name, value)
if storage_type != 'db':
self.save()
def save(self):
"""updates attribute updated_at to current time"""
if storage_type != 'db':
self.updated_at = datetime.now()
models.storage.new(self)
models.storage.save()
def to_json(self):
"""returns json representation of self"""
bm_dict = {}
for key, value in (self.__dict__).items():
if (self.__is_serializable(value)):
bm_dict[key] = value
else:
bm_dict[key] = str(value)
bm_dict['__class__'] = type(self).__name__
if '_sa_instance_state' in bm_dict:
bm_dict.pop('_sa_instance_state')
if storage_type == "db" and 'password' in bm_dict:
bm_dict.pop('password')
return bm_dict
def __str__(self):
"""returns string type representation of object instance"""
class_name = type(self).__name__
return '[{}] ({}) {}'.format(class_name, self.id, self.__dict__)
def delete(self):
"""
deletes current instance from storage
"""
self.delete()