示例#1
0
    def check_game_availability(self):
        emailer = None
        sql_dao = SQLDao()
        try:
            sql_dao.build_hockey_games_table()
            try:
                emailer = Emailer(gmail_user, gmail_password)
            except Exception as e:
                print('Exception while starting emailer: {}'.format(e))
                print('proceeding with console messages instead...')
                emailer = lambda msg: println(msg)

            game_statuses = self.get_game_statuses(sql_dao)

            did_game_change = any(
                [g.did_game_become_available() for g in game_statuses])
            if did_game_change:
                print("A game changed to available, sending email...")
                emailer.send_game_status_emails(game_statuses)
            else:
                print("No game changed state, not sending email...")
                errors_getting_game_availability = any(
                    [g.is_game_sold_out is None for g in game_statuses])
                if errors_getting_game_availability:
                    print("Errors getting game availability, sending email...")
                    emailer.send_error_email()

        except Exception as e:
            print('Exception while starting emailer: {}'.format(e))

        finally:
            if emailer and not callable(emailer):
                print('Closing SMTP Connection')
                emailer.close()
示例#2
0
def watch_canary(f):
    initial_file_access_time = stat(f).st_atime
    sleep(5)

    while True:
        file_access_time = stat(f).st_atime

        if file_access_time != initial_file_access_time:

            gmail_address = environ["GMAIL_ADDR"]
            gmail_password = environ["GMAIL_PASS"]

            with Emailer("smtp.gmail.com", 465) as email:

                # Remove print statements when running as cronjob or
                # scheduled task
                if email.authenticate(gmail_address, gmail_password):
                    print("{*} Authentication successful!")
                else:
                    print("{-} Authentication unsuccessful!")

                subject = "[WARNING] Canary Triggered"
                now = datetime.now().strftime("%d/%m/%Y %H:%M:%S")
                message = f"[{now}] Someone accessed the canary file:\n\t {realpath(f)}"

                if email.send(gmail_address, subject, message):
                    print("{*} Successfully sent email!")
                else:
                    print("{*} Email could not be sent!")
            break
        sleep(5)
示例#3
0
文件: reddit.py 项目: cjh232/BAPS-Bot
    def execute_search(self, product_flair, limit):

        # Search the subreddit for items matching the product_flair

        res = self.subreddit.new(limit=limit)

        emailer = Emailer(secrets.sender, secrets.receiver, secrets.user,
                          secrets.password, secrets.smtp_domain,
                          secrets.smtp_port)

        for submission in res:
            if submission.link_flair_text.lower() == product_flair.lower(
            ) and not submission.stickied:
                match_object = SimpleNamespace()

                match_object.title = submission.title
                match_object.url = submission.url
                match_object.created_utc = submission.created_utc

                emailer.appendMessage(match_object)

        # TODO: Send email when no submissions were found
        if emailer.getQueueLength() > 0:
            emailer.sendEmail()
        else:
            print("No submission were found...")
示例#4
0
	def handle_new_signals(self):
		if self.to_email:
			emailer = Emailer()
			for a in self.new_signals_array:
				if len(a) > 0:
					sig = a[-1]
					if sig.type == Sig.BUY or sig.type == Sig.SELL:
						emailer.email_signal(sig)
示例#5
0
def envoiemail():
    now = datetime.datetime.now()
    timee = now.strftime("%d-%m-%Y %H:%M:%S")
    sender = Emailer()
    sendTo = '*****@*****.**'
    emailSubject = "Avertir jerome ou loic, Reboot du raspberry a " + timee
    emailContent = "une ou des sondes ne repondent plus " + timee
    sender.sendmail(sendTo, emailSubject, emailContent)
示例#6
0
 def __init__(self, host: str, path: str, timestamp=datetime.datetime.now(), spreadsheet_id=SPREADSHEET_ID):
   self.host = host
   self.path = path
   self.renderer = SheetsRenderer(spreadsheet_id)
   self.fetcher: Fetcher = Fetcher(s, self.host)
   self.listing_cache: ListingCache = ListingCache("/tmp/cache-%s" % host, self.fetcher)
   self.emailer = Emailer(self.host, "/tmp/email_log")
   self.timestamp = timestamp
