本文整理汇总了Python中twython.Twython.show_user方法的典型用法代码示例。如果您正苦于以下问题:Python Twython.show_user方法的具体用法?Python Twython.show_user怎么用?Python Twython.show_user使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类twython.Twython
的用法示例。
在下文中一共展示了Twython.show_user方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: update_profile_images
# 需要导入模块: from twython import Twython [as 别名]
# 或者: from twython.Twython import show_user [as 别名]
def update_profile_images():
users = User.objects()
for user in users:
current_app.logger.debug('looking up user: %s' % user.username)
twitter = Twython(TWITTER_KEY, TWITTER_SECRET, user.oauthToken, user.oauthTokenSecret)
user_info = twitter.show_user(screen_name=user.username)
current_app.logger.debug(' user "%s" profile img: %s' % (user.username, user_info['profile_image_url']))
# figure out paths to store the image, using the filename and extension provided by twitter
rawId = str(user.id)
img_filename = user_info['profile_image_url'].split('/')[-1]
img_path_relative = '/%s/%s' % (rawId, img_filename)
img_path_absolute = current_app.config['PATH_USER_PROFILE_IMAGE'] + img_path_relative
# ensure parent folder exists
img_parent_dir = os.path.dirname(img_path_absolute)
if not os.path.isdir(img_parent_dir): os.makedirs(img_parent_dir)
# download image
current_app.logger.debug(' downloading profile image to %s' % img_path_absolute)
urllib.urlretrieve(user_info['profile_image_url'], img_path_absolute)
# save changes to user
user.profileImage = img_path_relative
user.save()
示例2: index
# 需要导入模块: from twython import Twython [as 别名]
# 或者: from twython.Twython import show_user [as 别名]
def index():
if not session.SCREENNAME:
redirect('/')
response.title = 'Dashboard'
tweets = []
try:
twitter = Twython(myglobals.APP_KEY, myglobals.APP_SECRET, session.USER_OAUTH_TOKEN, session.USER_OAUTH_TOKEN_SECRET)
timeline = twitter.get_user_timeline(screen_name=session.SCREENNAME, count=20)
tweets = []
for data in timeline:
created = data['created_at'].split('+')[0].strip().split(' ')
short = created[0]+'-'+created[1]+'-'+created[2]
user = "@"+data['user']['screen_name']
url = ''
text = data['text']+' '+url
image = data['user']['profile_image_url']
if text.split(' @')[0]=='RT':
user = text.strip('RT').split(':')[0]
text = text.split(':')[1]
image = data['retweeted_status']['user']['profile_image_url']
if data['retweeted_status']['entities']['urls']:
url = data['retweeted_status']['entities']['urls'][0]['url']
session.HOMEPAGE = 'https://twitter.com/%s' % user.split('@')[1]
userlink = A(B(user),_class='user-homepage-link', _href=session.HOMEPAGE)
textdiv = DIV(userlink, P(text, _class="tweet-text"), A(_href=url, _class='user-homepage-link'))
tuple1 = (IMG(_src=image, _class="twitter-timeline-user-image"), textdiv)
tweet = [ tuple1 ]
tweets.append(tweet)
except Exception as e:
tweets = e
return dict(message=twitter.show_user(screen_name=session.SCREENNAME), timeline=tweets)
示例3: handle_twitter_callback
# 需要导入模块: from twython import Twython [as 别名]
# 或者: from twython.Twython import show_user [as 别名]
def handle_twitter_callback():
twitter = Twython(app.config['TWITTER_API_KEY'],app.config['TWITTER_API_SECRET'],
session['oauth_token'], session['oauth_token_secret'])
success = True
try:
final_step = twitter.get_authorized_tokens(request.json['oauth_verifier'])
user_oauth_token = final_step['oauth_token']
user_oauth_token_secret = final_step['oauth_token_secret']
user_twitter = Twython(app.config['TWITTER_API_KEY'],app.config['TWITTER_API_SECRET'],
user_oauth_token, user_oauth_token_secret)
twitter_user_show = user_twitter.show_user(user_id=final_step['user_id'])
current_user.set_twitter_data(final_step['user_id'], final_step['screen_name'], twitter_user_show)
new_twitter_auth = TwitterAuth(current_user.get_id(), user_oauth_token, user_oauth_token_secret)
db.session.add(new_twitter_auth)
db.session.commit()
tasks.get_tweets_per_user.delay(current_user.get_id())
# db.session.close()
except:
# print 'error in twitter auth'
success = False
return jsonify({'success': success})
示例4: showBasicInfo
# 需要导入模块: from twython import Twython [as 别名]
# 或者: from twython.Twython import show_user [as 别名]
def showBasicInfo(userName, keySet):
#Creating a new Twython object
show_user_twython = Twython(
app_key = authKeys.getA(keySet),
app_secret = authKeys.getB(keySet),
oauth_token = authKeys.getC(keySet),
oauth_token_secret = authKeys.getD(keySet))
#Creating the show_user json dictionary
show_user = show_user_twython.show_user(screen_name=userName)
print 'Name: ' + show_user.get('name') # Name of the account owner
print 'Screen Name: ' + show_user.get('screen_name') # Screen name # This is a bit redundant
print 'User ID: ' + show_user.get('id_str') # Numeric id of the account
#print 'Account Creation: ' + show_user.get('created_at') # Date the account was created in twitter datetime format
# Converting from twitter datetime format to python datetime format
account_creation = datetime.strptime(show_user.get('created_at'), '%a %b %d %H:%M:%S +0000 %Y')
print 'Account Creation: {:%m-%d-%Y}'.format(account_creation) # Formatting
age = (datetime.now() - account_creation).days # Account Age in days
print 'Account Age: ' + str(age / 365) + ' Years, ' + str(age % 365) + ' days' # Formatting
#print 'Account Location: ' + show_user.get('location')
# Users location # This requires decoding
# Total number of tweets
print 'Total Tweets: ' + str(show_user.get('statuses_count'))
# Average number of tweets each day
print 'Average Number of Tweets Per Day: ' + str('%.2f'%(float(show_user.get('statuses_count')) / float(age)))
示例5: oauthorized
# 需要导入模块: from twython import Twython [as 别名]
# 或者: from twython.Twython import show_user [as 别名]
def oauthorized():
"""twitter user diredirect ke /users/register saja
karena data yang disediakan twitter tidak se-komplit fb.
"""
resp = twitter.authorized_response()
if resp is None:
flash('You denied the request to sign in.')
else:
session['twitter_oauth'] = resp
"""
{'oauth_token': u'14355401-cSw2vYM4r6NAQGgC6Za3NYAu2E9DImNp8hmKbYBYI',
'oauth_token_secret': u'NCWm1Muoph1xkRqdGxmMvHlo67hbIgsxsqj5hoRBhczxX',
'screen_name': u'sopier',
'user_id': u'14355401'}
"""
user = dbusers.user.find_one({"twitter_name": resp["screen_name"]})
# jika user sudah memasukkan email
if user:
if user.get("email"):
session["email"] = user["email"]
else:
session["email"] = resp["screen_name"]
# pake twython aje
from twython import Twython
t = Twython(
app_key=TWITTER_KEY,
app_secret=TWITTER_SECRET,
oauth_token=resp["oauth_token"],
oauth_token_secret=resp["oauth_token_secret"])
twitterdata = t.show_user(screen_name="%s" % resp["screen_name"])
twimgurl = twitterdata["profile_image_url"]
# jika visitor dari twitter perlu ditandai dengan menyimpan screen_name
# jika sudah ada, maka tidak perlu register lagi, langsung di redirect ke
# halaman profil
# jika sudah lengkap email, nama depan, nama belakang dan password
# jika completed == True: baru boleh lapor
# pengguna fb completed = True
# register biasa completed = True
user = dbusers.user.find_one({"twitter_name": resp["screen_name"]})
if not user:
dbusers.user.insert({
"twitter_name": twitterdata["screen_name"],
"completed": False,
})
return redirect("/users/register?tw=%s" % resp["screen_name"])
# from pprint import pformat
# return Response(pformat(t.show_user(screen_name="%s" % resp["screen_name"])), mimetype='text/plain')
# cek apakah email, firstname, lastname sudah terisi?
# jika sudah bisa lapor, else ke profile
if user.get("email") and user.get("firstname") and user.get("lastname"):
return redirect("/users")
return redirect("/users/profile")
示例6: user_info
# 需要导入模块: from twython import Twython [as 别名]
# 或者: from twython.Twython import show_user [as 别名]
def user_info(request, screen_name):
try:
django_user = User.objects.get(username=screen_name)
current_user = TwitterProfile(user=django_user)
APP_KEY = "f0wDo5a57mSLYIuaIU4nZA"
APP_SECRET = "XKgYeEng2G1qhVNhH3xae4r5LbDzcGD0QzRQp7nc"
twitter = Twython(APP_KEY, APP_SECRET, current_user.oauth_token, current_user.oauth_secret)
return HttpResponse(json.dumps(twitter.show_user(screen_name=screen_name)), content_type="application/json")
except:
return HttpResponse(json.dumps({"errors" : "Count not find user " + screen_name}), content_type="application/json")
示例7: twitter_image
# 需要导入模块: from twython import Twython [as 别名]
# 或者: from twython.Twython import show_user [as 别名]
def twitter_image(request, username):
cachekey = "twitter-image-url:%s" % (username,)
image_url = cache.get(cachekey)
if image_url is None:
print "fetch from twitter"
twitter = Twython(os.environ.get("SOCIAL_AUTH_TWITTER_KEY"),
access_token=os.environ.get("TWITTER_OAUTH2_ACCESS_TOKEN"))
image_url = twitter.show_user(screen_name=username).get("profile_image_url")
cache.set(cachekey, image_url)
return redirect(image_url)
示例8: get_user_data
# 需要导入模块: from twython import Twython [as 别名]
# 或者: from twython.Twython import show_user [as 别名]
def get_user_data(self, oauth_token = None, oauth_verifier = None, user_id=None):
"""Returns user ID within the OAuth provider system,
based on ``oauth_token`` and ``oauth_verifier``
"""
data = self.get_access_token(oauth_token, oauth_verifier)
twitter = Twython(self.parameters['consumer_key'], self.parameters['consumer_secret'],
data['oauth_token'], data['oauth_token_secret'])
data = twitter.show_user(user_id=user_id)
return self.parameters['get_user_data_function'](data)
示例9: getUserProfile
# 需要导入模块: from twython import Twython [as 别名]
# 或者: from twython.Twython import show_user [as 别名]
def getUserProfile(user_id=None, screen_name=None):
if user_id is None and screen_name is None:
return None
consumer_key = "MLGdNZCfmzGthHTAyJU4KFvbU"
consumer_secret ="Tfp7DIZcJLbnS8BR5CWQmZklrhsbtc3fMfssKPT4SZoYsPiQKw"
access_token ="2383540880-s2C8xPgA4ITF7QnLRFnHK1es2UEbmW8qHQ87sX5"
access_token_secret ="kLYgBTPeslLgaFugCx0PoiBpPIKnyCBEVfqqJCkjsSKpP"
twitter = Twython(consumer_key, consumer_secret,access_token,access_token_secret)
if screen_name:
while(True):
try:
user_profile = twitter.show_user(screen_name=screen_name)
return user_profile
except TwythonRateLimitError:
print("Fall asleep")
sleep(300)
pass
except TwythonAuthError:
print("Bad Authentication")
return []
except TwythonError:
print("404 not found")
return []
else:
while(True):
try:
user_profile = twitter.show_user(id = user_id)
return user_profile
except TwythonRateLimitError:
print("Fall asleep")
sleep(300)
pass
except TwythonAuthError:
print("Bad Authentication")
return []
except TwythonError:
print("404 not found")
return []
示例10: get_userinfo_intoDB
# 需要导入模块: from twython import Twython [as 别名]
# 或者: from twython.Twython import show_user [as 别名]
def get_userinfo_intoDB(table):
index = 0
#get users that need to be updated
conn = sqlite3.connect("tweets.sqlite")
cursor = conn.cursor()
#query = "select Usr_ID from tweets9_users where NumFollowers is null"
query = "select Usr_ID from users where Description is null or Screename is null"
cursor.execute(query)
users = cursor.fetchall()
i = 0
for user in users:
try:
APP_KEY = APP_KEYS[index]
APP_SECRET = APP_SECRETS[index]
OAUTH_TOKEN = OAUTH_TOKENS[index]
OAUTH_TOKEN_SECRET = OAUTH_TOKEN_SECRETS[index]
twitter = Twython (APP_KEY, APP_SECRET)
auth = twitter.get_authentication_tokens()
twitter = Twython(APP_KEY, APP_SECRET, OAUTH_TOKEN, OAUTH_TOKEN_SECRET)
usr_id = int(user[0])
result = twitter.show_user(user_id = user[0])
fo_count = int(result["followers_count"])
fr_count = int(result["friends_count"])
screename = str(result["screen_name"])
descript= str(result['description'])
query = "update %s set NumFollowers=%d, NumFollowing=%d, Screename ='%s', Description=\"\"\"%s\"\"\" where Usr_ID=%d;"%(table, fo_count, fr_count, screename, descript, usr_id)
cursor.execute(query)
conn.commit()
print i
i+=1
except Exception as e:
if "429 (Too Many Requests)" in str(e):
print "\nchanging apps!\n"
if index >= 7:
print "sleepy time"
print datetime.datetime.now()
time.sleep(860)
index = 0
index = index + 1
elif "401 (Unauthorized)" in str(e):
print "401 error"
elif "404 (Not Found)" in str(e):
print "404 error"
else:
print e
return
示例11: get_account_details
# 需要导入模块: from twython import Twython [as 别名]
# 或者: from twython.Twython import show_user [as 别名]
def get_account_details(log, id):
log.debug(" Getting account details for %s", id)
check_twitter_config()
logging.captureWarnings(True)
old_level = log.getEffectiveLevel()
log.setLevel(logging.ERROR)
twitter = Twython(APP_KEY, APP_SECRET, OAUTH_TOKEN, OAUTH_TOKEN_SECRET)
try:
details = twitter.show_user(screen_name=id)
except TwythonAuthError, e:
log.setLevel(old_level)
log.exception(" Problem trying to get account details")
twitter_auth_issue(e)
raise
示例12: get_new
# 需要导入模块: from twython import Twython [as 别名]
# 或者: from twython.Twython import show_user [as 别名]
def get_new(screen_name):
temp_dict=dict()
followers=dict()
l1=['friends']
twitter = Twython(CONSUMER_KEY , CONSUMER_SECRET,ACCESS_KEY, ACCESS_SECRET)
user = screen_name
fnum = 5000
try:
check_rate_limit_status('application/rate_limit_status')
except Exception as e:
print e
print 'sleeping for 15 mins...'
time.sleep(900)
try:
suser = twitter.show_user(screen_name=user)
temp_dict['_id']=smart_str(suser['id'])
temp_dict['id']=smart_str(suser['id'])
temp_dict['screen_name']=smart_str(suser['screen_name'])
for typ in l1:
dname=dict()
pnum = int(math.ceil(float(suser[str(typ)+"_count"]) / fnum))
pages = []
for i in range(pnum):
pages.append("p"+str(i+1))
oldpages = []
for i in range(pnum):
oldpages.append("p"+str(i))
p0 = { "next_cursor": -1 } # So the following exec() call doesn't fail.
for i in range(pnum):
check_rate_limit_status1(typ+'/ids',typ)
# exec(pages[i]+" = twitter.get_"+str(typ)+"_ids(screen_name=user, count=fnum, skip_status=1, cursor="+oldpages[i]+"['next_cursor'])")
exec(pages[i]+" = twitter.get_"+str(typ)+"_ids(screen_name=user, count=fnum, cursor="+oldpages[i]+"['next_cursor'])")
followers = []
for p in range(pnum):
try:
exec("for i in range(fnum): followers.append("+pages[p]+"['ids'][i])")
except(IndexError):
pass
temp_dict[str(typ)]=followers
print'No. of %s:%d'%(typ,len(followers))
except:
print screen_name
return 0
return temp_dict
示例13: get_twitter_avatar_url
# 需要导入模块: from twython import Twython [as 别名]
# 或者: from twython.Twython import show_user [as 别名]
def get_twitter_avatar_url(twitter_handle):
"""
gets the icon URL for a given twitter handle from the API
"""
app_key = app.config['TWITTER_APP_KEY']
app_secret = app.config['TWITTER_APP_SECRET']
if 'TWITTER_ACCESS_TOKEN' not in app.config:
access_token = Twython(app_key, app_secret, oauth_version=2)\
.obtain_access_token()
app.config['TWITTER_ACCESS_TOKEN'] = access_token
else:
access_token = app.config['TWITTER_ACCESS_TOKEN']
t = Twython(app_key, access_token=access_token)
user_obj = t.show_user(screen_name=twitter_handle)
return user_obj['profile_image_url']
示例14: get
# 需要导入模块: from twython import Twython [as 别名]
# 或者: from twython.Twython import show_user [as 别名]
def get(self, request, page=None, modifier=None, *args, **kwargs):
callback = {}
if modifier:
print "using a modifier"
item_list = Item.objects.all()
else:
item_list = Item.objects.all()
# Pagination: https://docs.djangoproject.com/en/1.7/topics/pagination/
paginated_items = Paginator(item_list, 9)
try:
items = paginated_items.page(page)
callback['next_page'] = int(page) + 1
except PageNotAnInteger:
items = paginated_items.page(1)
callback['next_page'] = 2
except EmptyPage:
items = paginated_items.page(paginated_items.num_pages)
except Exception as e:
print e
items = None
callback['item_list'] = items
if page is None:
callback['first_page'] = True
#################################################################
# This is a hack - because twitter profile pic is annoying to get
if request.user.id is not None:
if request.user.profile_img_url is None:
user = Contributor.objects.get(username=request.user)
social = user.social_auth.get(provider='twitter')
access_token = social.extra_data['access_token']
t = Twython(app_key=SOCIAL_AUTH_TWITTER_KEY,
app_secret=SOCIAL_AUTH_TWITTER_SECRET,
oauth_token=access_token[u'oauth_token'],
oauth_token_secret=access_token[u'oauth_token_secret'])
twitter_account = t.show_user(screen_name=request.user.username)
profile_img_url = twitter_account[u'profile_image_url']
user.profile_img_url = profile_img_url
user.save()
#################################################################
return render(request, self.template_name, callback)
示例15: home
# 需要导入模块: from twython import Twython [as 别名]
# 或者: from twython.Twython import show_user [as 别名]
def home(request):
# Si ha iniciado sesion
if 'oauth_token' in request.session:
try:
twitter = Twython( KeySecretApp.app_key, KeySecretApp.app_secret, request.session["oauth_token"], request.session["oauth_token_secret"] )
except Exception, e:
return render_to_response('error.html',context_instance=RequestContext(request))
user = request.session["user"]
JSONuser = twitter.show_user( screen_name = user )
request.session["profile_photo"] = JSONuser['profile_image_url_https']
profile_photo = request.session["profile_photo"]
home_timeline = twitter.get_home_timeline()
for item in home_timeline:
item['text'] = TransformarTweet.convertirTweet(item['text'])
request.session['max_id'] = home_timeline[ len( home_timeline ) -1 ]['id']
request.session['ultimo_id'] = int ( home_timeline[0]['id'] - 4 )
return render_to_response('home.html',{'tweets':home_timeline , 'profile_photo':profile_photo ,'user':user}, context_instance=RequestContext(request))