当前位置: 首页>>代码示例>>Python>>正文


Python Tweet.save方法代码示例

本文整理汇总了Python中models.Tweet.save方法的典型用法代码示例。如果您正苦于以下问题:Python Tweet.save方法的具体用法?Python Tweet.save怎么用?Python Tweet.save使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在models.Tweet的用法示例。


在下文中一共展示了Tweet.save方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: tweet

# 需要导入模块: from models import Tweet [as 别名]
# 或者: from models.Tweet import save [as 别名]
def tweet(request):

    if request.method == 'POST':
        form = TweetForm(request.POST)
        if form.is_valid():
            twit = Tweet()
            status = twit.tweet = form.cleaned_data['tweet']
            twit.name = request.user.username
            twit.save()
            variables = RequestContext(request,{
                'status':status
            })
            return render_to_response('tweet.html',RequestContext(request),variables)
        else:
            return render_to_response('tweet.html',{'request':RequestContext(request)})

    else:
        tweets = []
        queryset=Tweet.objects.all()
        for query in queryset:
            if request.user.username == query.name:
                tweets.append(query)
        status = ''
        for tweet in tweets:
            status = tweet.tweet

        form = TweetForm()
        form.name = request.user
        variables = RequestContext(request, {
                'form': form,'status': status
            })

        return render_to_response('tweet.html',RequestContext(request),variables)
开发者ID:Kanchu,项目名称:twitter,代码行数:35,代码来源:views.py

示例2: feed

# 需要导入模块: from models import Tweet [as 别名]
# 或者: from models.Tweet import save [as 别名]
def feed(request, username):
    url = "https://twitrss.me/twitter_user_to_rss/?user=" + username
    dicc = feedparser.parse(url)
    out = ""

    for number in range(5):
        out += dicc.entries[number].title + "<br>"
        #Obtener las urls del tweet si hay
        urls = dicc.entries[number].title.split()
        for i in urls:
            if i.startswith("http://") or i.startswith("https://"):
                i = i.split('&')[0]
                out += "<li><a href=" + i + ">" + i + "</a></li>"
                #Obtener primer elemento <p>
                soup = BeautifulSoup(urllib.urlopen(i).read())
                out += str(soup.p).decode('utf8')
                #Obtener primer elemento <img>
                out += str(soup.img).decode('utf8') + "<br><br>"

        #Comprobar y guardar autor del tweet
        user = dicc.entries[number].title.split(':')[0]
        try:
            p = User.objects.get(name=user)
        except ObjectDoesNotExist:
            p = User(name=user)
            p.save()

        #Comprobar y guardar tweet
        try:
            t = Tweet.objects.get(content=dicc.entries[number].title)
        except ObjectDoesNotExist:
            t = Tweet(content=dicc.entries[number].title, url= dicc.entries[number].link, name=p)
            t.save()

    return HttpResponse(out)
开发者ID:RebeccaSaez,项目名称:X-Serv-15.12-Django-feedexpander,代码行数:37,代码来源:views.py

示例3: do

# 需要导入模块: from models import Tweet [as 别名]
# 或者: from models.Tweet import save [as 别名]
 def do(self):
     logger.info("Initiating cronjob: {}".format(self.code)) 
     try:
         auth = tweepy.OAuthHandler(self._tak, self._tas)
         auth.set_access_token(self._tat, self._tats)
         api = tweepy.API(auth)
         screen_name = api.me().screen_name
         timeline = api.home_timeline()
     except Exception:
         e = traceback.format_exc()
         logger.error("Could not get home timeline. Error: {}".format(self.screen_name, e))
         return False
     
     for t in timeline:
         if t.user.screen_name == screen_name:
             msg = t.text
             if msg.startswith('RT @everycolorbot'):
                 chex = msg.split()[2].strip("\"")
                 evcinst = EveryColorBotTweet.objects.get_or_none(color__hex = chex)
                 if evcinst is not None:
                     evcinst.tweeted = True
                     evcinst.save()      
             inst = Tweet.objects.get_or_none(message = msg)
             if inst is None:
                 logger.info('Cronjob encountered unsaved tweet: "{}" Saving it to database.'.format(msg))
                 inst = Tweet(color_code = chex, message = msg) 
                 inst.save()