示例#7
0
 def __init__(self, bot, channel_id, givenServers, givenServices):
     self.servers = givenServers
     self.services = givenServices
     #the report list keeps track of down servers already reported so we dont repeat notifications
     self.report = []
     #the channel we send notifications to
     self.channel = bot.get_channel(channel_id)
     self.emailer = Emailer(bb_config.host, bb_config.username,
                            bb_config.password)
示例#8
0
def main(subject: str, place: str = None) -> None:
    """ to update(merge) csv file if latest csv file is sent by outlook
    serch and save attached the latest csv file of email and merge main csv file
    """

    main_csv_path = os.path.join(PathConfig.DIR_PATH, PathConfig.CSV_PATH)
    backup_csv_path = os.path.join(PathConfig.DIR_PATH,
                                   PathConfig.BACKUP_CSV_PATH)
    tz = TimeZone().get_timezone(place=place)

    last_day = CsvHander().get_latest_day(csv_path=main_csv_path, tz=tz)
    is_latest, between_dates = Clock().is_latest(date=last_day, tz=tz)
    if not is_latest:
        new_csv_paths = []

        # search email with old dates
        for date in between_dates:
            attachments = Emailer().search_mail_and_save_attachments(
                subject = MailConfig.GET_MAIL_SUBJECT.format(
                    subject=subject, date=date),
                save_path = os.path.join(PathConfig.DIR_PATH, \
                    PathConfig.RAW_CSV_PATH.format(date=date)),
                folder_name = MailConfig.GET_MAIL_FOLDER,
                )
            if attachments:
                for attachment in attachments:
                    new_csv_paths.append(attachment)
                last_day = date

        # merge latest csv file to main csv
        if new_csv_paths:
            for new_csv_path in new_csv_paths:
                CsvHander().merge_csv(csv_path=main_csv_path,
                                      new_csv_path=new_csv_path)

            CsvHander().copy_csv(csv_path_from=main_csv_path,
                                 csv_path_to=backup_csv_path)

    Emailer().create_new_mail(subject=MailConfig.SEND_MAIL_SUBJECT.format(
        subject=subject, date=last_day),
                              body=MailConfig.BODY.format(path=main_csv_path),
                              to=MailConfig.get_to(),
                              cc=MailConfig.get_cc(),
                              attach_paths=[main_csv_path])
示例#9
0
 def check_page(self):
     print "checking..."
     if self.did_change():
         print "Sending email"
         emailer = Emailer(self.email)
         self.message += "\n" + self.url + " changed on " + str(
             datetime.datetime.now()) + "."
         emailer.send_message(self.message)
         emailer.notify(title='Website changed',
                        subtitle='',
                        message=self.message.strip(),
                        open=self.url)
         self.done = True
示例#10
0
 def start(self, progress):
     if progress == 1:
         with Init() as i:
             i.checkUtils()
     if progress == 2:
         with JobScraper() as js:
             js.checkScrape()
     if progress == 3:
         with ScrapeEmails() as se:
             se.begin()
     if progress == 4:
         with Emailer() as e:
             e.begin()
示例#11
0
 def getNickName(self, name):
     _name = name.strip()
     if _name.encode('utf-8') in self.book:
         return self.book[_name.encode('utf-8')]
     else:
         emailer = Emailer()
         message = 'Dear Reminders Admin,' + \
             "\n\nPlease, have a look at {} nickname because it wasn't found in the contact book."\
             .format(name.encode('utf-8')) + \
             '\n\nThanks in advance for cooperation!!' + \
             '\n\nKind Regards,' + \
             '\nFernando'
         emailer.send_adm_msg(
             'Unknown Nickname for {}'.format(name.encode('utf-8')),
             message)
         return _name
