Python 在Flask中的后台运行进程

Python 在Flask中的后台运行进程,python,flask,Python,Flask,我正在用python和flask制作一个网络应用程序,当网站管理员的网站宕机时,它会向他发送电子邮件和推特。我正在考虑运行一个无限while循环,等待10分钟,然后向网站发送一个请求以进行检查,并检查返回的响应是否为200。问题是,在脚本中,我可以插入这个循环吗?有什么建议吗?士兵,你死后告诉我 试图报告应用程序中的问题并不是最可靠的方法 使用外部进程观看应用程序 你应该有一些外部独立的应用程序,监控你的应用程序 如果您生活在纯Python环境中,您可以编写一个脚本,该脚本将检查访问某个应用程序

我正在用python和flask制作一个网络应用程序,当网站管理员的网站宕机时,它会向他发送电子邮件和推特。我正在考虑运行一个无限while循环,等待10分钟,然后向网站发送一个请求以进行检查,并检查返回的响应是否为200。问题是,在脚本中,我可以插入这个循环吗?有什么建议吗?

士兵,你死后告诉我 试图报告应用程序中的问题并不是最可靠的方法

使用外部进程观看应用程序 你应该有一些外部独立的应用程序,监控你的应用程序

如果您生活在纯Python环境中,您可以编写一个脚本,该脚本将检查访问某个应用程序url是否成功,如果不成功,它将提醒某人。对于警报,您可以尝试通过电子邮件发送日志记录,例如
logbook
(请参阅或)

在生产环境中,最好运行一些监控应用程序,比如

使用日志检查脚本示例 为了更好的可读性,将内容拆分为多个部分,真正的脚本位于一个名为
monitor\u url.py

monitor\u url.py
:文档字符串、导入和邮件模板 Docstring解释用法,并最终由命令行解析器使用
docopt

进口主要与
logbook
相关

"""monitor_url.py - check GET access to a url, notify by GMail about problems
Usage:
    monitor_url.py   [options] <url> <from> <pswd> <to>...
    monitor_url.py -h

Options:
  -L, --logfile <logfile>    Name of logfile to write to [default: monitor_url.log].
  -N, --archives <archives>  Number of daily logs to keep, use 0 for unlimited [default: 0]

The check is performed once a minute and does HTTP GET request to <url>.
If there is a problem, it sends an e-mail using GMail account.
There is a limit of 6 e-mails, which can be sent per hour.
"""
import time
from logbook import Logger, GMailHandler, StderrHandler, NestedSetup, TimedRotatingFileHandler, Processor
from logbook.more import JinjaFormatter
from datetime import timedelta
import requests
from requests.exceptions import ConnectionError

MAIL_TEMPL = """Subject: {{ record.level_name }} on {{ record.extra.url }}

{{ record.message }}

Url: {{ record.extra.url }}
{% if record.exc_info %}
Exception: {{ record.formatted_exception }}
{% else %}
Status: {{ record.extra.req.status_code }}
Reason: {{ record.extra.req.reason }}
{% endif %}
"""
montior\u url.py
final
if\uuuu name\uuuu…
这部分实际上解析命令行参数并调用
main

if __name__ == "__main__":
    from docopt import docopt
    args = docopt(__doc__)
    print args
    main(args["<url>"], args["<from>"], args["<pswd>"], args["<to>"], args["--logfile"],
            int(args["--archives"]))
用法: 监视器\u url.py[选项]。。。 监视器url.py-h

要获得完整帮助,请使用
-h

$ python monitor_url.py -h
...the help is the same as script docstring...
将其用于实际监控,此处用于监控
http://localhost:8000

$ python monitor_url.py -L mylog.log -N 2 http://localhost:8000 <yourmail>@gmail.com xxxpasswordxxx notified.person@example.com
{'--archives': '2',
 '--logfile': 'mylog.log',
 '-h': False,
 '<from>': 'your.mail@gmail.com',
 '<pswd>': 'xxxxxxx',
 '<to>': ['notified.person@example.com'],
 '<url>': 'http://localhost:8000'}
[2014-06-09 19:41] INFO: httpWatcher: url was reached, status OK
[2014-06-09 19:41] ERROR: httpWatcher: Unable to connect
Traceback (most recent call last):
....(shortened)...
    raise ConnectionError(e, request=request)
ConnectionError: HTTPConnectionPool(host='localhost', port=8000): Max retries exceeded with url: / (Caused by <class 'socket.error'>: [Errno 111] Connection refused)
[2014-06-09 19:41] WARNING: httpWatcher: url was reached, status has changed
[2014-06-09 19:41] INFO: httpWatcher: url was reached, status OK
管理来自这样一个脚本的通知并不容易。在这方面考虑这个beta质量的脚本。


使用像
Nagios
这样的解决方案似乎更适合于此目的。

我正在制作一个外部独立的应用程序,我不是问我如何监控应用程序,而是问我如何始终运行一个进程flask@naumanahmad从你的问题来看,不太清楚你到底在问什么。将长期运行的流程放在flask应用程序中不是一个好主意,您应该将其与flask分开,后者将快速服务http请求(并且可能在多个实例中运行),并保持长期流程的独立性。可通过共享数据库内容等方式与Flask应用程序集成。
$ python monitor_url.py -h
...the help is the same as script docstring...
$ python monitor_url.py -L mylog.log -N 2 http://localhost:8000 <yourmail>@gmail.com xxxpasswordxxx notified.person@example.com
{'--archives': '2',
 '--logfile': 'mylog.log',
 '-h': False,
 '<from>': 'your.mail@gmail.com',
 '<pswd>': 'xxxxxxx',
 '<to>': ['notified.person@example.com'],
 '<url>': 'http://localhost:8000'}
[2014-06-09 19:41] INFO: httpWatcher: url was reached, status OK
[2014-06-09 19:41] ERROR: httpWatcher: Unable to connect
Traceback (most recent call last):
....(shortened)...
    raise ConnectionError(e, request=request)
ConnectionError: HTTPConnectionPool(host='localhost', port=8000): Max retries exceeded with url: / (Caused by <class 'socket.error'>: [Errno 111] Connection refused)
[2014-06-09 19:41] WARNING: httpWatcher: url was reached, status has changed
[2014-06-09 19:41] INFO: httpWatcher: url was reached, status OK
$ pip install logbook jinja2 requests