开发者ID:assamite,项目名称:TwatBot,代码行数:29,代码来源:cron.py

示例4: schedule

# 需要导入模块: from models import Tweet [as 别名]
# 或者: from models.Tweet import save [as 别名]
def schedule(request):
  if request.POST.get('auth') != settings.TWITGHOST_AUTH_KEY:
    logging.error("Unauthorized access")
    return HttpResponse('forbidden', status=403)
  new_tweet = Tweet(tweet=request.POST['tweet'])
  new_tweet.save()
  return HttpResponse('ok', mimetype="text/xml")
开发者ID:cgst,项目名称:twitghost,代码行数:9,代码来源:views.py

示例5: get_context_data

# 需要导入模块: from models import Tweet [as 别名]
# 或者: from models.Tweet import save [as 别名]
    def get_context_data(self, *args, **kwargs):
        context = super(TestTweetsView, self).get_context_data(*args, **kwargs)
        
        # retrieve tweets from db whose actual classifications have been set (already verified from previous tests)
        tweets_train_tourism = Tweet.objects.filter(classified=True, actual_classification='tourism')
        tweets_train_nontourism = Tweet.objects.filter(classified=True, actual_classification='nontourism')
        
        # train classifier using tourism and nontourism files and tweets from db
        train_result = train_db(tweets_train_tourism, tweets_train_nontourism)
        classifier = train_result['classifier']

        # retrieve random tweets from a file
        tweets = self.randomize_tweets('classifier/data/2015-03-06.happydata.txt', 10)
        tweets_test = []

        for tweet in tweets:
            if not Tweet.objects.filter(tweet_id=tweet['id']) and tweet['coordinates']:
                tweet_id = tweet['id']
                user = tweet['user']['name'].encode('utf-8')
                lat = tweet['coordinates']['coordinates'][1]
                lng = tweet['coordinates']['coordinates'][0]
                text = tweet['text'].encode('utf-8')
                if tweet_id and user and lat and lng and text:
                    # classify tweet
                    classification = classifier.classify(feature_extractor_lda_tripadvisor_top_words_weights(text))
                    # save tweet with classification (to be verified later)
                    tweet_obj = Tweet(tweet_id=tweet_id, user=user,
                                                     lat=lat, lng=lng, text=text, 
                                                     classification=classification)
                    tweet_obj.save()
                    tweets_test.append(tweet_obj)
        context['tweets'] = tweets_test
        return context
开发者ID:jedijulia,项目名称:nlp-tourism,代码行数:35,代码来源:views.py

示例6: buscar_en_todos_los_tweets

