forked from alexaorrico/AirBnB_clone_v2
-
Notifications
You must be signed in to change notification settings - Fork 0
/
base_model.py
executable file
·67 lines (57 loc) · 2.42 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
#!usr/bin/python3
"""This module defines a base class for all models in our hbnb clone"""
import uuid
from datetime import datetime
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import Column
from sqlalchemy import String
from sqlalchemy import DateTime
Base = declarative_base()
class BaseModel:
"""A base class for all hbnb models
Attributes:
id (sqlalchemy string): represents the base models id.
created_at (sqlalchemy DateTime): represents models creation time.
updated_at(sqlalchemy DateTime): represents update time of a model.
"""
id = Column(String(60), nullable=False, primary_key=True,
default=str(uuid.uuid4()))
created_at = Column(DateTime, nullable=False, default=datetime.utcnow())
updated_at = Column(DateTime, nullable=False, default=datetime.utcnow())
def __init__(self, *args, **kwargs):
"""Instatntiates a new model"""
if not kwargs:
self.id = str(uuid.uuid4())
self.created_at = datetime.now()
self.updated_at = datetime.now()
else:
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)
def __str__(self):
"""Returns a string representation of the instance"""
cls = (str(type(self)).split('.')[-1]).split('\'')[0]
return '[{}] ({}) {}'.format(cls, self.id, self.__dict__)
def save(self):
"""Updates updated_at with current time when instance is changed"""
from models import storage
self.updated_at = datetime.now()
storage.new(self)
storage.save()
def to_dict(self):
"""Convert instance into dict format"""
dictionary = {}
dictionary.update(self.__dict__)
dictionary.update({'__class__':
(str(type(self)).split('.')[-1]).split('\'')[0]})
dictionary['created_at'] = self.created_at.isoformat()
dictionary['updated_at'] = self.updated_at.isoformat()
dictionary.pop("_sa_instance_state", None)
dictionary.pop("password", None)
return dictionary
def delete(self):
'''deletes the current instance from the storage.'''
from models import storage
storage.delete(self)