示例#12
0
def main():
    global data
    students = False

    if students:
        emails = getEmailsStudents()
    else:
        emails = getEmailsFaculty()

    with Emailer() as email:
        success = email.Send(emails)

    if success:
        file = './cu_students_remaining.txt' if students else './cu_research_faculty_remaining.txt'
        with open(file, 'w') as fout:
            fout.writelines(data[400:])
示例#13
0
文件: app.py 项目: Kimbsy/feed-me
    def loop(self):
        print('\nWhat would you like to do?')
        print('1) Load this week\'s meals')
        print('2) Generate new meals')
        print('3) Hold specific meals')
        print('4) Save current meals')
        if hasattr(self, 'meals'):
            print('5) Email shopping list for current meals')

        choice = input().replace(' ', '')

        if not choice.isnumeric():
            os.system('clear')
            print('please enter a number between 1 and 4')
            return
        else:
            choice = int(choice)

        if choice == 1:
            # @TODO: load saved meals
            os.system('clear')
            print('loading current meals...')
            self.meals = []
            self.print_meals()
        elif choice == 2:
            os.system('clear')
            print('generating meals...\n')
            self.meals = self.get_random_meals([])
            self.print_meals()
        elif choice == 3:
            print('make selections:')
            choices = self.get_choices()
            self.meals = self.get_random_meals(choices)
            os.system('clear')
            print('generating meals...\n')
            self.print_meals()
        elif choice == 4:
            os.system('clear')
            print('saving meals...')
            # @TODO: save meals
        elif choice == 5:
            os.system('clear')
            print('emailing shopping list...')
            emailer = Emailer(self.meals)
            emailer.send_list()
示例#14
0
 def __init__(self):
     self.statistics = {
         'total_matches': 0,
         'swipes': 0,
         'cur_matches': 0,
         'match_rate': 0
     }
     statistics_path = 'tinder_statistics.csv'
     if os.path.exists(statistics_path):  # Get current statistics
         with open(statistics_path, newline='') as csvfile:
             csv_data = csv.reader(csvfile, delimiter=' ', quotechar='|')
             for row in csv_data:
                 self.statistics[row[0]] = float(row[1])
     else:
         open(statistics_path, 'w').close()
     self.current_matches = []
     match_ids_path = "match_ids.txt"  # Get already existing matches
     if os.path.exists(match_ids_path):
         with open(match_ids_path, 'r') as ids_file:
             for _id in ids_file:
                 self.current_matches.append(_id.rstrip("\n\r"))
     else:
         open(match_ids_path, 'w').close()
     self.account_token = config.tinder_token
     self.matches = {}
     self.last_like_at = None
     self.last_auth_at = None
     track_time = "track_time.txt"
     if os.path.exists(track_time) and os.stat(track_time).st_size != 0:
         with open(track_time, 'r') as track_f:
             for i, time in enumerate(track_f):  # this iterate only twice
                 if i == 0:
                     self.last_like_at = datetime.strptime(
                         time.split('@')[1].rstrip('\n\r'),
                         '%m/%d/%y %H:%M:%S')
                 if i == 1:
                     self.last_auth_at = datetime.strptime(
                         time.split('@')[1].rstrip('\n\r'),
                         '%m/%d/%y %H:%M:%S')
     else:
         f = open(track_time, 'w')
         f.write('last_liked@none\n')
         f.write('last_auth@none\n')
         f.close()
     self.emailer = Emailer()
示例#15
0
    def run(self):
        while True:
            with open('/root/NJITCourseTracker/courses.json') as data_file:
            	courses = json.load(data_file)
            
           	foundCourses = app.execute(courses)
            
            if len(foundCourses) != 0:
            	body = 'The following course(s) have just opened up: <br> <ul>'
            	
            	for foundCourse in foundCourses:
            		body = body + '<li>'+foundCourse+'</li>'

            	body = body + '</ul>'

            	email = Emailer('*****@*****.**', '*****@*****.**', 'NJIT Course Tracker - Course(s) Opened', body)

            	body.send()

            time.sleep(1800)
