Код Python выполняется, когда приложение закрывается?Python

Программы на Python
Ответить
Anonymous
 Код Python выполняется, когда приложение закрывается?

Сообщение 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()


Подробнее здесь: https://stackoverflow.com/questions/792 ... -shut-down
Ответить

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

Вернуться в «Python»