Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

My feature branch #1445

Open
wants to merge 33 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
33 commits
Select commit Hold shift + click to select a range
a695fb2
fix console and setup mysql
jamal4567 Mar 18, 2024
37fcf5d
Merge pull request #1 from jamal4567/test
jamal4567 Mar 18, 2024
9470e03
MySQL setup test
jamal4567 Mar 18, 2024
a2c4299
Merge pull request #2 from jamal4567/test
jamal4567 Mar 18, 2024
66ea56c
Marvel branch
Mar 18, 2024
694794a
Marvel branch
Mar 18, 2024
e95964d
update file_storage
jamal4567 Mar 18, 2024
72b4bbe
Merge pull request #3 from jamal4567/test
jamal4567 Mar 18, 2024
4d251e9
2. Console improvements
Mar 18, 2024
9dee970
2. Console improvements
Mar 18, 2024
fcd946f
2. Console improvements
Mar 18, 2024
fc52697
2. Console improvements
Mar 18, 2024
752feb1
2. Console improvements and unnittest file
Mar 19, 2024
f1e9f9a
2. Console improvements and unnittest file
Mar 19, 2024
a3d1f3a
Merge pull request #4 from jamal4567/marvel_branch
jamal4567 Mar 19, 2024
726e2c8
airbnb
jamal4567 Mar 20, 2024
5ed5412
Merge pull request #5 from jamal4567/test
marvel9117 Mar 20, 2024
22280c6
db_storage
jamal4567 Mar 20, 2024
7c3451b
Merge pull request #6 from jamal4567/test
marvel9117 Mar 20, 2024
4aa0889
corrected style conventions in PEP 8.
Mar 21, 2024
080e13c
task 8
Mar 21, 2024
9e18b65
debbugged task 6 and checked if it is a file storage before adding ge…
Mar 21, 2024
d77ec8e
Merge pull request #7 from jamal4567/marvel_test
jamal4567 Mar 21, 2024
3aeb4ba
Fabric script
jamal4567 Jul 11, 2024
6d033d2
Merge branch 'master' of https://github.com/jamal4567/AirBnB_clone_v2
jamal4567 Jul 11, 2024
80a264f
Fabric script
jamal4567 Jul 11, 2024
ba23222
task-01
jamal4567 Jul 11, 2024
4c3c586
deploy_web_static
jamal4567 Jul 11, 2024
8824f9a
deploy_web_static
jamal4567 Jul 11, 2024
45f702b
web_flask
jamal4567 Jul 28, 2024
1214662
web_flask
jamal4567 Jul 28, 2024
ec89ff0
updt
jamal4567 Jul 28, 2024
30d25f8
web_flask
jamal4567 Jul 28, 2024
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 27 additions & 0 deletions 0-setup_web_static.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
#!/usr/bin/env bash
# Bash script that sets up web servers for the deployment of web_static
sudo apt-get update
sudo apt-get -y install nginx
sudo ufw allow 'Nginx HTTP'

sudo mkdir -p /data/
sudo mkdir -p /data/web_static/
sudo mkdir -p /data/web_static/releases/
sudo mkdir -p /data/web_static/shared/
sudo mkdir -p /data/web_static/releases/test/
sudo touch /data/web_static/releases/test/index.html
sudo echo "<html>
<head>
</head>
<body>
Holberton School
</body>
</html>" | sudo tee /data/web_static/releases/test/index.html

sudo ln -s -f /data/web_static/releases/test/ /data/web_static/current

sudo chown -R ubuntu:ubuntu /data/

sudo sed -i '/listen 80 default_server/a location /hbnb_static { alias /data/web_static/current/;}' /etc/nginx/sites-enabled/default

sudo service nginx restart
19 changes: 19 additions & 0 deletions 1-pack_web_static.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
#!/usr/bin/python3
from fabric.api import local
from time import strftime
from datetime import date


def do_pack():
""" A script that generates archive the contents of web_static folder"""

filename = strftime("%Y%m%d%H%M%S")
try:
local("mkdir -p versions")
local("tar -czvf versions/web_static_{}.tgz web_static/"
.format(filename))

return "versions/web_static_{}.tgz".format(filename)

except Exception as e:
return None
56 changes: 56 additions & 0 deletions 2-do_deploy_web_static.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
#!/usr/bin/python3
"""Compress web static package
"""
from fabric.api import *
from datetime import datetime
from os import path


env.hosts = ['100.25.136.203', '52.90.22.104']
env.user = 'ubuntu'
env.key_filename = '~/.ssh/id_rsa'


def do_deploy(archive_path):
"""Deploy web files to server
"""
try:
if not (path.exists(archive_path)):
return False

# upload archive
put(archive_path, '/tmp/')

# create target dir
timestamp = archive_path[-18:-4]
run('sudo mkdir -p /data/web_static/\
releases/web_static_{}/'.format(timestamp))

# uncompress archive and delete .tgz
run('sudo tar -xzf /tmp/web_static_{}.tgz -C \
/data/web_static/releases/web_static_{}/'
.format(timestamp, timestamp))

# remove archive
run('sudo rm /tmp/web_static_{}.tgz'.format(timestamp))