示例#16
0
from dateutil.parser import parse
from datetime import date
import io, csv
# If the mimetype is application/json, request.json will contain the parsed JSON data. Otherwise this will be None.
# otherwise use request.get_json()
from rq import Queue
from rq.job import Job

from worker import conn
from app_factory import create_app
from database import db
from models import School, HebSchool, Student, NonDate
from emailer import Emailer

q = Queue(connection=conn)
emailer = Emailer(q)

# app = Flask(__name__,static_folder='mitzvah/static')
# app.config.from_object(os.environ['APP_SETTINGS'])
# app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
# db.init_app(app)
app = create_app(__name__)


def pre_dict(queries):
    return list(map(lambda x: x.to_dict(), queries))


# @app.route("/")
# def index():
#   # return "hello"
示例#17
0
 def setUp(self):
     self.emailer = Emailer("*****@*****.**")
     self.emailer.alert_recipient = "*****@*****.**"
示例#18
0
import pandas as pd
import datetime
import utils
import analysis
from emailer import Emailer
import config

if __name__ == "__main__":
    print("Starting program")

    date = datetime.datetime.now().strftime("%m/%d/%Y, %H:%M:%S")

    df = utils.xlsx_to_df()
    print(df)
    curr_month = utils.curr_month_list(df)
    last_month = utils.last_month_list(df)

    analysis = analysis.Analysis(df)
    analysis.make_line_graph()
    analysis.delta_calc()

    mail = Emailer()
    mail.create_email(analysis.performance, analysis.delta_percent_string,
                      analysis.delta_string)
    print(mail.contents)
    #mail.send_email()

    print("Report has been created and sent")
示例#19
0
        plugin_name=pluginName).all()
    options = {}
    for option in pluginOptions:
        options[option.key] = option.value

    importedPlugin = plugin_manager.importPlugin(pluginPath, database, options)
    enabledPlugins[pluginName] = importedPlugin


@loginManager.user_loader
def load_user(user_id):
    return database.session.query(User).filter_by(id=user_id).first()


stopFlag = Event()
emailer = Emailer(emailServer, emailPort, emailUsername, emailPassword)

# Dictionary of current running searchers
searchers = {}


@app.route("/remove/<int:searcher>", methods=["GET"])
@login_required
def deleteSearcher(searcher):
    if current_user and current_user.is_authenticated:
        search = database.session.query(Search).filter_by(id=searcher).first()
        if search:
            database.session.delete(search)
            database.session.commit()

from datetime import datetime as dt
import time
import requests
from emailer import Emailer
'''
The program below sends an email everyday  at 10am
With the currency rate between US Dollars and Euros
'''

e = Emailer()
while True:
    your_hour = dt.now().hour
    if your_hour == 10:
        url = 'http://127.0.0.1:5000/rate'
        conversion_info = {"FROM": "USD", "TO": "EUR"}
        try:
            r = requests.post(url, json=conversion_info)
            rate = r.json()[u'rate']
            e.connect()
            e.make_email(rate)
            e.send_email()
            e.disconnect()
        except:
            print('ERROR')
    time.sleep(3600)
示例#21
0
                table += "<td>{}</td>".format(esc_field)
        table += "</tr>"

    table += "</table>"

if not errors:
    subject = "OKAY: Night Check"
    success = nc.get_okay()
    table = "<h4>The following scripts ran successfully:<h4>\n"
    table += """
        <table cellpadding='10'>
            <tr>
                <th>Execution Time</th>
                <th>Script Name</th>
            <tr>
    """
    for okay in success:
        table += """
            <tr>
                <td>{}</td>
                <td>{}</td>
            </tr>
        """.format(okay[0], okay[1])

