Documentation

This commit is contained in:
2021-03-06 16:28:31 +00:00
parent 5711d4c249
commit 0d9b62adcf

View File

@@ -1,5 +1,4 @@
import os import os
from sys import exit
from pathlib import Path from pathlib import Path
import logging import logging
import requests import requests
@@ -19,6 +18,8 @@ config = {
def get_logger(log_level=logging.WARN): def get_logger(log_level=logging.WARN):
"""Creates, configures and returns a logger that outputs to console with supplied log_level
"""
log = logging.getLogger(__name__) log = logging.getLogger(__name__)
log.setLevel(log_level) log.setLevel(log_level)
log_handler = logging.StreamHandler() log_handler = logging.StreamHandler()
@@ -38,6 +39,7 @@ def send_sms(target: str, msg: str):
account_sid = os.environ['TWILIO_ACCOUNT_SID'] account_sid = os.environ['TWILIO_ACCOUNT_SID']
auth_token = os.environ['TWILIO_AUTH_TOKEN'] auth_token = os.environ['TWILIO_AUTH_TOKEN']
messaging_sid = os.environ['TWILIO_MESSAGE_SID'] messaging_sid = os.environ['TWILIO_MESSAGE_SID']
client = Client(account_sid, auth_token) client = Client(account_sid, auth_token)
message = client.messages.create( message = client.messages.create(
@@ -50,20 +52,28 @@ def send_sms(target: str, msg: str):
log.debug(message.sid) log.debug(message.sid)
def stop_if_previous_action(lock_file: str): def does_file_exist(lock_file: str) -> bool:
if os.path.isfile(lock_file): """Checks for presence of lockfile
log = logging.getLogger(__name__)
log.info("Script has already run it's action before") Args:
exit() lock_file (str): path to lockfile
Returns:
(bool): True if file exists
"""
return os.path.isfile(lock_file)
def action_taken(lock_file): def create_file(lock_file):
Path(lock_file).touch() Path(lock_file).touch()
def main(config, log): def main(config, log):
# This script runs once, to avoid spamming SMS every time run # This script runs once, to avoid spamming SMS every time run
stop_if_previous_action(config['message_sent_file']) if does_file_exist(config['message_sent_file']):
log.info(
f'Already had positive result, remove {config["message_sent_file"]} to allow script to run again')
return
json = get_json_from_url(config['api_url']) json = get_json_from_url(config['api_url'])
@@ -73,10 +83,11 @@ def main(config, log):
log.info("Item is out of stock") log.info("Item is out of stock")
else: else:
log.info("Item is in stock") log.info("Item is in stock")
send_sms(config['msg_to'], 'The coat is in stock at ' + config['website_url']) send_sms(
config['msg_to'], 'The coat is in stock at ' + config['website_url'])
# Prevents it being run again # Prevents it being run again
action_taken(config['message_sent_file']) create_file(config['message_sent_file'])
if __name__ == '__main__': if __name__ == '__main__':