【问题标题】:How to exec periodically a function in CherryPy如何在 CherryPy 中定期执行一个函数
【发布时间】:2016-12-23 00:42:13
【问题描述】:

此代码使用 CheryPy 生成 3 个网页。它有效,但现在我需要定期执行“PageWeb”函数以获取查询的最后信息。 如何在 CherryPy 中使用线程:

from Widget import showLine
from Widget import SocketLivestatus
import cherrypy
import threading


def PageWeb(cluster):
    # Open Socket
    table = SocketLivestatus(['host1','host2'], 50000, cluster)
    # Result
    Line = showLine(table) 
    HTML = '''<!doctype html>
             <html lang="en">
                <head><meta charset="utf-8">
                 <title>Widget</title>
                 <link rel="stylesheet" href="css/font-awesome.min.css">
             </head>
            <body style="background-color: #1F1F1F">'''+Line+'''</body>
            </html>'''
    return HTML

#BEFORE
re7 = PageWeb("re7")
prod1 = PageWeb("prod1")
prod2 = PageWeb("prod2")
#MY GOAL
re7 = threading.Timer(5.0, PageWeb("re7")).start()
prod1 = threading.Timer(5.0, PageWeb("prod1")).start()
prod2 = threading.Timer(5.0, PageWeb("prod2")).start()


class HelloWorld(object):
    @cherrypy.expose
    def re7(self):
        return re7

    @cherrypy.expose
    def prod1(self):
        return prod1

    @cherrypy.expose
    def prod2(self):
        return prod2



if __name__ == '__main__':
   cherrypy.config.update(
    {'server.socket_host': '0.0.0.0'} )
   cherrypy.quickstart(HelloWorld(),config={
        '/':
        { 'tools.staticdir.on':True,
          'tools.staticdir.dir': "/app"
        }
       # '/fonts':
       # { 'tools.staticdir.on':True,
       #   'tools.staticdir.dir': "/app"
       # }  
    })

问题是关于threading.Timer(5.0, PageWeb("...")).start() 返回错误:

Traceback (most recent call last):
  File "/usr/lib64/python2.7/threading.py", line 811, in __bootstrap_inner
    self.run()
  File "/usr/lib64/python2.7/threading.py", line 1083, in run
    self.function(*self.args, **self.kwargs)
TypeError: 'str' object is not callable

我想帮助我在 CherryPy 中使用线程函数。

【问题讨论】:

标签: python cherrypy


【解决方案1】:

threading.Timer 只运行一次:

这个类代表一个动作,应该在经过一定时间后才运行

经过一些实验,cherrypy 似乎不适用于线程。以下代码使用multiprocessing 库创建一个单独的Process。通过将HTML 存储为托管list 的第一个条目来共享HTML

import cherrypy
import multiprocessing
import time

def PageWeb(cluster, sleep_interval, lock, shared_result):
    counter = 0
    while True:
        HTML = '''<!doctype html>
                 <html lang="en">
                    <head><meta charset="utf-8">
                     <title>Widget</title>
                     <link rel="stylesheet" href="css/font-awesome.min.css">
                 </head>
                <body style="background-color: #1F1F1F">'''+str(counter)+'''</body>
                </html>'''
        counter += 1
        with lock:
            shared_result[0] = HTML
        time.sleep(sleep_interval)

class HelloWorld(object):
    def __init__(self):
        self.re7_lock = multiprocessing.Lock()
        self.manager = multiprocessing.Manager()
        self.re7_result = self.manager.list()
        self.re7_result.append('')
        arg_list = ("re7", 5.0, self.re7_lock, self.re7_result)
        self.re7_process = multiprocessing.Process(target=PageWeb, args=arg_list)
        self.re7_process.daemon = True
        self.re7_process.start()

    @cherrypy.expose
    def re7(self):
        with self.re7_lock:
            return str(self.re7_result[0])

cherrypy.quickstart(HelloWorld())

此代码是minimal, complete, and verifiable example。您应该能够将它与您的代码集成。

【讨论】:

  • 我不知道为什么,但是当我执行 CherryPy webServer 时,我有一个没有 HTML 代码的白页。
  • 我添加了“导入时间”
  • 您可以使用print 语句或调试器进行调试。尝试将print shared_result 放在shared_result = HTML 之后,将print re7_result 放在return re7_result 之前。
  • print shared_result 在我的 shell 中显示我的 HTML 代码。 print re7_result 显示无
  • 尝试将线程和共享变量初始化移动到构造函数中,如上所示。
猜你喜欢
  • 1970-01-01
  • 2016-06-18
  • 1970-01-01
  • 1970-01-01
  • 2016-09-27
  • 2017-03-14
  • 1970-01-01
  • 2021-10-22
  • 1970-01-01
相关资源
最近更新 更多