在烧瓶的背景中运行一个过程 [英] Running A Process In the Background In Flask

查看:154
本文介绍了在烧瓶的背景中运行一个过程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在python和flask中制作一个webapp,当他的网站崩溃的时候,向网站管理员发送消息。我想运行一个无限的while循环,等待10分钟,然后发送请求到网站进行检查,并检查返回的响应是否是200.问题是,在脚本中我可以插入这个循环?关于如何实现这一点的任何建议?

解决方案

士兵,当你死时告诉我



尝试报告死于应用程序的问题不是最可靠的方法。

使用外部进程来观看应用程序



如果你生活在纯Python环境中,你可以编写一个脚本,这将检查访问某个应用程序url是否成功,如果不成功,它会提醒某人。为了提醒您,您可以尝试日志记录是通过电子邮件发送的( logbook rel =nofollow> MailHandler GMailHandler )。 在生产环境中,最好运行一些监控应用程序,比如 Nagios ,只需通过 check_http <

使用日志的示例检查脚本



为了获得更好的可读性,被分割成更多的部分,真正的脚本是在一个名为 monitor_url.py



docstring,import和MAIL_TEMPLATE



Docstring解释了用法,最终被命令行解析器 docopt



进口是主要是 logbook 相关

 monitor_url.py  - 检查GET访问通过GMail通知有关问题
用法:
monitor_url.py [options]< url> <从大于; < PSWD> < to> ...
monitor_url.py -h

选项:
-L,--logfile< logfile>要写入的日志文件的名称[默认:monitor_url.log]。
-N,--archives< archives>保留的每日日志数量,使用0表示无限[默认值:0]

检查每分钟执行一次,并向< url>执行HTTP GET请求。
如果出现问题,则使用GMail帐户发送电子邮件。
有6封电子邮件的限制,可以每小时发送一次。

导入时间
从logbook导入Logger,GMailHandler,StderrHandler,NestedSetup,TimedRotatingFileHandler,处理器
from logbook.more进口JinjaFormatter
from datetime import timedelta
从requests.exceptions导入请求
导入ConnectionError
$ b MAIL_TEMPL =主题:{{record.extra.url}} $ b $上的{{record.level_name}} b
{{record.message}}

网址:{{record.extra.url}}
{%如果record.exc_info%}
例外:{ {record.formatted_exception}}
{%else%}
状态:{{record.extra.req.status_code}}
原因:{{record.extra.req.reason}}
{%endif%}



monitor_url.py main 执行检查的函数

这个脚本循环,同时并执行一次检查
如果检测到问题或者状态码已经改变,GMailHandler被配置为发送电子邮件。

  def main(url,e_from,pswd,e_to,logfile,archives):
log = Logger(httpWatcher)
def inject_req(record):
record.extra.url = url
record.extra.req = req
processor = Processor(inject_req)
gmail_handler = GMailHandler(e_from,pswd,e_to,
level =WARNING,record_limit = 6 ,record_delta = timedelta(hours = 1),bubble = True)
gmail_handler.formatter = JinjaFormatter(MAIL_TEMPL)
$ b $ setup = NestedSetup([StderrHandler(),
TimedRotatingFileHandler ,bubble = True),
gmail_handler,
处理器])

with setup.applicationbound():
last_status = 200
,True:
尝试:
req = requests.get(url)
如果req.status_code!= last_status:
log.warn(已达到网址,状态已更改)
如果req.ok:
log.info(url was reache d,状态OK)
else:
log.error(到达URL的问题)
last_status = req.status_code
除了ConnectionError:
req =无
log.exception(无法连接)
last_status = 0
time.sleep(6)


$ b

montior_url.py final if __name__ ...



这部分实际上是分析命令行参数并调用 main

 if __name__ == args [< from>],args [< pswd>],args [>],args [ -  logfile],
int(args [ - archives]))



调用它

尝试不带参数调用它:

  $ python monitor_url.py 

用法:
monitor_url.py [选项] ...
monitor_url。 py -h


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

  $ python monitor_url.py -h 
...帮助与脚本docstring相同...