# 需要导入模块: from models import Tweet [as 别名]
# 或者: from models.Tweet import save [as 别名]
def buscar_en_todos_los_tweets(busqueda, cantidad_de_tweets=50, partir_del_tweet=None):
	## App keys
	APP_KEY = 'IR5sQyceHa34Cxxm2hAw'
	APP_SECRET = 'y5Nti0zdCFfzY1ifokC6iHIZFZ14Z2GAjTI6VFx2mg'

	## User keys
	OAUTH_TOKEN = '202826188-6OCQEmzi7JCu8S6UERP5nhjUo4NHirk0Kd4VRRvl'
	OAUTH_TOKEN_SECRET = '1wmkXUkqkDhBnbugzaNIzf07VKeCddjEPynVG2gayU'	
	

	# requires authentication as of Twitter API v1.1
	twitter = Twython(APP_KEY, APP_SECRET, OAUTH_TOKEN, OAUTH_TOKEN_SECRET)

	try:
	    search_results = twitter.search(q=busqueda, count=cantidad_de_tweets)
	    print '===============', busqueda, '==============='
	except TwythonError as e:
	    print e

    # Initialize array of tweet objects
	tweets = [] 		
	for tweet in search_results['statuses']:
		# Parameters of a tweet
		tweet_id = tweet['id_str']
		tweet_user = tweet['user']['screen_name'].encode('utf-8')
		tweet_created_at = tweet['created_at']
		tweet_text = tweet['text'].encode('utf-8')
		tweet_reply_to_status_id  = tweet['in_reply_to_user_id_str']
		tweet_retweet_count = tweet['retweet_count']

		try:
			Tweet.objects.get(pk=tweet_id)
			print "Tweet %s already in the db." % tweet_id
		except:
			# Print in console
			print 'Added %s.- Tweet from @%s Date: %s' % (tweet_id, tweet_user, tweet_created_at)
			print tweet_text, '\n', 'reply to %s' % tweet_reply_to_status_id

			## Change twitter api time to python datetime
			## ej. Wed Jan 16 22:08:18 +0000 2013

			tweet_created_at = datetime.strptime(tweet_created_at, "%a %b %d %H:%M:%S +0000 %Y").replace(tzinfo=utc)

			tmp_tweet = Tweet(id=tweet_id, user=tweet_user, text=tweet_text, created_at=tweet_created_at, retweet_count=tweet_retweet_count)
			add_tweet_search = TwitterSearch(search=busqueda, tweet=tmp_tweet)
			
			# extract, save and link hastags with tweet
			extract_hash_tags(tmp_tweet)
			

			# save newly created objects
			tmp_tweet.save()
			add_tweet_search.save()


## Tests are to be performed here
# buscar_en_todos_los_tweets('#uabc')
开发者ID:jimenezjrs,项目名称:hermes,代码行数:59,代码来源:recolector.py

示例7: on_success

# 需要导入模块: from models import Tweet [as 别名]
# 或者: from models.Tweet import save [as 别名]
 def on_success(self, data):
     if 'text' in data:
         data['fetched_timestamp'] = datetime.datetime.now()
         data['fresh_tweet'] = True
         tweet = Tweet()
         tweet.tweet_id = data['id_str']
         tweet.tweets.append(data)
         tweet.save()
         print("saved", self.i)
         self.i += 1
开发者ID:kaflesudip,项目名称:TweetStats,代码行数:12,代码来源:get_tweets.py

示例8: tweet_add

# 需要导入模块: from models import Tweet [as 别名]
# 或者: from models.Tweet import save [as 别名]
def tweet_add():
    user = current_user()
    if user is None:
        return redirect(url_for('login_view'))
    else:
        t = Tweet(request.form)
        # 设置是谁发的
        t.user = user
        # 保存到数据库
        t.save()
        return redirect(url_for('timeline_view', username=user.username))
开发者ID:James-Lee-s,项目名称:lisen,代码行数:13,代码来源:app.py

示例9: save_raw

# 需要导入模块: from models import Tweet [as 别名]
# 或者: from models.Tweet import save [as 别名]
def save_raw(results: Generator) -> Generator:
    """Save the results and yields the id values
    """
    for result in results:
        id_str = result.__dict__.get('id_str')
        data = result.__dict__.get('_json')

        tweet = Tweet(id_str)
        tweet.save(data)

        yield id_str
开发者ID:markdessain,项目名称:tweet-analyser,代码行数:13,代码来源:twitter.py

示例10: post

# 需要导入模块: from models import Tweet [as 别名]
# 或者: from models.Tweet import save [as 别名]
 def post(self, request, username):
     form = TweetForm(self.request.POST)
     if form.is_valid():
         user = User.objects.get(username=username)
         tweet = Tweet(text=form.cleaned_data['text'], user=user, country=form.cleaned_data['country'])
         tweet.save()
         words = form.cleaned_data['text'].split(" ")
         for word in words:
             if word[0] == "#": #Separamos todas las letras del tweet y si empieza con #, se va a crear un hashtag de esa palabra
                 hashtag, created = HashTag.objects.get_or_create(name=word[1:])
                 hashtag.tweet.add(tweet)
     return HttpResponseRedirect('/user/' +username)
