本文整理汇总了Python中models.User.access_token方法的典型用法代码示例。如果您正苦于以下问题:Python User.access_token方法的具体用法?Python User.access_token怎么用?Python User.access_token使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类models.User
的用法示例。
在下文中一共展示了User.access_token方法的13个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: current_user
# 需要导入模块: from models import User [as 别名]
# 或者: from models.User import access_token [as 别名]
def current_user(self):
"""
:returns object: User object or None
"""
if not hasattr(self, "_current_user"):
logging.info("not hasattr")
self._current_user = None
cookie = facebook.get_user_from_cookie(
self.request.cookies,
self.app.config.get("FACEBOOK_APP_ID", ""),
self.app.config.get("FACEBOOK_APP_SECRET", ""))
logging.info(str(self.request.cookies))
if cookie:
logging.info("if cookie")
# Store a local instance of the user data so we don't need
# a round-trip to Facebook on every request
user = User.get_by_key_name(cookie["uid"])
if not user:
logging.info("if not user")
graph = facebook.GraphAPI(cookie["access_token"])
profile = graph.get_object("me")
user = User(key_name=str(profile["id"]),
id=str(profile["id"]),
name=profile["name"],
profile_url=profile["link"],
access_token=cookie["access_token"])
user.put()
elif user.access_token != cookie["access_token"]:
logging.info("elif user.access_token")
user.access_token = cookie["access_token"]
user.put()
self._current_user = user
# else:
# return None
return self._current_user
示例2: current_user
# 需要导入模块: from models import User [as 别名]
# 或者: from models.User import access_token [as 别名]
def current_user(self):
if not hasattr(self, "_current_user"):
self._current_user = None
cookie = facebook.get_user_from_cookie(
self.request.cookies, FACEBOOK_APP_ID, FACEBOOK_APP_SECRET)
if cookie:
# Store a local instance of the user data so we don't need
# a round-trip to Facebook on every request
user = User.get_by_key_name(cookie["uid"])
if not user:
graph = facebook.GraphAPI(cookie["access_token"])
profile = graph.get_object("me")
# Change the user type's key to be a unique key (maybe openid)
user = User(key_name=str(profile["id"]),
#user = User(key_name=str(api.users.get_current_user().email()),
guser=api.users.get_current_user(),
fbid=str(profile["id"]),
name=profile["name"],
profile_url=profile["link"],
access_token=cookie["access_token"])
user.put()
elif user.access_token != cookie["access_token"]:
user.access_token = cookie["access_token"]
user.put()
self._current_user = user
return self._current_user
示例3: authorize
# 需要导入模块: from models import User [as 别名]
# 或者: from models.User import access_token [as 别名]
def authorize():
error = request.args.get('error')
code = request.args.get('code')
state = request.args.get('state')
#TODO: Handle state here
if error:
flash(error, 'error')
#TODO: Handle error here
return redirect(url_for('home'))
if not code:
#TODO: No code received, something went wrong
return redirect(url_for('home'))
else:
reddit = get_reddit()
access_info = reddit.get_access_information(code)
praw_user = reddit.get_me()
user = User.get_by_id(praw_user.name)
if not user:
user = User(
id=praw_user.name,
username=praw_user.name,
created_reddit=datetime.fromtimestamp(praw_user.created)
)
user.access_token = access_info['access_token']
user.refresh_token = access_info['refresh_token']
user.put()
session['user'] = user.username
return redirect(url_for('home'))
示例4: current_user
# 需要导入模块: from models import User [as 别名]
# 或者: from models.User import access_token [as 别名]
def current_user(self):
try:
"""Returns the active user, or None if the user has not logged in."""
if not hasattr(self, "_current_user"):
self._current_user = None
cookie = facebook.get_user_from_cookie(
self.request.cookies, self.get_config('facebook', 'app_id'), self.get_config('facebook', 'app_secret'))
if cookie:
# Store a local instance of the user data so we don't need
# a round-trip to Facebook on every request
user = User.get_by_key_name(cookie["uid"])
if not user:
graph = facebook.GraphAPI(cookie["access_token"])
profile = graph.get_object("me")
user = User(key_name=str(profile["id"]),
id=str(profile["id"]),
name=profile["name"],
email=profile["email"],
profile_url=profile["link"],
access_token=cookie["access_token"])
user.put()
try:
name = user.name.split()
fname = name[0]
lname = name[len(name)-1]
deferred.defer(export_email_mailchimp,{'email':user.email,"fname":fname,"lname":lname})
except:
pass
elif user.access_token != cookie["access_token"]:
user.access_token = cookie["access_token"]
user.put()
self._current_user = user
return self._current_user
except:
self._current_user = None
示例5: current_user
# 需要导入模块: from models import User [as 别名]
# 或者: from models.User import access_token [as 别名]
def current_user(self):
if self.session.get("user"):
return self.session.get("user")
else:
cookie = facebook.get_user_from_cookie(self.request.cookies,
FACEBOOK_APP_ID,
FACEBOOK_APP_SECRET)
if cookie:
user = User.get_by_key_name(cookie["uid"])
if not user:
graph = facebook.GraphAPI(cookie["access_token"])
profile = graph.get_object("me")
user = User(
key_name = str(profile["id"]),
id = str(profile["id"]),
name = profile["name"],
profile_url = profile["link"],
access_token = cookie["access_token"]
)
user.put()
elif user.access_token != cookie["access_token"]:
user.access_token = cookie["access_token"]
user.put()
self.session["user"] = dict(
name = user.name,
profile_url = user.profile_url,
id = user.id,
access_token = user.access_token
)
return self.session.get("user")
return None
示例6: get_current_user
# 需要导入模块: from models import User [as 别名]
# 或者: from models.User import access_token [as 别名]
def get_current_user():
"""Set g.user to the currently logged in user.
Called before each request, get_current_user sets the global g.user
variable to the currently logged in user. A currently logged in user is
determined by seeing if it exists in Flask's session dictionary.
If it is the first time the user is logging into this application it will
create the user and insert it into the database. If the user is not logged
in, None will be set to g.user.
"""
# A/B test value
g.ab = _ab()
# Set the user in the session dictionary as a global g.user and bail out
# of this function early.
if session.get('user'):
user = session.get('user')
user = User.query.filter(User.id == user['id']).first()
g.user = user
return
# Attempt to get the short term access token for the current user.
result = get_user_from_cookie(cookies=request.cookies, app_id=app.config['FB_APP_ID'],
app_secret=app.config['FB_SECRET'])
# If there is no result, we assume the user is not logged in.
if result:
# Check to see if this user is already in our database.
user = User.query.filter(User.id == result['uid']).first()
if not user:
# Not an existing user so get info
graph = GraphAPI(result['access_token'])
profile = graph.get_object('me')
# Create the user and insert it into the database
user = User(id=str(profile['id']), name=profile['name'],
profile_url=profile['link'],
access_token=result['access_token'])
db.session.add(user)
elif user.access_token != result['access_token']:
# If an existing user, update the access token
user.access_token = result['access_token']
# Add the user to the current session
session['user'] = dict(name=user.name, profile_url=user.profile_url,
id=user.id, access_token=user.access_token,
admin=user.admin)
# Commit changes to the database and set the user as a global g.user
db.session.commit()
g.user = session.get('user', None)
else:
g.user = None
示例7: current_user
# 需要导入模块: from models import User [as 别名]
# 或者: from models.User import access_token [as 别名]
def current_user(self):
if self.session.get("user"):
# User is logged in
return self.session.get("user")
else:
# Either used just logged in or just saw the first page
# We'll see here
cookie = facebook.get_user_from_cookie(self.request.cookies,
FACEBOOK_APP_ID,
FACEBOOK_APP_SECRET)
if cookie:
# Okay so user logged in.
# Now, check to see if existing user
user = User.get_by_key_name(cookie["uid"])
if not user:
# Not an existing user so get user info
graph = facebook.GraphAPI(cookie["access_token"])
profile = graph.get_object("me")
email_verified = False
verification_code = generate_verification_code()
user = User(
key_name=str(profile["id"]),
id=str(profile["id"]),
name=profile["name"],
profile_url=profile["link"],
access_token=cookie["access_token"],
email_verified = email_verified,
verification_code = verification_code,
)
user.put()
elif user.access_token != cookie["access_token"]:
user.access_token = cookie["access_token"]
user.put()
# User is now logged in
self.session["user"] = dict(
name=user.name,
profile_url=user.profile_url,
id=user.id,
access_token=user.access_token,
email_verified = user.email_verified,
verification_code = user.verification_code,
#is_part_of_rangoli = self.is_part_of_group(cookie, RANGOLI_GROUP_ID)
is_part_of_rangoli = True
)
return self.session.get("user")
return None
示例8: authorized
# 需要导入模块: from models import User [as 别名]
# 或者: from models.User import access_token [as 别名]
def authorized():
resp = google.authorized_response()
if resp is None:
return 'Access denied: reason=%s error=%s' % (
request.args['error_reason'],
request.args['error_description']
)
if isinstance(resp, OAuthException):
return 'Access denied: %s' % resp.message
session['user_token'] = (resp['access_token'], '')
me = google.get('userinfo')
access_token = resp['access_token']
name = me.data['name']
picture = me.data['picture']
# Check if user already exists on database
user = db_session.query(User).filter_by(access_token=access_token).first()
if user is None:
user = User(access_token, name, picture)
db_session.add(user)
# store access token into database
user.access_token = access_token
db_session.commit()
# store user data on session
session['user_id'] = user.id
session['user_token'] = user.access_token
session['user_name'] = user.name
session['user_picture'] = user.picture
flash('You\'re logged in!', 'success')
return redirect(url_for('index'))
示例9: authenticate
# 需要导入模块: from models import User [as 别名]
# 或者: from models.User import access_token [as 别名]
def authenticate():
# Check for errors in authentication
error = request.args.get('error')
if error:
flash(error)
return redirect(url_for('login'))
# Validate state to prevent XSRF
state = request.args.get('state')
if not is_valid_state(state):
abort(403)
# Get access token with provided single-use code
code = request.args.get('code')
access_token = get_token(code)
# Get username with access token
username = get_username(access_token)
# Get User object (if exists)
user = User.query.filter_by(username = username).first()
# If not, create user
if user is None:
user = User(username = username)
db.session.add(user)
# Save new access token
user.access_token = access_token
db.session.commit()
# Login user with User object
login_user(user)
return redirect(request.args.get('next') or url_for('index'))
示例10: get
# 需要导入模块: from models import User [as 别名]
# 或者: from models.User import access_token [as 别名]
def get(self):
if self.request.get('code'):
url = 'https://api.instagram.com/oauth/access_token'
post = 'client_id=&client_secret=&redirect_uri=http://instadaily.appspot.com/auth/&grant_type=authorization_code&code=%s' % self.request.get(
'code')
try:
result = urlfetch.fetch(url=url, payload=str(post), method=urlfetch.POST)
except urlfetch.DownloadError:
logging.error('User could not connect with Instagram auth')
return self.response.out.write('We could not connect to Instagram. Please try again soon.')
if result.status_code == 200:
res = json.loads(result.content)
md5 = hashlib.md5()
md5.update('%s%s' % (res['access_token'], SECRET))
token = md5.hexdigest()
if User.all().filter('instagram_id =', res['user']['id']).count() == 0:
user = User()
user.token = token
user.access_token = res['access_token'] # instagram's one
user.name = res['user']['username']
user.instagram_id = res['user']['id']
user.full_name = res['user']['full_name']
user.pic = res['user']['profile_picture']
user.photos = 0
user.vote_like = 0
user.vote_dislike = 0
try:
user.last_subject_id = Subject().get_current().key().id()
except AttributeError:
logging.error('cannot find current subject!!!')
user.last_subject_id = 0
user.last_subject_points = 0
user.put()
else:
user = User.all().filter('instagram_id =', res['user']['id']).get()
user.token = token
user.access_token = res['access_token'] # instagram's one
user.pic = res['user']['profile_picture']
user.full_name = res['user']['full_name']
user.put()
# put data to remote server
url = 'http://www.instadailyapp.com/auth/'
# fill in with data
user_dict = user.to_dict()
user_dict['token'] = user.token
user_dict['access_token'] = user.access_token
user_dict['full_name'] = ''
user_dict['vote_like'] = user.vote_like
user_dict['vote_dislike'] = user.vote_dislike
post = 'user=%s' % json.dumps(user_dict)
try:
result = urlfetch.fetch(url=url, payload=str(post), method=urlfetch.POST)
except urlfetch.DownloadError:
logging.error('Remote server failed!')
if result.status_code != 200:
logging.error('Remote server failed with %s!' % result.status_code)
template = """
<html><head><style type="text/css">body { color: #ffffff; }</style></head>
<body>%s</body></html>
""" % json.dumps({
'status': 'ok',
'user': user.to_dict(),
'token': token
})
self.response.out.write(template)
else:
logging.warning('failed to receive token. response: %s' % result.content)
self.response.out.write('failed to receive token: %s' % result.content)
elif self.request.get('error'):
# Access Denied
self.redirect(
'http://instagram.com/oauth/authorize/?client_id=&redirect_uri=http://instadaily.appspot.com/auth/&response_type=code&scope=comments+likes&display=touch')
else:
logging.info('unknown request')
self.response.out.write('unknown request')
示例11: current_user
# 需要导入模块: from models import User [as 别名]
# 或者: from models.User import access_token [as 别名]
def current_user(self):
if settings.DEBUG:
# Since we can't test real FB user on localhost
# I made a fake account
user = User.get_by_key_name('100000145269859')
if not user:
user = User(
key_name='100000145269859',
id='100000145269859',
username='ekaputra07',
name='Eka Putra',
profile_url='https://facebook.com/ekaputra07',
is_admin=True,
access_token='AAAH4xJelaP7vErxcrgPn7VZCdFfmUReP6ZC29tYHui5OO',
)
user.put()
self.session['user'] = dict(
username=user.username,
name=user.name,
profile_url=user.profile_url,
id=user.id,
access_token=user.access_token,
is_admin=user.is_admin,
)
return self.session.get('user');
else:
if self.session.get("user"):
# User is logged in
return self.session.get("user")
else:
# Either used just logged in or just saw the first page
# We'll see here
cookie = facebook.get_user_from_cookie(self.request.cookies,
settings.FACEBOOK_APP_ID,
settings.FACEBOOK_APP_SECRET
)
if cookie:
# Okay so user logged in.
# Now, check to see if existing user
user = User.get_by_key_name(cookie["uid"])
if not user:
# Not an existing user so get user info
graph = facebook.GraphAPI(cookie["access_token"])
profile = graph.get_object("me")
username = profile.get('username', 'user%s' % str(profile['id'])[-4:])
user = User(
key_name=str(profile['id']),
id=str(profile['id']),
username=username,
name=profile['name'],
profile_url=profile['link'],
access_token=cookie['access_token']
)
user.put()
elif user.access_token != cookie['access_token']:
user.access_token = cookie['access_token']
user.put()
# User is now logged in
self.session['user'] = dict(
username=user.username,
name=user.name,
profile_url=user.profile_url,
id=user.id,
access_token=user.access_token,
is_admin=user.is_admin,
)
return self.session.get("user")
return None
示例12: current_user
# 需要导入模块: from models import User [as 别名]
# 或者: from models.User import access_token [as 别名]
def current_user(self):
if self.session.get("user"):
# User is logged in
logging.info("User is logged in.")
return self.session.get("user")
else:
logging.info("Check if user is logged in to Facebook.")
# Either used just logged in or just saw the first page
# We'll see here
try:
cookie = facebook.get_user_from_cookie(self.request.cookies,
FACEBOOK_APP_ID,
FACEBOOK_APP_SECRET)
except HTTPError as err:
logging.error(err.code)
logging.error(err.reason)
return None
if cookie:
# Okay so user logged in.
# Now, check to see if existing user
user = User.get_by_key_name(cookie["uid"])
logging.info("Cookie found, user is logged in.")
if not user:
logging.info('New app user')
graph = facebook.GraphAPI(version=2.1,access_token=cookie["access_token"])
# also get long live access token for approved off-line access
offline_token_full = graph.extend_access_token(app_id=FACEBOOK_APP_ID,app_secret=FACEBOOK_APP_SECRET)
offline_token = offline_token_full["access_token"]
#logging.info('old token expires %s', cookie['expires'])
#logging.info('new token expires %s', offline_token_full['expires'])
profile = graph.get_object("me")
user = User(
key_name=str(profile["id"]),
id=str(profile["id"]),
name=profile["name"],
profile_url=profile["link"],
access_token=cookie["access_token"],
offline_token=offline_token,
offline_token_created=datetime.utcnow(),
)
user.put()
elif user.access_token != cookie["access_token"]:
logging.info('Existing app user with new access token')
# Facebook will only extend the expiration time once per day
# @see https://developers.facebook.com/docs/roadmap/completed-changes/offline-access-removal
if user.offline_token_created.date() < datetime.utcnow().date():
graph = facebook.GraphAPI(version=2.1,access_token=cookie["access_token"])
user.offline_token = graph.extend_access_token(app_id=FACEBOOK_APP_ID,app_secret=FACEBOOK_APP_SECRET)['access_token']
user.offline_token_created = datetime.utcnow()
user.offline_token_expires = (datetime.utcnow() + timedelta(0,int(cookie["expires"])))
user.access_token = cookie["access_token"]
user.put()
# User is now logged in
self.session["user"] = dict(
name=user.name,
profile_url=user.profile_url,
id=user.id,
access_token=user.offline_token,
)
return self.session.get("user")
logging.info("No user logged in.")
return None
示例13: analyze
# 需要导入模块: from models import User [as 别名]
# 或者: from models.User import access_token [as 别名]
def analyze(username):
user_q = User.query.filter_by(nickname = username).first()
with_access_token = False
if user_q != None:
#print user_q.access_token
data = search(username, user_q.access_token)
#print user_q.access_token
with_access_token = True
else:
new_user = User(nickname = username, scanned = False)
db.session.add(new_user)
db.session.commit()
data = search(username, access_token)
with_access_token = False
user_q = User.query.filter_by(nickname = username).first()
print data
if data and user_q.scanned == False:
#print 'OK_1'
#print type(new_user)
if with_access_token:
new_user = User.query.filter_by(nickname = username).first()
new_user.name = data[0][1]
new_user.user_id = data[0][0]
new_user.website = data[0][2]
new_user.media_counts = data[0][3]
new_user.likes_counts = data[0][4]
new_user.follows_counts = data[0][5]
new_user.followed_by_counts = data[0][6]
new_user.profile_photo = data[0][7]
new_user.bio = data[0][8]
new_user.scanned = True
db.session.commit()
#new_user = User(name = data[0][1], user_id = data[0][0], website = data[0][2],
# media_counts = data[0][3], likes_counts = data[0][4], follows_counts = data[0][5],
# followed_by_counts = data[0][6], profile_photo = data[0][7], bio = data[0][8])
else:
new_user = User.query.filter_by(nickname = username).first()
new_user.name = data[0][1]
new_user.user_id = data[0][0]
new_user.website = data[0][2]
new_user.media_counts = data[0][3]
new_user.likes_counts = data[0][4]
new_user.follows_counts = data[0][5]
new_user.followed_by_counts = data[0][6]
new_user.profile_photo = data[0][7]
new_user.bio = data[0][8]
new_user.access_token = ""
new_user.scanned = True
#new_user = User(name = data[0][1], nickname = username, user_id = data[0][0], website = data[0][2],
# media_counts = data[0][3], likes_counts = data[0][4], follows_counts = data[0][5],
# followed_by_counts = data[0][6], profile_photo = data[0][7], bio = data[0][8], scanned = True)
db.session.commit()
#print 'OK'
#print type(new_user)
for obj in data[1]:
image = UserImages(images = unicode(obj[0]), quantity = obj[1], author = new_user)
db.session.add(image)
for obj in data[2]:
video = UserVideos(videos = unicode(obj), author = new_user)
db.session.add(video)
for obj in data[3]:
caption = UserCaptions(captions = unicode(obj[0]), quantity = obj[1], author = new_user)
db.session.add(caption)
for obj in data[4]:
hashtag = UserHashtags(hashtags = unicode(obj[0]), quantity = obj[1], author = new_user)
db.session.add(hashtag)
for obj in data[5]:
location = UserLocations(locations = unicode(obj[0]), quantity = obj[1] , author = new_user)
db.session.add(location)
for obj in data[6]:
comment = UserComments(comments = unicode(obj), author = new_user)
db.session.add(comment)
for obj in data[7]:
user = UserLiked(name = unicode(obj[0]), quantity = obj[1], author = new_user)
db.session.add(user)
for obj in data[8]:
user = LikesOfUsers(name = unicode(obj[0]), quantity = obj[1], author = new_user)
db.session.add(user)
for obj in data[9]:
user = CommentRating(name = unicode(obj[0]), quantity = obj[1], author = new_user)
db.session.add(user)
for obj in data[10]:
user = UserFilters(name = unicode(obj[0]), quantity = obj[1], author = new_user)
db.session.add(user)
db.session.commit()
return render_template('successful_adding.html')
else:
return render_template('user_not_exist.html', username = username)