# move contents into host web_static
run('sudo mv /data/web_static/releases/web_static_{}/web_static/* \
/data/web_static/releases/web_static_{}/'.format(timestamp, timestamp))

# remove extraneous web_static dir
run('sudo rm -rf /data/web_static/releases/\
web_static_{}/web_static'
.format(timestamp))

# delete pre-existing sym link
run('sudo rm -rf /data/web_static/current')

# re-establish symbolic link
run('sudo ln -s /data/web_static/releases/\
web_static_{}/ /data/web_static/current'.format(timestamp))
except:
return False

# return True on success
return True
75 changes: 75 additions & 0 deletions 3-deploy_web_static.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
#!/usr/bin/python3
import os.path
from datetime import datetime
from fabric.api import env
from fabric.api import local
from fabric.api import put
from fabric.api import run

env.hosts = ['100.25.136.203', '52.90.22.104']


def do_pack():
"""Create a tar gzipped archive of the directory web_static."""
dt = datetime.utcnow()
file = "versions/web_static_{}{}{}{}{}{}.tgz".format(dt.year,
dt.month,
dt.day,
dt.hour,
dt.minute,
dt.second)
if os.path.isdir("versions") is False:
if local("mkdir -p versions").failed is True:
return None
if local("tar -cvzf {} web_static".format(file)).failed is True:
return None
return file


def do_deploy(archive_path):
"""Distributes an archive to a web server.

Args:
archive_path (str): The path of the archive to distribute.
Returns:
If the file doesn't exist at archive_path or an error occurs - False.
Otherwise - True.
"""
if os.path.isfile(archive_path) is False:
return False
file = archive_path.split("/")[-1]
name = file.split(".")[0]

if put(archive_path, "/tmp/{}".format(file)).failed is True:
return False
if run("rm -rf /data/web_static/releases/{}/".
format(name)).failed is True:
return False
if run("mkdir -p /data/web_static/releases/{}/".
format(name)).failed is True:
return False
if run("tar -xzf /tmp/{} -C /data/web_static/releases/{}/".
format(file, name)).failed is True:
return False
if run("rm /tmp/{}".format(file)).failed is True:
return False
if run("mv /data/web_static/releases/{}/web_static/* "
"/data/web_static/releases/{}/".format(name, name)).failed is True:
return False
if run("rm -rf /data/web_static/releases/{}/web_static".
format(name)).failed is True:
return False
if run("rm -rf /data/web_static/current").failed is True:
return False
if run("ln -s /data/web_static/releases/{}/ /data/web_static/current".
format(name)).failed is True:
return False
return True


def deploy():
"""Create and distribute an archive to a web server."""
file = do_pack()
if file is None:
return False
return do_deploy(file)
Binary file added __pycache__/console.cpython-38.pyc
Binary file not shown.
43 changes: 34 additions & 9 deletions console.py
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,7 @@ def precmd(self, line):
pline = pline[2].strip() # pline is now str
if pline:
# check for *args or **kwargs
if pline[0] is '{' and pline[-1] is'}'\
if pline[0] == '{' and pline[-1] == '}'\
and type(eval(pline)) is dict:
_args = pline
else:
Expand Down Expand Up @@ -115,16 +115,40 @@ def emptyline(self):

def do_create(self, args):
""" Create an object of any class"""
if not args:
try:
class_name = args.split(" ")[0]
except IndexError:
pass
if not class_name:
print("** class name missing **")
return
elif args not in HBNBCommand.classes:
elif class_name not in HBNBCommand.classes:
print("** class doesn't exist **")
return
new_instance = HBNBCommand.classes[args]()
storage.save()
all_list = args.split(" ")

new_instance = eval(class_name)()

for i in range(1, len(all_list)):
key, value = tuple(all_list[i].split("="))
if value.startswith('"'):
value = value.strip('"').replace('"', '\\"')
else:
try:
value = eval(value)
except Exception:
print(f"** couldn't evaluate {value}")
pass

if isinstance(value, str):
value = value.replace("_", " ")

if hasattr(new_instance, key):
setattr(new_instance, key, value)

storage.new(new_instance)
print(new_instance.id)
storage.save()
new_instance.save()

def help_create(self):
""" Help information for the create method """
Expand Down Expand Up @@ -272,18 +296,18 @@ def do_update(self, args):
args.append(v)
else: # isolate args
args = args[2]
if args and args[0] is '\"': # check for quoted arg
if args and args[0] == '\"': # check for quoted arg
second_quote = args.find('\"', 1)
att_name = args[1:second_quote]
args = args[second_quote + 1:]

args = args.partition(' ')

# if att_name was not quoted arg
if not att_name and args[0] is not ' ':
if not att_name and args[0] != ' ':
att_name = args[0]
# check for quoted val arg
if args[2] and args[2][0] is '\"':
if args[2] and args[2][0] == '\"':
att_val = args[2][1:args[2].find('\"', 1)]

# if att_val was not quoted arg
Expand Down Expand Up @@ -320,5 +344,6 @@ def help_update(self):
print("Updates an object with new information")
print("Usage: update <className> <id> <attName> <attVal>\n")


