【问题标题】:Running Twitter API Streaming Code (Python) in HTML Page (Click on Button)在 HTML 页面中运行 Twitter API 流代码 (Python)(单击按钮)
【发布时间】:2015-08-02 10:34:49
【问题描述】:

我有这个 python 代码,用于通过基于关键字的 Twitter API 获取推文并将其保存到 JSON 文件中:

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 页面中的按钮来运行它?

【问题讨论】:

    标签: python html api twitter


    【解决方案1】:

    如果我正确理解您的问题,我认为您可以使用烧瓶框架和 Jinja 模板引擎来获取您需要的数据并调用您想要调用的函数。假设你想要一个按钮来调用一个特定的函数,你可以这样做:

    首先安装flask和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>
    

    【讨论】:

      猜你喜欢
      • 2019-07-03
      • 2013-03-27
      • 1970-01-01
      • 2021-03-24
      • 2021-07-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-10-18
      相关资源
      最近更新 更多