2015-05-20 29 views
0

我有這樣的Python代碼通過基於關鍵字Twitter的API獲得的鳴叫,並保存到一個JSON文件:在HTML頁面運行Twitter的API流代碼(蟒蛇)(點擊按鈕)

Python代碼:

import json 
import tweepy 
from datetime import datetime 
from pytz import timezone 
import pytz 


# put your keys 
CONSUMER_KEY = '' 
CONSUMER_SECRET = '' 
ACCESS_TOKEN_KEY ='' 
ACCESS_TOKEN_SECRET = '' 

# FILTER_KEYWORDS = ['manhattan' + 'nyc'] 
FILTER_KEYWORDS = ['Twitter'] 
#FILTER_LANGUAGES = ['en'] 
#FILTER_LOCATIONS_ALL=[-180,-90,180,90] 
#FILTER_LOCATIONS_MANHATTAN=[-74.021248,40.698770 ,-73.905459, 40.872932] 

class SimpleTweetStreamer: 



    def __init__(self): 
     try: 
      self.auth = tweepy.OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET) 
      self.auth.set_access_token(ACCESS_TOKEN_KEY, ACCESS_TOKEN_SECRET) 
      self.api = tweepy.API(self.auth) 

      self.sapi = tweepy.streaming.Stream(self.auth, CustomStreamListener(self.api)) 
      self.sapi.filter(track=FILTER_KEYWORDS) 
      #self.sapi.filter(locations=FILTER_LOCATIONS_MANHATTAN, languages=FILTER_LANGUAGES) 

     except tweepy.error.TweepError as e: 
      print("Unable to authenticate", e) 



class CustomStreamListener(tweepy.StreamListener): 

    def __init__(self, api): 
     self.api = api 
     def on_data(self, body): 
     try: 
      tweet = json.loads(body) 

      date_format = '%Y-%m-%d' 
      time_format = '%H:%M:%S' 

      ts = tweet['timestamp_ms'] 
      date = datetime.fromtimestamp(int(ts)/1000, tz=pytz.timezone('EST')) 
      tweet['MYT_local_date'] = date.strftime(date_format) 
      tweet['MYT_local_time'] = date.strftime(time_format) 




      fileName = 'abc'+ '.json' 
      with open(fileName, 'a') as outfile: 
       json.dump(tweet, outfile) 
       outfile.write("\n") 
       outfile.flush() 
       outfile.close() 

     except: 
      pass 
     return True 

    def on_error(self, status_code): 
     print("[error] " + str(status_code)) 
     return True # Don't kill the stream 

    def on_timeout(self): 
     return True # Don't kill the stream 


if __name__ == "__main__": 

    t = SimpleTweetStreamer() 

如何通過單擊HTML頁面中的按鈕來運行此操作?

回答

2

如果我正確理解你的問題,我認爲你可以使用flask框架和Jinja模板引擎來獲取你需要的數據並調用你想調用的函數。假設你想要一個按鈕來調用特定的功能,你這樣做:

首先安裝燒瓶和Jinja。

接下來,在Python代碼你的主要部分:

from flask import Flask 
app = Flask(__name__) 

然後你就可以在你的類不上的按鈕點擊所需操作的方法:

@app.route("/some_operation", methods=['POST']) 
def perform_some_operation(): 

最後,在你的html頁面中,你可以調用像這樣的perform_some_operation函數:

<form method="POST" action="{{ url_for('perform_some_operation') }}"><button type="submit" name="submit" value="submit">StartSomeOperation</button></form>