Skip to content

Commit

Permalink
Merge pull request #2 from hyper750/develop
Browse files Browse the repository at this point in the history
Release 0.2
  • Loading branch information
hyper750 authored Nov 13, 2019
2 parents d61a2a0 + a0b20e7 commit ca47bb3
Show file tree
Hide file tree
Showing 4 changed files with 41 additions and 59 deletions.
24 changes: 24 additions & 0 deletions constants.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
import os
import logging


BASE_PROJECT = os.path.abspath(os.path.dirname(__file__))

# Formaters
DEFAULT_FORMATER = logging.Formatter('%(name)s - %(asctime)s - %(levelname)s - %(message)s')

# Handlers
# File handler
FILE_HANDLER = logging.FileHandler(os.path.join(BASE_PROJECT, 'factorialclient.log'), 'a', 'utf-8')
FILE_HANDLER.setLevel(logging.DEBUG)
FILE_HANDLER.setFormatter(DEFAULT_FORMATER)
# Console handler
CONSOLE_HANDLER = logging.StreamHandler()
CONSOLE_HANDLER.setLevel(logging.DEBUG)
CONSOLE_HANDLER.setFormatter(DEFAULT_FORMATER)

# Loggers
LOGGER = logging.getLogger('factorial.client')
LOGGER.setLevel(logging.DEBUG)
LOGGER.addHandler(FILE_HANDLER)
LOGGER.addHandler(CONSOLE_HANDLER)
33 changes: 16 additions & 17 deletions factorial/factorialclient.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,17 +10,16 @@
import logging.config
import random
from datetime import date


logging.config.fileConfig(fname='logging.conf', disable_existing_loggers=False)
logger = logging.getLogger('factorial.client')
from constants import BASE_PROJECT, LOGGER


class FactorialClient:
# Folder to save the session's cookie
SESSIONS_FOLDER = "sessions"
SESSIONS_FOLDER = os.path.join(BASE_PROJECT, "sessions")
# Default factorial settings file
DEFAULT_FACTORIAL_SETTINGS = os.path.join(BASE_PROJECT, 'factorial_settings.json')

# Url's
# Endpoints
BASE_NAME = "https://api.factorialhr.com/"
# Url to be able to login (post: username, password) and logout (delete) on the api
SESSION_URL = '{}sessions'.format(BASE_NAME)
Expand Down Expand Up @@ -54,7 +53,7 @@ def __init__(self, email, password, cookie_file=None):
if os.path.exists(cookie_path):
with open(cookie_path, "rb") as file:
# TODO: Watch out the expiration of the cookie
logger.info('Getting the session from cookies files')
LOGGER.info('Getting the session from cookies files')
self.session.cookies.update(pickle.load(file))

def login(self):
Expand All @@ -65,7 +64,7 @@ def login(self):
try:
self.load_user_data()
# Try to load the user info using the cookie, if can't login again using the username and password
logger.info('Already logged in, re-login is not needed')
LOGGER.info('Already logged in, re-login is not needed')
return True
except UserNotLoggedIn:
payload = {
Expand All @@ -80,15 +79,15 @@ def login(self):
response = self.session.post(url=self.SESSION_URL, data=payload)
loggedin = response.status_code == http_client.CREATED
if loggedin:
logger.info('Login successfully')
LOGGER.info('Login successfully')
# Load user data
self.load_user_data()
# Save the cookies if is logged in
if not os.path.exists(self.SESSIONS_FOLDER):
os.mkdir(self.SESSIONS_FOLDER)
with open(os.path.join(self.SESSIONS_FOLDER, self.cookie_file), "wb") as file:
pickle.dump(self.session.cookies, file)
logger.info('Sessions saved')
LOGGER.info('Sessions saved')
return loggedin

@staticmethod
Expand All @@ -103,7 +102,7 @@ def generate_new_token():
return token_value

@staticmethod
def load_from_settings(json_settings='factorial_settings.json'):
def load_from_settings(json_settings=DEFAULT_FACTORIAL_SETTINGS):
"""Login from the settings if the session still valid from the saved cookies, otherwise ask for the password
:param json_settings: string config filename
Expand Down Expand Up @@ -275,7 +274,7 @@ def generate_worked_periods(self, start_work, end_work, work_minutes_variation,
})
return self.add_breaks_to_period(start_sign_hour, start_sign_minutes, end_sign_hour, end_sign_minutes, breaks_with_variation)

def worked_day(self, day=date.today(), json_settings='factorial_settings.json'):
def worked_day(self, day=date.today(), json_settings=DEFAULT_FACTORIAL_SETTINGS):
"""Mark today as worked day
:param day: date to save the worked day, by default is today
Expand All @@ -295,7 +294,7 @@ def worked_day(self, day=date.today(), json_settings='factorial_settings.json'):
for worked_period in already_work:
self.delete_worked_period(worked_period.get('id'))
else:
logger.info('Day already sign')
LOGGER.info('Day already sign')
return

add_worked_period_kwargs = {
Expand All @@ -321,7 +320,7 @@ def worked_day(self, day=date.today(), json_settings='factorial_settings.json'):
'end_minute': end_minute,
})
if self.add_worked_period(**add_worked_period_kwargs):
logger.info('Saved worked period for the day {0:s} between {1:02d}:{2:02d} - {3:02d}:{4:02d}'.format(
LOGGER.info('Saved worked period for the day {0:s} between {1:02d}:{2:02d} - {3:02d}:{4:02d}'.format(
day.isoformat(),
start_hour, start_minute,
end_hour, end_minute))
Expand All @@ -333,7 +332,7 @@ def logout(self):
"""
response = self.session.delete(url=self.SESSION_URL)
logout_correcty = response.status_code == http_client.NO_CONTENT
logger.info('Logout successfully {}'.format(logout_correcty))
LOGGER.info('Logout successfully {}'.format(logout_correcty))
self.session = requests.Session()
path_file = os.path.join(self.SESSIONS_FOLDER, self.cookie_file)
if os.path.exists(path_file):
Expand Down Expand Up @@ -368,7 +367,7 @@ def load_employees(self):
}
]
"""
logger.info("Loading employees")
LOGGER.info("Loading employees")
employee_response = self.session.get(self.EMPLOYEE_URL)
self.check_status_code(employee_response.status_code, http_client.OK)
employee_json = employee_response.json()
Expand Down Expand Up @@ -596,7 +595,7 @@ def add_worked_period(self, year, month, day, start_hour, start_minute, end_hour
formatted_date = f'{year:04d}-{month:02d}-{day:02d}'
for calendar_day in calendar:
if calendar_day.get('date') == formatted_date:
logger.info(f"Can't sign today {formatted_date}, because are vacations")
LOGGER.info(f"Can't sign today {formatted_date}, because are vacations")
return False
period = self.get_period(year=year, month=month)
current_period = period[0]
Expand Down
41 changes: 0 additions & 41 deletions logging.conf

This file was deleted.

2 changes: 1 addition & 1 deletion main.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,6 @@
except AuthenticationTokenNotFound as err:
print(f"Can't retrieve the login token: {err}")
except UserNotLoggedIn as err:
print(err)
print(f'User not logged in: {err}')
except ApiError as err:
print(f"Api error: {err}")

0 comments on commit ca47bb3

Please sign in to comment.