Beispiel #1
0
 def parse(self, response):
     '''
     Will be called to handle the response downloaded for each of the
     requests made.
     :param response:  holds the page content
     :return:
     '''
     formatted_items = self.format_items(self.parse_helper(response))
     send_mail(formatted_items.encode('utf-8'))
Beispiel #2
0
def main():
    seoul_timezone = datetime.timezone(datetime.timedelta(hours=9))
    date = datetime.datetime.now(tz=seoul_timezone).strftime('%Y-%m-%d %H:%M')
    csv_file = 'low_price_list.csv'
    re = []

    # read configuration
    with open('config.json', 'r') as jsonf:
        config = json.load(jsonf)  # dict

    cred = credentials.Certificate(config['db_api_key'])
    firebase_admin.initialize_app(cred, {
        'databaseURL': config['db_address']
    })

    sales = db.reference(config['db_ref'])
    get_db = sales.get()

    for i in get_db:
        re.append(get_low_price(get_db[i]['url'],date))

    is_exists = os.path.exists('./low_price_list.csv')
    previous_dic = {}
    diff_dic = {}

    if is_exists:
        with open(csv_file, newline='') as f:
            reader = csv.DictReader(f)
            for row in reader:
                key = row['product_name']
                previous_dic[key] = row

    with open(csv_file, 'w', encoding='utf-8', newline='') as f:
        fieldnames = ['date','product_name', 'low_price', 'product_link']
        writer = csv.DictWriter(f, fieldnames=fieldnames)
        writer.writeheader()

        for item in re:
            writer.writerow(item)
            product_name = item['product_name']

            if product_name in previous_dic:
                pre_price = previous_dic[product_name]['low_price']
                if int(pre_price) > int(item['low_price']):
                    diff_dic[product_name] = item
                    diff_dic[product_name]['previous_price'] = pre_price

    make_excel()

    if len(diff_dic) > 0:
        print('Sending mail:')
        # read email-related configuration from file
        send_mail(config['to'], diff_dic, config['id'], config['pwd'])
Beispiel #3
0
def handle_add_member():
    """
    Handle adding new members to the database.
    Not all arguments has to be specified in order for a user to be added.
    Only id and name is required.
    """
    args = request.args

    required_arguments = ["id", "name"]
    optional_arguments = ["email", "joined", "receive_email"]
    optional_default = ["{}@student.liu.se".format(args["id"]),
            datetime.date.today().isoformat(), "1"]

    member_args = []

    for required_argument in required_arguments:
        if required_argument not in args:
            return f"No '{required_argument}' specifed", 400
        else:
            member_args.append(args[required_argument])

    for optional_argument, default in zip(optional_arguments, optional_default):
        if optional_argument not in args:
            member_args.append(default)
        else:
            member_args.append(args[optional_argument])

    success, message = add_member(*member_args)

    if success:
        for action in ACTIONS:
            add_link(args["id"], action)

        if SENDER_PASSWORD != "dev":

            with open("email-templates/welcome.html") as f:
                html = f.read()

            send_mail(
                get_mailing_list(args["id"]),
                "Welcome to LiTHe kod!",
                html,
                get_links()
            )

    return message, 200 if success else 400
Beispiel #4
0
    def emergencyAlert(self, *args):
        self.root.ids.fall_indicator01.text = 'FALL DETECTED!! WARNING'
        self.alertClock.cancel()
        self.dialog.dismiss()
        emerg_email = self.root.ids.contact01.text

        send_mail('*****@*****.**', emerg_email, 'sweNotify',
                  username)

        Snackbar(
            text=
            f'ALERT >>> {emerg_email} has been notified of the fall!!! <<<',
        ).show()

        MDDialog(
            title='Notification Sent',
            text=f'ALERT >>> {emerg_email} has been notified of the fall!!! <<<'
        ).open()
def main():
    # get release codes from csv
    release_codes = [
        c for code in read_csv(r'data/release_codes.csv') for c in code
    ]
    # create urls for web scraping
    urls = [
        'https://www.discogs.com/de/sell/release/{}?ev=rb'.format(r)
        for r in release_codes
    ]
    # web scraping
    current_offers = list(get_offers_from_dicogs(urls))
    # get last offers from csv
    last_offers = read_csv(r'data/offers.csv')
    # compare results from web scraping (current offers) with last offers
    # and only send mail if there are any changes
    if not current_offers == last_offers:
        mail_string = '\n\n'.join(
            [' '.join(offer) for offer in current_offers])
        emailer.send_mail(mail_string)
        write_csv(current_offers)
Beispiel #6
0
def main(k):
    
    response_weather = query_weather_api(k.locations)
    vedur = response_weather.json()['results']
    alert = list()
    for i in range(len(vedur)):
        location_id = int(vedur[i]['id'])
        link = vedur[i]['link']
        
        utgafutimi = vedur[i]['atime']
        df = pd.DataFrame(vedur[i]['forecast'])
        df['ftime'] = df['ftime'].astype('datetime64[s]')
        df['F'] = df['F'].astype('float')
        
        # Set the index to a DateTimeIndex so we can filter by hour
        df.set_index(pd.DatetimeIndex(df['ftime']), inplace=True)
        df.index.names=['index']
        df = hour_range_filter(df, k.hour_range)
        
        # Get the first date
        day = df['ftime'].iloc[0]

        for i in range(0, check_days):
            df_day = df[df.ftime.dt.day == day.day]
            # Call day_check with a dataframe for each day
            message = day_check(df_day, k, location_id, link, utgafutimi, day)
            if message:
                message = "Spá gefin út: " + utgafutimi + '\n' + message
                alert.append(message)
            # Iterate to the next day
            day += pd.DateOffset(days=1)
    
    print("\n".join(alert))
    if alert:
        try:
            send_mail("\n".join(alert), [k.email])
        except NameError as e:
            print("Not sending email")
Beispiel #7
0
    def test_send_mail_success(self):
        # arrange
        # mail_sender.return_value = mail_sender_send
        body = '''
                <div class="list"><div class="item">
                <p class="price">hello</p>
                <a href="foobar">hi</a>
                </div>
                </div>
                '''

        # act
        with mock.patch.object(scrapy.mail.MailSender, 'send', return_value='Success'):
            response = emailer.send_mail(body)

        # assert
            self.assertEqual(response, 'Success')