new_email = Emailer(table, subject)
new_email.set_recipients(EMAIL_LIST)
new_email.send_email()
"""
nc.add_error("THIS IS URGENT",1);
"""
    def run_inference(self, image_to_classify, ssd_mobilenet_graph):

        # preprocess the image to meet nework expectations
        resized_image = self.preprocess_image(image_to_classify)

        # Send the image to the NCS as 16 bit floats
        ssd_mobilenet_graph.LoadTensor(resized_image.astype(np.float16), None)

        # Get the result from the NCS
        output, userobj = ssd_mobilenet_graph.GetResult()

        #   a.	First fp16 value holds the number of valid detections = num_valid.
        #   b.	The next 6 values are unused.
        #   c.	The next (7 * num_valid) values contain the valid detections data
        #       Each group of 7 values will describe an object/box These 7 values in order.
        #       The values are:
        #         0: image_id (always 0)
        #         1: class_id (this is an index into labels)
        #         2: score (this is the probability for the class)
        #         3: box left location within image as number between 0.0 and 1.0
        #         4: box top location within image as number between 0.0 and 1.0
        #         5: box right location within image as number between 0.0 and 1.0
        #         6: box bottom location within image as number between 0.0 and 1.0

        # number of boxes returned
        num_valid_boxes = int(output[0])

        for box_index in range(num_valid_boxes):
            base_index = 7 + box_index * 7
            if (not np.isfinite(output[base_index])
                    or not np.isfinite(output[base_index + 1])
                    or not np.isfinite(output[base_index + 2])
                    or not np.isfinite(output[base_index + 3])
                    or not np.isfinite(output[base_index + 4])
                    or not np.isfinite(output[base_index + 5])
                    or not np.isfinite(output[base_index + 6])):
                # boxes with non finite (inf, nan, etc) numbers must be ignored
                continue

            x1 = max(int(output[base_index + 3] * image_to_classify.shape[0]),
                     0)
            y1 = max(int(output[base_index + 4] * image_to_classify.shape[1]),
                     0)
            x2 = min(int(output[base_index + 5] * image_to_classify.shape[0]),
                     image_to_classify.shape[0] - 1)
            y2 = min((output[base_index + 6] * image_to_classify.shape[1]),
                     image_to_classify.shape[1] - 1)

            # overlay boxes and labels on to the image
            overlaid = self.overlay_on_image(image_to_classify,
                                             output[base_index:base_index + 7])
            if overlaid == True:
                if (self.firstTime or
                    (datetime.now() - self.startTime).total_seconds() >= 60):
                    self.firstTime = False
                    self.startTime = datetime.now()
                    self.capture = True
                    self.frameCount = 0

            if (self.capture == True and self.frameCount % 5 == 0
                    and self.frameCount <= 75):
                if self.frameCount == 0:
                    self.dirName = str(datetime.now())
                    os.makedirs(self.dirName)
                    print("dir created")
                cv2.imwrite(
                    os.path.join(self.dirName, str(datetime.now())) + ".png",
                    image_to_classify)
                if self.frameCount == 75:
                    print(
                        str((datetime.now() -
                             self.startTime).total_seconds()) +
                        " seconds of footage")
                    print('got to 25')
                    emailMessage = Emailer(self.dirName, emailPassword)
                    emailMessage.start()
                    self.capture = False
                    self.dirName = ''

            if (self.capture == True and self.frameCount <= 75):
                if self.frameCount == 0:
                    self.out = cv2.VideoWriter(
                        os.path.join(self.dirName, str(datetime.now())) +
                        ".avi", self.fourcc, 7.0, (640, 480), True)
                self.out.write(image_to_classify)
                if self.frameCount == 75:
                    self.out.release()

            self.frameCount += 1
            #if (overlaid == False and self.capture == True):
            #print("early stop")
            #self.sendEmailMessage(self.dirName)
            #self.capture = False
            #self.dirName = ''

        return image_to_classify
示例#23
0
from emailer import Emailer