开发者ID:quinto7,项目名称:django_mytweets,代码行数:14,代码来源:views.py

示例11: post

# 需要导入模块: from models import Tweet [as 别名]
# 或者: from models.Tweet import save [as 别名]
	def post(self, request, username):
		form = TweetForm(self.request.POST)
		if form.is_valid():
			user = User.objects.get(username = username)
			tweet = Tweet(text = form.cleaned_data['text'], user = user,
				country = "Vietname" )#form.cleaned_data['country'])
			tweet.save()
			words = form.cleaned_data['text'].split(" ")
			for word in words:
				hashtag, created = HashTag.objects.get_or_create(name = word[1:])
				hashtag.tweet.add(tweet)
			return HttpResponseRedirect('/tweets/user/%s' % username)
		return redirect(Profile.as_view())
开发者ID:enixdark,项目名称:django-rest-pratices,代码行数:15,代码来源:views.py

示例12: GetPastTweets

# 需要导入模块: from models import Tweet [as 别名]
# 或者: from models.Tweet import save [as 别名]
    def GetPastTweets(app, searchStrings):

        with app.app_context():

            auth = OAuthHandler( current_app.config['TWITTER_CONSUMER_KEY'], current_app.config['TWITTER_CONSUMER_SECRET'])
            auth.set_access_token(current_app.config['TWITTER_ACCESS_TOKEN'], current_app.config['TWITTER_ACCESS_TOKEN_SECRET'])
            api = API(auth)

            deleteEntries = connect(current_app.config['MONGODB_SETTINGS']['DB'])
            deleteEntries.drop_database(current_app.config['MONGODB_SETTINGS']['DB'])

            listTweetIDs = []

            user_query = session['userSentence']

            session['completeTweetFetch'] = False
            session['completedMetaModel'] = False

            for searchString in searchStrings:
                # Sleep for 28 secs to avoid Twitter download rate restrictions
                searchTweets = [status for status in Cursor(api.search, q=searchString).items(current_app.config['MAX_FETCH_TWEETS'])]

                for tweet in searchTweets:
                    tweet_id = tweet.id
                    if listTweetIDs.__contains__(tweet_id):
                        continue
                    if len(Tweet.objects(tweet_id=tweet_id)) > 1:
                        continue
                    tweet_message = tweet.text.encode("utf-8")
                    tweet_userhandle = tweet.user.screen_name
                    tweet_retweet_count = tweet.retweet_count
                    tweet_createtime = tweet.created_at
                    tweet_location = None
                    tweet_geo = None
                    tweet_favoritecount = tweet.favorite_count
                    tweet_username = tweet.user.name
                    tweet_user_no_of_following = tweet.user.friends_count
                    tweet_user_no_of_followers = tweet.user.followers_count
                    tweet_positiveOrnegative = 0
                    tweet_polarOrneutral = 0
                    tweet_isRetweet = 0

                    oneTweet = Tweet(tweet_id=tweet_id, tweet_msg=tweet_message, tweet_likes=tweet_favoritecount, tweet_retweets=tweet_retweet_count, tweet_search_category=searchString, tweet_user_search_query=user_query, tweet_positiveOrnegative=tweet_positiveOrnegative, tweet_polarOrneutral=tweet_polarOrneutral, tweet_user_handle=tweet_userhandle, tweet_user_name=tweet_username, tweet_user_followers=tweet_user_no_of_followers, tweet_user_following=tweet_user_no_of_following, tweet_isretweet=tweet_isRetweet, tweet_time=tweet_createtime, tweet_location=tweet_location, tweet_geo=tweet_geo)
                    oneTweet.save()
                    listTweetIDs.append(tweet_id)
                    if session['metamodelThread'] is None:
                        session['metamodelThread'] = thread.start_new_thread(twittermetamodelBuilding, ())

            print 'completed tweet fetch'
            session['completeTweetFetch'] = True
        pass
开发者ID:harsha-kadekar,项目名称:Chitralochana,代码行数:53,代码来源:DataDownloader.py

