forked from justinmajetich/AirBnB_clone
-
Notifications
You must be signed in to change notification settings - Fork 1
/
base_model.py
63 lines (52 loc) · 2.08 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
#!/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, String, DateTime
Base = declarative_base()
class BaseModel:
"""A base class for all hbnb models"""
id = Column(String(60), nullable=False, primary_key=True, unique=True)
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"""
self.id = str(uuid.uuid4())
self.created_at = datetime.now()
self.updated_at = datetime.now()
if kwargs:
kwargs['updated_at'] = self.updated_at
kwargs['created_at'] = self.created_at
try:
del kwargs['__class__']
except KeyError:
pass
self.__dict__.update(kwargs)
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()
try:
del dictionary['_sa_instance_state']
except KeyError:
pass
return dictionary
def delete(self):
""" Function that deletes current instance from storage """
from models import storage
storage.delete(self)