コード例 #1
0
def alarm_end(alarm_time: datetime.datetime, alarm: dict, news_call: bool,
              weather_call: bool) -> None:
    """
    This function runs when an alarm has gone off. The notification and log
    dictionaries are created including the necessary alarm data. 
    If the user has checked news and weather checkboxes then news and weather information
    will be played. Covid Data Nwews will be plaayed on every alarm
    """
    # Alarm Go off notification created
    alarm_notification = ({
        'timestamp': time.strftime('%H:%M:%S'),
        'type': 'Alarm',
        'title': ' Alarm scheduled for ' + str(alarm_time) + ' has gone off.',
        'description': ''
    })
    alarm_log = ({
        'timestamp': time.strftime('%H:%M:%S'),
        'type': 'alarm',
        'description':
        'Alarm scheduled for ' + str(alarm_time) + ' has gone off.',
        'error': ''
    })
    new_notification(alarm_notification)
    info_log(alarm_log)
    tts("Alarm  " + str(alarm_time) + "has gone off")
    if news_call == True:
        get_news(True)
    if weather_call == True:
        get_weather(True)
    get_covid_data(True)
コード例 #2
0
def delete_alarm(alarmToBeDeleted):
    """
    This function takes an alarm argument which is to be deleted.
    Creates a new alarms object. The old alarms gets daved in "alarms_list"
    If no alarms are there then it will instantiate a new clean object "alarm_list"
    The for loop iterates through
    each alarm. If an alarm time is found that is not equal to the time
    the user has requested to delete, that alarm object is appended to
    a new list 'new_alarm_objects'.The edited list of alarms is then
    written to the json file and the start alarm thread is reset.
    """
    new_alarm_objects = []

    with open(tmpdir + '/alarms.json', 'r') as alarms_file:
        try:
            alarm_list = json.load(alarms_file)
        except Exception:
            alarm_list = []
            error_log(Exception)

        for alarm in alarm_list:
            if alarm['title'] != alarmToBeDeleted:
                new_alarm_objects.append(alarm)

    with open(tmpdir + '/alarms.json', 'w') as alarms_file:
        json.dump(new_alarm_objects, alarms_file, indent=2)
    info_log("deleted alarm" + alarmToBeDeleted)
コード例 #3
0
ファイル: stock_basic.py プロジェクト: fenglilee/trade
def get_stock_basic(list_status='L', fields='ts_code,name,area,industry'):
    try:
        with scheduler.app.app_context():
            pro = ts.pro_api()
            try:
                data = pro.stock_basic(list_status=list_status, fields=fields)
            except Exception as e:
                data = None

            if data is None:
                return

            data = data.dropna(axis=0, how='any')
            records = data.to_dict(orient='records')
            for record in records:
                ins = StockBasic.find_one(ts_code=record['ts_code'])
                if ins is None:
                    StockBasic.create(commit=False, **record)
                else:
                    ins.update(commit=False, **record)
            else:
                db.session.commit()
                info_log('update stock basic succeed')
    except Exception as e:
        error_log('update stock basic failed: %s' % (repr(e),), exc_info=True)
コード例 #4
0
def clearAll():
    """
    This function calls all clearing functions from all modules
    """
    clearAllNotification()
    clearAllWeather()
    clearNews()
    clearAlarms()
    clear_covid_news()
    clearLogs()
    info_log("Cleared all .json files")
    return redirect('/')
コード例 #5
0
def get_weather(tts_enabled: bool) -> None:
    """
    This function fetches the weather data from openweathermap using
    api key provided in "config.json" and stores the data in 
    "weather.json" 
    New Notification and info log is created each time new data is fetched
    """
    # location
    location = 'New Delhi'
    api_key = get_api_key()
    url = 'https://api.openweathermap.org/data/2.5/weather?q={} \
    &appid={}&units=metric'.format(location, api_key)
    new_weather = requests.get(url).json()
    with open('assets/weather.json', 'w') as weather_file:
        json.dump(new_weather, weather_file, indent=2)
    weather_notification = ({
        'timestamp':
        time.strftime('%H:%M:%S'),
        'type':
        'Weather',
        'title':
        'Current temperature in ' + new_weather['name'] + ' is ' +
        str(new_weather['main']['temp']) + "\n Minimum Temperature is " +
        str(new_weather['main']['temp_min']) + "\n and " +
        "\n  Maximum Temperature is " + str(new_weather['main']['temp_max']),
        'description':
        ''
    })
    weather_log = ({
        'timestamp':
        time.strftime('%H:%M:%S'),
        'type':
        'weather',
        'description':
        'Current Weather in ' + new_weather['name'] + ' has been updated.',
        'error':
        ''
    })
    new_notification(weather_notification)
    info_log(weather_log)
    if tts_enabled:
        try:
            tts('Current temperature in ' + new_weather['name'] + 'is' +
                str(new_weather['main']['temp']) + "Minimum Temperature is" +
                str(new_weather['main']['temp_min']) + "and" +
                "Maximum Temperature is" +
                str(new_weather['main']['temp_max']))
        except RuntimeError:
            error_log(RuntimeError)
    with open('assets/weather.json', 'w') as weather_file:
        json.dump(new_weather, weather_file, indent=2)
