У меня есть приложение Python в flask, которое имеет функцию, которая запрашивает данные из API графиков Instagram и сохраняет их в базе данных с интервалом 43200 секунд (12 часов). Затем он сохраняет результат запроса (УСПЕХ или ОШИБКА) в текстовом файле вместе с отметкой времени и указанием ошибки, если запрос не выполнен. Когда запрос не удается, я отправляю электронное письмо с помощью библиотеки simplegmail на свою учетную запись Gmail, чтобы уведомить меня об ошибке.
Похоже, что функция работает нормально. Однако каждый день около 18:30 я получаю электронное письмо об ошибке от моего приложения (даже если приложение не запущено), в котором говорится, что мой запрос не выполнен и что ошибка — [Errno 32] Broken Pipe. Как это возможно? Работает ли моя функция, даже если мое приложение — нет? Я изо всех сил пытаюсь решить проблему. Ниже приведен фрагмент кода, обрабатывающий периодические запросы.
def my_scheduled_task():
with app.app_context(): # Push the app context
file_path = "static/instagram_api_log.txt"
token_record = Token.query.first()
if token_record:
access_token = token_record.access_token
params = {'access_token': access_token}
user_data_df = get_media(source_url, page_id, params)
if user_data_df is not None:
try:
save_media_to_database(user_data_df)
missing_days_profile_visits_len = check_for_missing_dates(ProfileVisit)
profile_views_data = get_profile_views(source_url, page_id, params, missing_days_profile_visits_len)
save_profile_visits(profile_views_data)
missing_days_profile_reach_len = check_for_missing_dates(ProfileReach)
profile_reach_data = get_profile_reach_per_day(source_url, page_id, params,
missing_days_profile_reach_len)
save_profile_reach(profile_reach_data)
profile_follows_data = get_follows_per_day(source_url, page_id, params)
save_profile_follows(profile_follows_data)
success_message = "SUCCESS!"
current_time = datetime.now()
with open(file_path, 'a') as file:
# Append the current date and time to the file
file.write(str(current_time) + " " + success_message + "\n")
except Exception as e:
error_message = f"ERROR! - Unknown error occurred in {e.__class__.__name__}: {str(e)}"
current_time = datetime.now()
with open(file_path, 'a') as file:
# Append the current date and time to the file
file.write(str(current_time) + " " + error_message + "\n")
admin_emails = User.get_admin_emails()
for email in admin_emails:
send_mail(email, "Instagram API Query Error", str(current_time) + " " + error_message + "\n")
else:
error_message = "ERROR! - get_media function returned None!"
current_time = datetime.now()
with open(file_path, 'a') as file:
# Append the current date and time to the file
file.write(str(current_time) + " " + error_message + "\n")
admin_emails = User.get_admin_emails()
for email in admin_emails:
send_mail(email, "Instagram API Query Error", str(current_time) + " " + error_message + "\n")
else:
error_message = "ERROR! - No access token found! Check the database or update your auth token!"
current_time = datetime.now()
with open(file_path, 'a') as file:
# Append the current date and time to the file
file.write(str(current_time) + " " + error_message + "\n")
admin_emails = User.get_admin_emails()
for email in admin_emails:
send_mail(email, "Instagram API Query Error", str(current_time) + " " + error_message + "\n")
# Create a scheduler instance
scheduler = BackgroundScheduler()
# Call the task immediately for debugging purposes
my_scheduled_task()
# Add a job to the scheduler
scheduler.add_job(my_scheduled_task, IntervalTrigger(seconds=43200))
# Start the scheduler
scheduler.start()
Подробнее здесь: https://stackoverflow.com/questions/792 ... -shut-down
Код Python выполняется, когда приложение закрывается? ⇐ Python
Программы на Python
-
Anonymous
1733306035
Anonymous
У меня есть приложение Python в flask, которое имеет функцию, которая запрашивает данные из API графиков Instagram и сохраняет их в базе данных с интервалом 43200 секунд (12 часов). Затем он сохраняет результат запроса (УСПЕХ или ОШИБКА) в текстовом файле вместе с отметкой времени и указанием ошибки, если запрос не выполнен. Когда запрос не удается, я отправляю электронное письмо с помощью библиотеки simplegmail на свою учетную запись Gmail, чтобы уведомить меня об ошибке.
Похоже, что функция работает нормально. Однако каждый день около 18:30 я получаю электронное письмо об ошибке от моего приложения (даже если приложение не запущено), в котором говорится, что мой запрос не выполнен и что ошибка — [Errno 32] Broken Pipe. Как это возможно? Работает ли моя функция, даже если мое приложение — нет? Я изо всех сил пытаюсь решить проблему. Ниже приведен фрагмент кода, обрабатывающий периодические запросы.
def my_scheduled_task():
with app.app_context(): # Push the app context
file_path = "static/instagram_api_log.txt"
token_record = Token.query.first()
if token_record:
access_token = token_record.access_token
params = {'access_token': access_token}
user_data_df = get_media(source_url, page_id, params)
if user_data_df is not None:
try:
save_media_to_database(user_data_df)
missing_days_profile_visits_len = check_for_missing_dates(ProfileVisit)
profile_views_data = get_profile_views(source_url, page_id, params, missing_days_profile_visits_len)
save_profile_visits(profile_views_data)
missing_days_profile_reach_len = check_for_missing_dates(ProfileReach)
profile_reach_data = get_profile_reach_per_day(source_url, page_id, params,
missing_days_profile_reach_len)
save_profile_reach(profile_reach_data)
profile_follows_data = get_follows_per_day(source_url, page_id, params)
save_profile_follows(profile_follows_data)
success_message = "SUCCESS!"
current_time = datetime.now()
with open(file_path, 'a') as file:
# Append the current date and time to the file
file.write(str(current_time) + " " + success_message + "\n")
except Exception as e:
error_message = f"ERROR! - Unknown error occurred in {e.__class__.__name__}: {str(e)}"
current_time = datetime.now()
with open(file_path, 'a') as file:
# Append the current date and time to the file
file.write(str(current_time) + " " + error_message + "\n")
admin_emails = User.get_admin_emails()
for email in admin_emails:
send_mail(email, "Instagram API Query Error", str(current_time) + " " + error_message + "\n")
else:
error_message = "ERROR! - get_media function returned None!"
current_time = datetime.now()
with open(file_path, 'a') as file:
# Append the current date and time to the file
file.write(str(current_time) + " " + error_message + "\n")
admin_emails = User.get_admin_emails()
for email in admin_emails:
send_mail(email, "Instagram API Query Error", str(current_time) + " " + error_message + "\n")
else:
error_message = "ERROR! - No access token found! Check the database or update your auth token!"
current_time = datetime.now()
with open(file_path, 'a') as file:
# Append the current date and time to the file
file.write(str(current_time) + " " + error_message + "\n")
admin_emails = User.get_admin_emails()
for email in admin_emails:
send_mail(email, "Instagram API Query Error", str(current_time) + " " + error_message + "\n")
# Create a scheduler instance
scheduler = BackgroundScheduler()
# Call the task immediately for debugging purposes
my_scheduled_task()
# Add a job to the scheduler
scheduler.add_job(my_scheduled_task, IntervalTrigger(seconds=43200))
# Start the scheduler
scheduler.start()
Подробнее здесь: [url]https://stackoverflow.com/questions/79250628/python-code-executing-when-app-is-shut-down[/url]
Ответить
1 сообщение
• Страница 1 из 1
Перейти
- Кемерово-IT
- ↳ Javascript
- ↳ C#
- ↳ JAVA
- ↳ Elasticsearch aggregation
- ↳ Python
- ↳ Php
- ↳ Android
- ↳ Html
- ↳ Jquery
- ↳ C++
- ↳ IOS
- ↳ CSS
- ↳ Excel
- ↳ Linux
- ↳ Apache
- ↳ MySql
- Детский мир
- Для души
- ↳ Музыкальные инструменты даром
- ↳ Печатная продукция даром
- Внешняя красота и здоровье
- ↳ Одежда и обувь для взрослых даром
- ↳ Товары для здоровья
- ↳ Физкультура и спорт
- Техника - даром!
- ↳ Автомобилистам
- ↳ Компьютерная техника
- ↳ Плиты: газовые и электрические
- ↳ Холодильники
- ↳ Стиральные машины
- ↳ Телевизоры
- ↳ Телефоны, смартфоны, плашеты
- ↳ Швейные машинки
- ↳ Прочая электроника и техника
- ↳ Фототехника
- Ремонт и интерьер
- ↳ Стройматериалы, инструмент
- ↳ Мебель и предметы интерьера даром
- ↳ Cантехника
- Другие темы
- ↳ Разное даром
- ↳ Давай меняться!
- ↳ Отдам\возьму за копеечку
- ↳ Работа и подработка в Кемерове
- ↳ Давай с тобой поговорим...
Мобильная версия