if __name__ == "__main__":
HBNBCommand().cmdloop()
1 change: 1 addition & 0 deletions file.json
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
{"State.d4328bb2-f591-4889-bdea-3de7d5de3969": {"id": "d4328bb2-f591-4889-bdea-3de7d5de3969", "created_at": "2024-03-18T14:03:24.970352", "updated_at": "2024-03-18T14:03:24.970396", "name": "California", "__class__": "State"}, "State.8eb236e6-d50a-4189-8b37-de177b27bbb9": {"id": "8eb236e6-d50a-4189-8b37-de177b27bbb9", "created_at": "2024-03-18T14:03:24.970671", "updated_at": "2024-03-18T14:03:24.970713", "name": "Arizona", "__class__": "State"}, "Place.da3107f0-96de-4ae5-88be-1fa8ee926b74": {"id": "da3107f0-96de-4ae5-88be-1fa8ee926b74", "created_at": "2024-03-18T14:03:24.971920", "updated_at": "2024-03-18T14:03:24.972044", "city_id": "0001", "user_id": "0001", "name": "My little house", "number_rooms": 4, "number_bathrooms": 2, "max_guest": 10, "price_by_night": 300, "latitude": 37.773972, "longitude": -122.431297, "__class__": "Place"}}
11 changes: 8 additions & 3 deletions models/__init__.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,12 @@
#!/usr/bin/python3
"""This module instantiates an object of class FileStorage"""
from models.engine.file_storage import FileStorage
"""This module instantiates an object of class FileStorage """
from os import getenv


storage = FileStorage()
if getenv("HBNB_TYPE_STORAGE") == "db":
from models.engine.db_storage import DBStorage
storage = DBStorage()
else:
from models.engine.file_storage import FileStorage
storage = FileStorage()
storage.reload()
Binary file added models/__pycache__/__init__.cpython-38.pyc
Binary file not shown.
Binary file added models/__pycache__/amenity.cpython-38.pyc
Binary file not shown.
Binary file added models/__pycache__/base_model.cpython-38.pyc
Binary file not shown.
Binary file added models/__pycache__/city.cpython-38.pyc
Binary file not shown.
Binary file added models/__pycache__/place.cpython-38.pyc
Binary file not shown.
Binary file added models/__pycache__/review.cpython-38.pyc
Binary file not shown.
Binary file added models/__pycache__/state.cpython-38.pyc
Binary file not shown.
Binary file added models/__pycache__/user.cpython-38.pyc
Binary file not shown.
45 changes: 30 additions & 15 deletions models/base_model.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,25 +2,36 @@
"""This module defines a base class for all models in our hbnb clone"""
import uuid
from datetime import datetime
from sqlalchemy import String, Column, DateTime
from sqlalchemy.ext.declarative import declarative_base
import models

Base = declarative_base()


class BaseModel:
"""A base class for all hbnb models"""
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):
"""Instatntiates a new model"""
if not kwargs:
from models import storage
self.id = str(uuid.uuid4())
self.created_at = datetime.now()
self.updated_at = datetime.now()
storage.new(self)
else:
kwargs['updated_at'] = datetime.strptime(kwargs['updated_at'],
'%Y-%m-%dT%H:%M:%S.%f')
kwargs['created_at'] = datetime.strptime(kwargs['created_at'],
'%Y-%m-%dT%H:%M:%S.%f')
del kwargs['__class__']
self.__dict__.update(kwargs)
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,
'%Y-%m-%dT%H:%M:%S.%f')
if type(self.updated_at) is str:
self.updated_at = datetime.strptime(self.updated_at,
'%Y-%m-%dT%H:%M:%S.%f')

def __str__(self):
"""Returns a string representation of the instance"""
Expand All @@ -29,16 +40,20 @@ def __str__(self):

def save(self):
"""Updates updated_at with current time when instance is changed"""
from models import storage
self.updated_at = datetime.now()
storage.save()
models.storage.new(self)
models.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]})
"""Returns all dictionary containing all keys,values"""
dictionary = dict(self.__dict__)
dictionary["__class__"] = str(type(self).__name__)
dictionary['created_at'] = self.created_at.isoformat()
dictionary['updated_at'] = self.updated_at.isoformat()
if '_sa_instance_state' in dictionary.keys():
del dictionary['_sa_instance_state']
return dictionary

def delete(self):
""" delete the current instance from the storage"""
models.storage.delete(self)
13 changes: 9 additions & 4 deletions models/city.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,14 @@
#!/usr/bin/python3
""" City Module for HBNB project """
from models.base_model import BaseModel
from models.base_model import BaseModel, Base
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import String, Column, ForeignKey


class City(BaseModel):
class City(BaseModel, Base):
""" The city class, contains state ID and name """
state_id = ""
name = ""
__tablename__ = "cities"
name = Column(String(128), nullable=False)
state_id = Column(String(60), ForeignKey('states.id'), nullable=False)
places = relationship("Place", backref="cities",
cascade="all, delete-orphan")
Binary file added models/engine/__pycache__/__init__.cpython-38.pyc
Binary file not shown.
Binary file not shown.
Loading