I tried using the code below but it doesn't work. when I press Fetch Tweets button it won't pass value from the textbox name number from HTML page to self.m and keep streaming all the tweets and store them all into database.
from app import *
from flask import Blueprint, flash, redirect, render_template, request, url_for, g
from models import Label, TrainingTweets, TestingTweets
from flask_login import login_required
from tweepy import Stream
from tweepy import OAuthHandler
from tweepy.streaming import StreamListener
from flask_sqlalchemy import SQLAlchemy
from sqlalchemy.exc import IntegrityError
import mysql.connector
import json
import tweepy
from tweepy.api import API
fetchtweet = Blueprint('fetchtweet', __name__, template_folder='templates')
#consumer key, consumer secret, access token, access secret.
ckey=""
csecret=""
atoken=""
asecret=""
@fetchtweet.route('/')
@login_required
def index():
return render_template('fetchtweetpage.html')
@fetchtweet.route('/fetchtrainingtweets/', methods=["GET", "POST"])
@login_required
def ttweets():
if request.method == 'POST':
auth = OAuthHandler(ckey, csecret)
auth.set_access_token(atoken, asecret)
api = tweepy.API(auth)
getlabelid = Label.query.filter_by(label_id=request.form['label']).first()
getlabelname = getlabelid.label_name
number = request.form['number']
class listener(StreamListener):
def __init__(self, api=None):
self.api = api or API()
self.n = 0
self.m = number
def on_data(self, data):
all_data = json.loads(data)
tweet = all_data["text"]
username = all_data["user"]["screen_name"]
label = getlabelid.label_id
ttweets = TrainingTweets(label_id=label, tweet_username=username, tweet=tweet)
try:
db.session.add(ttweets)
db.session.commit()
# Increment the counter here, as we've truly successfully
# stored a tweet.
self.n += 1
except IntegrityError:
db.session.rollback()
# Don't stop the stream, just ignore the duplicate.
# print("Duplicate entry detected!")
if self.n >= self.m:
#print("Successfully stored", self.m, "tweets into database")
# Cross the... stop the stream.
return False
else:
# Keep the stream going.
return True
def on_error(self, status):
print(status)
auth = OAuthHandler(ckey, csecret)
auth.set_access_token(atoken, asecret)
twitterStream = Stream(auth, listener())
twitterStream.filter(track=[getlabelname], languages=["en"])
return render_template('fetchtrainingtweets.html',
labels=Label.query.all(),
ttweets=TrainingTweets.query.all())
else:
return render_template('fetchtrainingtweets.html',
labels=Label.query.all(),
ttweets=TrainingTweets.query.all())
I want to know if I can pass the value from textbox name number from HTML page to self.m StreamListener Tweepy in Flask. Is it possible or? because I pass the value to self.m but it doesn't work. it will work only if I set the value of self.m by myself.
Aucun commentaire:
Enregistrer un commentaire