0

I have this python code for getting tweets through the Twitter API based on keywords and save it into a JSON file:

Python Code:

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()

How do I run this by clicking a button in an HTML Page?

1 Answer 1

2

If I understand your question correctly, I think you may be able to use the flask framework and the Jinja template engine to get the data which you need and call the functions which you want to call. Suppose you want a button to call a particular function, you do this:

First install flask and Jinja.

Next, in your main portion of the python code:

from flask import Flask
app = Flask(__name__)

Then you can have a method in your class which does the required actions on a button click:

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

Finally, in your html page, you can call perform_some_operation function like this:

<form method="POST" action="{{ url_for('perform_some_operation') }}"><button type="submit" name="submit" value="submit">StartSomeOperation</button></form>
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.