如何在CherryPy中定期执行一个函数

时间:2016-08-16 15:00:36

标签: python cherrypy

此代码使用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中使用线程功能。

1 个答案:

答案 0 :(得分:1)

threading.Timer只运行一次:

  

此类表示仅在经过一定时间后才应运行的操作

经过一些实验,似乎cherrypy对线程不起作用。以下代码使用multiprocessing库创建单独的Process。通过将HTML存储为托管list的第一个条目来共享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())

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode==GALLERY_REQUEST) && resultCode == RESULT_OK) {
        Uri selectedImage = data.getData();
        String[] filePathColumn = {MediaStore.Images.Media.DATA};
        Cursor cursor = getContentResolver().query(selectedImage, filePathColumn, null, null, null);
        if (cursor != null && cursor.moveToFirst()) {
            int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
            String filePath = cursor.getString(columnIndex);
            Bitmap bitmap = scaleBitmap(BitmapFactory.decodeFile(filePath), 512,512,360);

            bitMapToString(bitmap); //this function logs the base64 strings
        }
    }
}

public String bitmapToString(Bitmap bitmap){
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
    byte[] imageBytes = baos.toByteArray();
    String result = Base64.encodeToString(imageBytes, Base64.DEFAULT);

    Log.d("BitmapToString",result); //here I get base64 strings
    return result;
}

public Bitmap scaleBitmap(Bitmap bm, int maxWidth, int maxHeight, int ifSquareMaxValue) {
    int width = bm.getWidth();
    int height = bm.getHeight();

    if(maxWidth>width && maxHeight>height)
        return bm;
    if (width > height) {
        float ratio = (float) width / maxHeight;
        width = maxHeight;
        height = (int)(height / ratio);
    } else if (height > width) {
        float ratio = (float) height / maxWidth;
        height = maxWidth;
        width = (int)(width / ratio);
    } else {
        height = ifSquareMaxValue;
        width = ifSquareMaxValue;
    }

    return Bitmap.createScaledBitmap(bm, width, height, true);
}

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