コード例 #6
0
def get_covid_data(tts_enabled: bool):
    """
    This function fetches data from api.coronavirus.data.gov using
    get method in requests module, creates a dictionary and store it 
    in "covid_notifications.json" file.
    New Notification and info log is created each time new data is found
    """
    url = "https://api.covid19india.org/v4/data-2020-12-04.json"

    data = requests.get(url).json()
    new_covid_data = data['DL']

    with open('assets/covid_notifications.json', 'w') as covid_file:
        json.dump(new_covid_data, covid_file, indent=2)

        new_covid_notification = ({
            'timestamp':
            time.strftime('%H:%M:%S'),
            'type':
            'Covid News',
            'title':
            "Covid News for Delhi" + " with" + " Total confirmed cases " +
            str(new_covid_data['total']['confirmed']) +
            " Todays confirmed cases " +
            str(new_covid_data['delta']['confirmed'])
        })

        covid_logs = ({
            'timestamp': time.strftime('%H:%M:%S'),
            'type': 'Covid News',
            'description': "New Covid Data for Delhi",
            'error': ''
        })
        new_notification(new_covid_notification)
        info_log(covid_logs)
        if tts_enabled:
            try:
                tts("Covid News for Delhi" + " with " +
                    " Total confirmed cases " +
                    str(new_covid_data['total']['confirmed']) +
                    " Todays confirmed cases " +
                    str(new_covid_data['delta']['confirmed']))
            except RuntimeError:
                error_log(RuntimeError)

    with open('assets/covid_notifications.json', 'w') as covid_file:
        json.dump(new_covid_data, covid_file, indent=2)
コード例 #7
0
def get_big_deal():
    try:
        with scheduler.app.app_context():
            stock_set = StockBasic.find_all()
            now = datetime.now()
            for stock in stock_set:
                ts_code = stock.ts_code
                code, _ = ts_code.split('.')
                try:
                    data = ts.get_sina_dd(code,
                                          date=datetime.strftime(
                                              now, DATE_FORMAT))
                except Exception as e:
                    data = None

                if data is None:
                    continue

                try:
                    data = data.dropna(axis=0, how='any')
                    data = data.loc[:, ['price', 'volume', 'type']]
                    records = data.to_dict(orient='records')
                    for record in records:
                        BigDeal.create(commit=False,
                                       ts_code=ts_code,
                                       date=now.date(),
                                       price=record['price'],
                                       volume=record['volume'],
                                       trade_type=record['type'])
                    else:
                        db.session.commit()
                        info_log('get %s trade data succeed' % (ts_code, ))
                except Exception as e:
                    error_log('get %s trade data failed: %s' %
                              (ts_code, repr(e)),
                              exc_info=True)

                random_int = random.randint(1, 10)
                time.sleep(random_int)

    except Exception as e:
        error_log(repr(e), exc_info=True)
コード例 #8
0
def get_news(tts_enbled: bool) -> None:
    """
    This function fetches the weather data from newssapi using
    api key provided in "config.json" and stores the data in 
    "news.json" 
    New Notification and info log is created each time new data is fetched
    """
    api_key = get_api_key()
    country = 'in'
    url = 'https://newsapi.org/v2/top-headlines?country={}&apiKey={}' \
        .format(country, api_key)
    new_news = requests.get(url).json()
    with open('assets/news.json', 'w') as news_file:
        json.dump(new_news, news_file, indent=2)

    for i in range(3):
        news_notification = ({
            'timestamp': time.strftime('%H:%M:%S'),
            'type': 'News',
            'title': new_news['articles'][i]['title'],
            'description': ''
        })
        news_log = ({
            'timestamp':
            time.strftime('%H:%M:%S'),
            'type':
            'news',
            'description':
            'New news articles' + new_news['articles'][i]['title'],
            'error':
            ''
        })
        new_notification(news_notification)
        info_log(news_log)
        if (tts_enbled):
            try:
                tts('New news story.' + new_news['articles'][i]['title'])
            except RuntimeError:
                error_log(RuntimeError)

    with open('assets/news.json', 'w') as news_file:
        json.dump(new_news, news_file, indent=2)