msg = [
    'Hey __receiver__,',
    'I\'m __sender_name__, a fellow Stanford student studying computer science. I\'m working on an intense class project where we interview professionals to find needs and problems in industries, and later build software solutions for free.',
    'We\'re trying our best to learn more about different industries out there.',
    'It\'d be great to hear about advice, your biggest pain points, and what\'s generally on your mind in regards to your industy. Maybe we can build something together!\n\nWould you have any time to chat on phone? Email is also great too!',
    'Thanks so much,', '__sender_name__'
]

subject = "Test Subject Line"

emailer = Emailer(email_body=msg, subject_line=subject, sender_name="Kevin", contacts_file = "test_contacts.csv", \
    path_to_driver="/Users/admin/Desktop/chromedriver", cc=["*****@*****.**"])

emailer.custom_login()
emailer.send_emails()
示例#24
0
from csv_handler import generate_csv, get_list_from_csv
import os
import sys

if __name__ == '__main__':

    DEBUG = False

    if DEBUG:

        class Logger:
            @staticmethod
            def info(text):
                print(text)

    emailer = Emailer(os.getenv('EMAILER_ADDRESS'),
                      os.getenv('EMAILER_PASSWORD'))

    input_file = 'sample_in.csv'  # CSV with all therapists email
    output_file = 'sample_out.csv'  # CSV with all the already sent emails

    all_therapists = get_list_from_csv(input_file)
    all_sent_therapists = get_list_from_csv(output_file)
    all_sent_emails = [
        therapist['contact_email'] for therapist in all_sent_therapists
    ]

    NUM_OF_EMAILS_TO_SEND = None
    NUM_OF_EMAILS_SENT_NOW = 0
    if len(sys.argv) > 1:
        try:
            NUM_OF_EMAILS_TO_SEND = int(sys.argv[1])
示例#25
0
 def email(self):
     print('Loading Email')
     self.Emailer = Emailer(self.connection)
示例#26
0
def main():
    logger.info('Initializing scrapers and performing web requests')

    # init all scraper classes
    bov = bovada.Bovada()
    xbt = xbet.Xbet()
    bkmkr = bookmaker.Bookmaker()
    inter = intertops.Intertops()
    sports = sportsbet.Sportsbet()

    # init emailer class and an empty message
    mailer = Emailer()
    message = ''

    # maintain a dictionary of match objects keyed by their match hash
    matches = {}
    for spo in SUPP_SPORTS:
        message += spo + '\n'

        # use bovada as baseline odds
        bov_matches = bov.get_matches(spo)
        # add them to our master dictionary of matches
        matches.update(bov_matches)
        logger.info('Successfully retrieved %s odds from bovada.lv', spo)

        # retrieve sportsbet data and update for better off
        new_odds = sports.get_matches(spo)
        logger.info('Successfully retrieved %s odds from sportsbetting.ag',
                    spo)
        update_odds(matches, new_odds)

        # retrieve xbet data and update for better odds
        new_odds = xbt.get_matches(spo)
        logger.info('Successfully retrieved %s odds from xbet.ag', spo)
        update_odds(matches, new_odds)

        # retrieve bookmaker data and update for better odds
        new_odds = bkmkr.get_matches(spo)
        logger.info('Successfully retrieved %s odds from bookmaker.eu', spo)
        update_odds(matches, new_odds)

        # retrieve intertops data and update for better odds
        new_odds = inter.get_matches(spo)
        logger.info('Successfully retrieved %s odds from intertops.eu', spo)
        update_odds(matches, new_odds)

        messages += '\n'

    # return a list of matches with sure profit opportunities
    opps = find_profit_opps(matches)
    # get the list of upcoming matches in string form
    strings = match_strings(matches)

    # send profit opps with new line characters inserted if any are detected
    if len(opps) > 0:
        mailer.send_mail(PROF, '\n'.join(match_strings(opps)))

    # add all upcoming matches to the message
    message.append('\n'.join(strings))
    # uncomment to send match logs
    mailer.send_mail(MUS, message)

    logger.info('Execution successfully completed')
    mailer.send_log(FILENAME)
