检测到重复值的烧瓶SQLAlchemy时停止插入表

因陀罗

我能够从推文中获取数据并将其存储到MySQL表中。但问题是有时某条推文具有相同价值的重复推文。我想知道当使用Flask-SQLAlchemy检测到重复值时是否有可能停止插入表中。

from tweepy import Stream
from tweepy import OAuthHandler
from tweepy.streaming import StreamListener
from flask_sqlalchemy import SQLAlchemy
from models import TrainingTweets, db
import mysql.connector
import json
import tweepy
from tweepy.api import API

#consumer key, consumer secret, access token, access secret.
ckey=""
csecret=""
atoken=""
asecret=""

auth = OAuthHandler(ckey, csecret)
auth.set_access_token(atoken, asecret)

api = tweepy.API(auth)


class listener(StreamListener):

    def __init__(self, api=None):
        self.api = api or API()
        self.n = 0
        self.m = 50

    def on_data(self, data):
        all_data = json.loads(data)
        self.n = self.n+1
        if self.n <= self.m:
            tweet = all_data["text"]
            username = all_data["user"]["screen_name"]
            label = "1"
            ttweets = TrainingTweets(label_id=label, tweet_username=username, tweet=tweet)
            db.session.add(ttweets)
            checkedtweet = TrainingTweets.query.filter(ttweets.tweet).all()
            if not checkedtweet:
                db.session.commit()
                print((username, tweet))
                return True
            else:
                print("Duplicate entry detected!")
                return False
        else:
            print("Successfully stored ", self.m, " tweets into database")
            return False

    def on_error(self, status):
        print(status)

auth = OAuthHandler(ckey, csecret)
auth.set_access_token(atoken, asecret)

twitterStream = Stream(auth, listener())
twitterStream.filter(track=["health"], languages=["en"], follow="")

这是我的model.py:

class TrainingTweets(db.Model):
    tweet_id = db.Column(db.Integer, primary_key=True)
    tweet_username = db.Column(db.String(50))
    tweet = db.Column(db.String(191))
    slug = db.Column(db.String(191), unique=False)
    created_date = db.Column(db.DateTime, default=datetime.datetime.now)
    label_id = db.Column(db.Integer, db.ForeignKey('label.label_id'))

    def __init__(self, *args, **kwargs):
        super(TrainingTweets, self).__init__(*args, **kwargs)  # Call parent constructor.
        self.generate_slug()

    def generate_slug(self):
        self.slug = ''
        if self.tweet:
            self.slug = slugify(self.tweet)
伊利亚·艾维拉(IljaEverilä)

您的模型应具有用于某些条件的唯一索引,以删除重复项。Column默认情况下,s不是唯一的,您似乎会假设(unique=False在列和注释中)。您应该使用一些“自然”键(例如twitter提供的ID)来代替自动递增的替代键,或者使文本列tweet唯一。

固定唯一性要求后,如果希望忽略IntegrityErrors并继续进行,请将插入内容包装在事务中(或使用隐式行为),并相应地提交或回滚:

from sqlalchemy.exc import IntegrityError

class listener(StreamListener):

    def on_data(self, data):
        all_data = json.loads(data)
        tweet_id = all_data["id_str"]
        tweet_text = all_data["text"]
        tweet_username = all_data["user"]["screen_name"]
        label = 1
        ttweets = TrainingTweets(label_id=label,
                                 tweet_username=tweet_username,
                                 tweet=tweet_text)

        try:
            db.session.add(ttweets)
            db.session.commit()
            print((username, tweet))
            # 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

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

PDO-根据3个值检测到重复项时插入新行

动态地将行插入表烧瓶sqlalchemy

插入目标表时跳过mysql中的重复值

当 tbody 有值时如何停止插入 thead 表

Alembic-SQLAlchemy无法检测到现有表

声明表插入的值重复

重复新列中的值,直到检测到更改pyspark

检测到重复条目时显示错误消息

使用#temp表时未检测到无效列

在MySQL中检测到“ x”时添加到值

oracle 在插入表之前检查重复值

如何检测 URL 列表中的重复值并停止迭代?

没有会话的烧瓶 sqlalchemy 插入

停止用户向表中插入重复的行

动态插入的表:JQuery未检测到最后一行

删除查询在检测到重复时删除所有记录而不保留原始记录

当检测到重复作者时,如何解决计数程序,使当前编号递增?

当检测到重复字段时,Rails Active :: Records创建不完整的嵌套记录

需要帮助我的 Android Java 后台服务在检测到呼叫时停止

检测到对象可重复迭代

Babel:检测到重复的插件/预设错误

WinRAR是否检测到重复文件?

烧瓶,防止SQLAlchemy在实例化映射类时添加未指定的值

尝试更新值时,烧瓶SQLAlchemy IntegrityError“唯一约束失败”

尝试使用SQLAlchemy更新数据库时,烧瓶sqlalchemy.exc.OperationalError:(OperationalError)没有此类表

插入表时处理 SQLAlchemy 中的触发器

将 HDMI 插入显示器并将 DVI 插入 PC 时,显示器上显示“未检测到信号”

意外地从表中检测到所有数据,使用循环psql将伪数据插入到表中

当文本框值为空时,使用 C# 停止在表中插入空值日期