使用它进行实际监控,这里用于监控 http:// localhost:8000

  $ python monitor_url.py -L mylog.log -N 2 http:// localhost:8000< yourmail> @ gmail.com xxxpasswordxxx notifications.person@example.com 
{'archives':'2',
'--logfile':'mylog.log',
'-h':False,$ b $< from>':'your.mail@gmail.com',
'< pswd>':'xxxxxxx',
'< to>': person@example.com'],
'< url>':'http:// localhost:8000'}
[2014-06-09 19:41]信息:httpWatcher:已达到网址,状态确定
[2014-06-09 19:41]错误:httpWatcher:无法连接
Traceback(最近一次调用最后一次):
....(简写)...
提升ConnectionError(e,request = request)
ConnectionError:HTTPConnectionPool(host ='localhost',port = 8000):最大重试次数超过了url:/(由< class'socket.error'>:导致:[Errno 111] Connection refused)
[2014-06-09 19:41]警告:httpWatcher:网址已达到,状态已更改
[2014-06-09 19:41]信息:httpWatcher:网址已达到,状态确定



检查在本地文件夹中创建的日志文件。

检查你的Gmail收件箱(如果没有,你必须使用密码) 。
$ b

结论



Twitter通知也可以通过 logbook ,但这里没有显示。



为了运行这个脚本,需要Python 2.7,你需要安装一些软件包:

  $ pip install logbook jinja2请求

管理从这样的脚本通知是否不容易。在这方面考虑一下这个beta版本的脚本。

> Nagios 这样的解决方案似乎更适合这个用途。

I am making a webapp in python and flask which will email & tweet to the webmaster when the moment his website goes down. I am thinking of running an infinite while loop which waits for 10 minutes and then send a request to the website to be checked and checks if the returned response is 200. The problem is that were in the script can I insert this loop? Any suggestions about how I can achieve this?

解决方案

Soldier, tell me when you are dead

Trying to report a problem from dying app is not the most reliable method.

Use external process to watch the app

You shall have some external independent app, monitoring your app.

If you live in pure Python environment, you may write a script, which will check if accessing some app url succeeds and if not, it would alert someone. For alerting, you may try e.g. logbook with log records being sent by e-mail (see MailHandler or GMailHandler).

In production environment it would be best to run some monitoring app like Nagios and simply check by check_http

Sample checking script using Logbook

For better readibility, the content is split to more parts, real script is in one file called monitor_url.py

monitor_url.py: Docstring, imports and MAIL_TEMPLATE

Docstring explains usage and is finally used by command line parser docopt

Imports are mostly logbook related

"""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 %}
"""

monitor_url.py: main function performing the checks

This script is looping in while and performs once a minute a check. If a problem is detected, or status code has changed, GMailHandler is configured to send e-mail.

def main(url, e_from, pswd, e_to, logfile, archives):
    log = Logger("httpWatcher")
    def inject_req(record):
        record.extra.url = url
        record.extra.req = req
    processor = Processor(inject_req)
    gmail_handler = GMailHandler(e_from, pswd, e_to,
        level="WARNING", record_limit=6, record_delta=timedelta(hours=1), bubble=True)
    gmail_handler.formatter = JinjaFormatter(MAIL_TEMPL)

    setup = NestedSetup([StderrHandler(),
        TimedRotatingFileHandler(logfile, bubble=True),
        gmail_handler,
        processor])

    with setup.applicationbound():
        last_status = 200
        while True:
            try:
                req = requests.get(url)
                if req.status_code != last_status:
                    log.warn("url was reached, status has changed")
                if req.ok:
                    log.info("url was reached, status OK")
                else:
                    log.error("Problem to reach the url")
                last_status = req.status_code
            except ConnectionError:
                req = None
                log.exception("Unable to connect")
                last_status = 0
            time.sleep(6)

montior_url.py final if __name__ ...

This part actually parses command line parameters and calls the 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"]))

Call it

Try to call it without parameters:

$ python monitor_url.py 

Usage: monitor_url.py [options] ... monitor_url.py -h

To get full help, use -h

$ python monitor_url.py -h
...the help is the same as script docstring...

Use it for real monitoring, here used for monitoring 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

Check logfile created in local folder.

Check your gmail inbox (if there is nothing, you have to play with the password).

Conclusions

Twitter notification is also possible with logbook, but is not shown here.

To run the script, Python 2.7 is expected and you shall install some packages:

$ pip install logbook jinja2 requests

Managing notification from such a script is not easy. Consider this script of beta quality in this regard.

Usage of solutions like Nagios seems to be more appropriate for this purpose.

这篇关于在烧瓶的背景中运行一个过程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