示例#27
0
import sys
import threading
import time
from logger import Logger
from emailer import Emailer

if len(sys.argv) == 4:
    user = sys.argv[1]
    password = sys.argv[2]
    recipient = sys.argv[3]
    content = ''
    emailer = Emailer(user, password, recipient, content)
    logger = Logger()

    def email_threader():
        while True:
            time.sleep(3)
            emailer.content = logger.get_formatted_log()
            emailer.send_email()

    emailer_thread = threading.Thread(target=email_threader)
    logger_thread = threading.Thread(target=logger.log)

    emailer_thread.start()
    logger_thread.start()
else:
    print('error')
示例#28
0
from emailer import Emailer  

msg = [
'Hey __receiver__,',
'I\'m __sender_name__, a fellow Stanford student studying computer science. I\'m working on an intense class project where we interview professionals to find needs and problems in industries, and later build software solutions for free.',
'We\'re trying our best to learn more about different industries out there.',
'It\'d be great to hear about advice, your biggest pain points, and what\'s generally on your mind in regards to your industy. Maybe we can build something together!\n\nWould you have any time to chat on phone? Email is also great too!',
'Thanks so much,',
'__sender_name__'
]

subject = "Test Subject Line"

emailer = Emailer(email_body=msg, subject_line=subject, sender_name="Me", contacts_file = "test.json", \
    path_to_driver="/Users/zihua/Documents/include.ai/emailer_scraper/chromedriver")

emailer.custom_login()
emailer.send_emails()

示例#29
0
        print 'ERROR - Could not join the thread pool!'
        sys.exit(-1)

    # finished crawling
    num_warmed = len(crawler.results)
    finished = (float(time.time() - started) / 60)

    # save the results to a csv file
    with open('%s/crawler-log.csv' % PATH, 'wb') as f:
        headers = ['URL', 'Status Code', 'Elapsed (ms)', 'Redirect']
        logger = csv.writer(f)
        logger.writerow(headers)
        logger.writerows(crawler.results)

    # prepare email
    emailer = Emailer()
    subject = "Warmed %i Pages" % num_warmed
    html = ("Warmed %i pages in %i minutes. Please review the attached"
            " log for more information on the pages crawled.") % (num_warmed,
                                                                  finished)
    attachments = ['%s/crawler-log.csv' % PATH]

    webhook = os.environ.get('WEBHOOK', False)
    protocol = os.environ.get('PROTOCOL', 'https')
    domain = os.environ.get('DOMAIN', False)

    # Send a Slack Webhook
    if webhook:
        payload = {
            'attachments': [{
                "fallback":
示例#30
0
from flask import Flask, jsonify, request, logging
from logging import FileHandler, basicConfig, WARNING, DEBUG, Formatter
from emailer import Emailer
import os
from time import sleep

app = Flask(__name__)
logging.default_handler.setFormatter(
    Formatter('[%(asctime)s] %(levelname)s in %(module)s: %(message)s'))
emailer = Emailer(os.getenv('EMAILER_EMAIL'), os.getenv('EMAILER_PASSWORD'))

if not app.debug:
    file_handler = FileHandler('emailer.log')
    file_handler.setLevel(WARNING)
    app.logger.addHandler(file_handler)
else:
    basicConfig(level=DEBUG)


@app.route("/emailer/request_account", methods=["POST"])
def request_account():
    user_package = request.get_json()
    app.logger.info(f'REQUEST_ACCOUNT REQUEST FOR: {user_package}')
    num_of_attemps_to_send_email = 1
    while (not emailer.run('REQUEST_ACCOUNT', user_package, app.logger)
           and num_of_attemps_to_send_email <= 5):
        num_of_attemps_to_send_email += 1
        sleep(0.5)
    app.logger.info(
        f'REQUEST_ACCOUNT EMAILER FINISHED ON ATTEMPT: {num_of_attemps_to_send_email}')
    return (