示例13: post

# 需要导入模块: from models import Tweet [as 别名]
# 或者: from models.Tweet import save [as 别名]
 def post(self, request, username):
     form = TweetForm(self.request.POST)
     if form.is_valid():
         user = User.objects.get(username=username)
         tweet = Tweet(text=form.cleaned_data['text'],
                                      user=user,
                                      country=form.cleaned_data['country'])
         tweet.save()
         words = form.cleaned_data['text'].split(" ")
         for word in words:
             if word[0] == "#":
                 hashtag, created = HashTag.objects.get_or_create(name=word[1:])
                 hashtag.tweet.add(tweet)
     return HttpResponseRedirect('/user/'+username)
开发者ID:aflopera,项目名称:learning-django-web-development,代码行数:16,代码来源:views.py

示例14: homepage

# 需要导入模块: from models import Tweet [as 别名]
# 或者: from models.Tweet import save [as 别名]
def homepage(request):
    """Renders homepage, with public timeline"""
    if request.method == 'POST': # If the form has been submitted...
        form = TweetForm(request.POST) # A form bound to the POST data
        if form.is_valid(): # All validation rules pass
            # Process the data in form.cleaned_data
            t=Tweet(text=form.cleaned_data['text'], owner=request.user)
            t.save()
            return HttpResponseRedirect('/') # Redirect after POST
    else:
        form = TweetForm() # An unbound form
    return render_to_response(request, 'homepage.html', {
        'form': form,
    })
开发者ID:maskedduck,项目名称:twitranet,代码行数:16,代码来源:views.py

示例15: on_data

# 需要导入模块: from models import Tweet [as 别名]
# 或者: from models.Tweet import save [as 别名]
    def on_data(self, feed):
        #print feed


        try:
            if feed != []:
                tweet = json.loads(feed)
                tweet_id = tweet['id']
                tweet_message = tweet['text'].encode("utf-8")
                tweet_userhandle = tweet['user']['screen_name']
                tweet_retweet_count = tweet['retweet_count']
                tweet_createtime = datetime.datetime.strptime(tweet['created_at'], '%a %b %d %H:%M:%S +0000 %Y')

                tweet_location = None
                tweet_geo = None
                tweet_favoritecount = tweet['favorite_count']
                tweet_username = tweet['user']['name']
                tweet_user_no_of_following = tweet['user']['friends_count']
                tweet_user_no_of_followers = tweet['user']['followers_count']
                tweet_positiveOrnegative = 0
                tweet_polarOrneutral = 0
                tweet_isRetweet = 0

                oneTweet = Tweet(tweet_id=tweet_id, tweet_msg=tweet_message, tweet_likes=tweet_favoritecount,
                                 tweet_retweets=tweet_retweet_count, tweet_search_category=None,
                                 tweet_user_search_query=session['userSentence'], tweet_positiveOrnegative=tweet_positiveOrnegative,
                                 tweet_polarOrneutral=tweet_polarOrneutral, tweet_user_handle=tweet_userhandle,
                                 tweet_user_name=tweet_username, tweet_user_followers=tweet_user_no_of_followers,
                                 tweet_user_following=tweet_user_no_of_following, tweet_isretweet=tweet_isRetweet,
                                 tweet_time=tweet_createtime, tweet_location=tweet_location, tweet_geo=tweet_geo)
                oneTweet.save()
                if session['metamodelThread'] is None:
                    print 'starting metamodel building'
                    session['metamodelThread'] = thread.start_new_thread(twittermetamodelBuilding, ())

                self.num_tweets += 1

                if self.num_tweets < current_app.config['MAX_LIVE_TWEETS']:
                    return True
                else:
                    print 'completed tweet fetch'
                    session['completeTweetFetch'] = True
                    return False
            else:
                return True
        except:
            print 'Unexpected error', sys.exc_info()[0]

        return True
开发者ID:harsha-kadekar,项目名称:Chitralochana,代码行数:51,代码来源:DataDownloader.py


注:本文中的models.Tweet.save方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。