2014-01-31 41 views
0

我在Flask中構建了一個應用程序,但我對它很陌生。我想要做的是從外部.txt文件中獲取一個字符串,從中返回n個數字,等待一段時間,然後返回n + 1個數字,等待另一個數字,然後n + 2個數字等。在Flask/Python中每秒顯示一部分截斷的字符串

我可以在打印到終端時獲得此功能,但無法使其在視圖中實際返回。不知道我要去哪裏錯,任何幫助將非常感激。

現在,我越來越無論是懸掛頁面或「View功能沒有返回響應」與我的想法

@app.route('/') 
@app.route('/index') 

def index(): 


    class RepeatEvery(threading.Thread): 
       def __init__(self, interval, func, *args, **kwargs): 
       threading.Thread.__init__(self) 
       self.interval = interval # seconds between calls 
       self.func = func   # function to call 
       self.args = args   # optional positional argument(s) for call 
       self.kwargs = kwargs  # optional keyword argument(s) for call 
       self.runable = True 
      def run(self): 
       while self.runable: 
         self.func(*self.args, **self.kwargs) 
         time.sleep(self.interval) 
      def stop(self): 
       self.runable = False 

    counter = 0 

    while counter != 5: 
     number = str(counter) 
     counter += 1 
     thread = RepeatEvery(1, truncate, number) 
     thread.start() 
     thread.join(1) 
     thread.stop() 


def truncate(num): 
    with open(os.path.join(APP_STATIC, 'file.txt')) as f: 
     data = f.read() 
     truncated = data[:num] 
     return truncated ` 

回答

2

您可以通過using a generator流數據返回給客戶端:

from flask import Response 

@app.route('/') 
def index(): 
    data = "" 
    with open(os.path.join(APP_STATIC, 'file.txt')) as f: 
     data = f.read() 

    gen = (data[:num] for num in range(1, 6)) 

    return Response(gen, mimetype="text/plain") 

知道了,則有可能要暫停添加到您的發電機:

from time import sleep 

def gen(data): 
    for num in range(1, 6): 
     yield data[:num] 
     sleep(1)