本文整理汇总了Python中facebook.Facebook类的典型用法代码示例。如果您正苦于以下问题:Python Facebook类的具体用法?Python Facebook怎么用?Python Facebook使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Facebook类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: AuthFactory
class AuthFactory(object):
# TODO: begin auth/verify auth needed
@staticmethod
def FacebookAuth(func):
def authenticated_request_method(self, *args, **kw):
from gaesessions import get_current_session
session = get_current_session()
self.user = None
self.fb = Facebook(creds['AppSecret'], creds['AppID'])
if session.has_key('fb_auth_state') and session['fb_auth_state'] == self.request.get('state'):
if self.fb.exchange_code_for_auth_token(self.request):
session.terminate()
session = get_current_session()
session['uid'] = 'F' + self.fb.uid
self.user = UserFactory.getFacebookUser(self.fb)
else:
if session.has_key('uid'):
self.user = UserFactory.getFacebookUserById(session['uid'])
elif not self.fb.check_authentication(self.request):
if session.is_active():
session.terminate()
import hashlib
md5 = hashlib.md5()
md5.update("cam is cool")
session['fb_auth_state'] = md5.hexdigest()
else:
if not session.has_key('uid'):
session['uid'] = 'F' + self.fb.uid
self.user = UserFactory.getFacebookUser(self.fb)
func(self, *args, **kw)
return authenticated_request_method
示例2: desktop_app
def desktop_app():
userdata = {}
apiattr = ['uid', 'name', 'about_me', 'activities', 'birthday_date', 'relationship_status',
'books', 'current_location', 'email_hashes', 'first_name', 'hometown_location',
'hs_info', 'interests', 'last_name', 'locale', 'meeting_for', 'meeting_sex',
'movies', 'music', 'notes_count', 'notes_count', 'pic_with_logo', 'pic_big',
'pic_big_with_logo','pic_small','pic_small_with_logo','pic_square','pic_square_with_logo',
'political','profile_blurb','profile_update_time','profile_url','proxied_email',
'quotes','religion','sex','significant_other_id','status','timezone','tv','username',
'username','wall_count','website','work_history',
'education_history', 'affiliations']
# Get api_key and secret_key from a file
homedir = os.path.expanduser('~')
fbs = open(homedir + '/.fbkeys').readlines()
facebook = Facebook(fbs[0].strip(), fbs[1].strip())
file = open('fbdat_1.txt', 'w')
facebook.auth.createToken()
# Show login window
facebook.login()
wait_login() # somehow wait for the user to log in
# Login to the window, then press enter
#print 'After logging in, press enter...'
#raw_input()
facebook.auth.getSession()
info = facebook.users.getInfo([facebook.uid], ['name', 'birthday', 'affiliations', 'sex'])[0]
for attr in info:
print '%s: %s' % (attr, info[attr])
friends = facebook.friends.get()
print friends
dat = facebook.users.getInfo(friends,apiattr)
print '################################ DAT #########################'
print dat
for da in dat: # put to dict
userdata[da[u'uid']] = da
print '################################ USERDATA ####################'
print userdata
pickle.dump(userdata, file)
## for user in userdata:
## #if not user.haskey(u'uid'):
## s = str(userdata[user])
## sd = s.encode(output_encoding)
## file.write(sd)
file.close()
exit()
示例3: context_processor
def context_processor(request) :
key = None
if 'facebook' in settings.OPENAUTH_DATA and 'key' in settings.OPENAUTH_DATA['facebook'] :
key = settings.OPENAUTH_DATA['facebook']['key']
result = {}
user = get_user(request)
if not user.is_anonymous() :
from views import GENERATED_USERBASE
result.update({
'openauth' : {
'need_name' : len(user.get_full_name()) == 0,
#'need_screen' : user.username.find(GENERATED_USERBASE) == 0,
'need_email' : user.email == '',
}
})
inCanvas = False
if 'facebook' in settings.OPENAUTH_DATA :
from facebook import Facebook
fb = Facebook(settings.OPENAUTH_DATA['facebook']['key'], settings.OPENAUTH_DATA['facebook']['secret'])
fb.check_session(request)
inCanvas = fb.in_canvas
result.update({
'facebook' : {
'apikey' : key,
'inCanvas' : inCanvas,
}
})
return result
示例4: get_user
def get_user(request):
from django.contrib.auth.models import AnonymousUser
if 'facebook' in settings.OPENAUTH_DATA :
from facebook import Facebook
fb = Facebook(settings.OPENAUTH_DATA['facebook']['key'], settings.OPENAUTH_DATA['facebook']['secret'])
fb.check_session(request)
if fb.uid is not None :
identity = 'facebook:%s' % fb.uid
try :
from .models import OpenUser
oiuser = OpenUser.objects.get(openid=identity, source='openid')
return oiuser.user
except OpenUser.DoesNotExist :
pass
try:
auth = request.COOKIES.get(AUTH_COOKIE, '')
parts = auth.split('|')
if len(parts) != 4 :
user = AnonymousUser()
elif parts[3] == md5("|".join([parts[0], parts[1], parts[2], settings.SECRET_KEY])).hexdigest() :
backend = load_backend(parts[2])
user = backend.get_user(parts[0]) or AnonymousUser()
else :
user = AnonymousUser()
except KeyError:
user = AnonymousUser()
return user
示例5: fbLogin
def fbLogin():
from facebook import Facebook
facebook = Facebook(API,SECRET)
facebook.auth.createToken()
facebook.login()
facebook.auth.getSession()
return facebook
示例6: authenticate
def authenticate(self, request):
if not settings.FACEBOOK_API_KEY in request.COOKIES:
return None
facebook = Facebook(settings.FACEBOOK_API_KEY,
settings.FACEBOOK_SECRET_KEY)
check = facebook.check_session(request)
fb_user = facebook.users.getLoggedInUser()
try:
profile = FacebookUserProfile.objects.get(facebook_uid = fb_user)
return profile.user
except FacebookUserProfile.DoesNotExist:
fb_data = facebook.users.getInfo([fb_user], ['uid', 'first_name', 'last_name', 'pic_small', 'current_location'])
if not fb_data:
return None
fb_data = fb_data[0]
username = 'FB:%s' % fb_data['uid']
user_email = '%[email protected]%s.com'%(fb_data['first_name'], settings.SITE_NAME)
user = User.objects.create(username = username, email=user_email)
user.first_name = fb_data['first_name']
user.last_name = fb_data['last_name']
user.save()
location = str(fb_data['current_location'])
fb_profile = FacebookUserProfile(facebook_uid = fb_data['uid'], user = user, profile_image_url = fb_data['pic_small'], location=location)
fb_profile.save()
auth_meta = AuthMeta(user=user, provider='Facebook').save()
return user
except Exception, e:
print str(e)
示例7: desktop_app
def desktop_app():
from facebook import Facebook
# Get api_key and secret_key from a file
fbs = open(FB_SETTINGS).readlines()
facebook = Facebook(fbs[0].strip(), fbs[1].strip())
facebook.auth.createToken()
# Show login window
facebook.login()
# Login to the window, then press enter
print 'After logging in, press enter...'
raw_input()
facebook.auth.getSession()
info = facebook.users.getInfo([facebook.uid], ['name', 'birthday', 'affiliations', 'sex'])[0]
for attr in info:
print '%s: %s' % (attr, info[attr])
friends = facebook.friends.get()
friends = facebook.users.getInfo(friends[0:5], ['name', 'birthday', 'relationship_status'])
for friend in friends:
if 'birthday' in friend:
print friend['name'], 'has a birthday on', friend['birthday'], 'and is', friend['relationship_status']
else:
print friend['name'], 'has no birthday and is', friend['relationship_status']
arefriends = facebook.friends.areFriends([friends[0]['uid']], [friends[1]['uid']])
photos = facebook.photos.getAlbums(friends[1]['uid'])
print photos
示例8: authenticate
def authenticate(self, request):
"""
Started at
http://github.com/uswaretech/Django-Socialauth/blob/master/socialauth/auth_backends.py
Made massive improvements with error handling.
"""
facebook = Facebook(settings.FACEBOOK_API_KEY, settings.FACEBOOK_SECRET_KEY)
check = facebook.check_session(request)
clear_permissions(request) # for internal perms
try:
fb_user = facebook.users.getLoggedInUser()
fb_data = get_fb_data(facebook, fb_user)
profile = FacebookUserProfile.objects.get(facebook_uid = unicode(fb_user))
except FacebookUserProfile.DoesNotExist:
username = 'FB:%s' % fb_data['uid']
fb_user,new_user = User.objects.get_or_create(username = username)
fb_user.is_active = True
fb_user.first_name = fb_data['first_name']
fb_user.last_name = fb_data['last_name']
fb_user.email = fb_data['email']
fb_user.save()
try:
profile = FacebookUserProfile(facebook_uid= unicode(fb_data['uid']), user=fb_user)
profile.save()
auth_meta = AuthMeta(user=user, provider='Facebook').save()
except:
pass
except Exception, e:
return None
示例9: download_data
def download_data(api):
if api == '&VK':
vkapi = VK()
return vkapi.get_information_friends()
if api == '&Facebook':
fbapi = Facebook()
return fbapi.get_friends()
示例10: facebook_connect
def facebook_connect(request, template='socialregistration/facebook.html', extra_context=dict()):
"""
View to handle connecting existing accounts with facebook
"""
fb = Facebook(settings.FACEBOOK_API_KEY, settings.FACEBOOK_SECRET_KEY)
if not fb.check_session(request) \
or not request.user.is_authenticated():
extra_context.update(
dict(error=FB_ERROR)
)
return render_to_response(
template,
extra_context,
context_instance=RequestContext(request)
)
try:
profile = FacebookProfile.all().filter('uid=',fb.uid).fetch(1)[0]
except IndexError:
fb_profile = fb.users.getInfo(fb.uid, ['name','email','pic_square','username', ])[0]
profile = FacebookProfile(user=request.user,
uid=fb.uid,
username = fb_profile['username'],
real_name = fb_profile['name'],
email = fb_profile['email'],
pic_url = fb_profile['pic_square'],
)
profile.save()
return HttpResponseRedirect(_get_next(request))
示例11: app
def app():
from facebook import Facebook
#Get api key and secret key
facebook=Facebook(API_KEY, API_SECRET)
facebook.auth.createToken()
#Show login window
facebook.login()
#Log in to the window and then press enter
print "After you log in, press enter"
raw_input()
facebook.request_extended_permission('friends_birthday')
raw_input()
facebook.auth.getSession()
info = facebook.users.getInfo([facebook.uid], ['name', 'birthday'])[0]
print info
for attr in info:
print '%s: %s' % (attr, info[attr])
friends = facebook.friends.get()
friends = facebook.users.getInfo(friends[0:100], ['name', 'birthday'])
for friend in friends:
if friend['birthday'] is not None:
print friend['name'], 'has a birthday on', friend['birthday']
else:
print friend['name'], 'has no birthday'
示例12: post
def post(self):
fb = Facebook(settings.key.api, settings.key.secret)
logging.debug('Created Facebook instance')
# Checks to make s ure that the user is logged into Facebook.
if fb.check_session(self.request):
pass
else:
# If not redirect them to your application add page.
url = fb.get_add_url()
self.response.out.write('<fb:redirect url="' + url + '" />')
return
# Checks to make sure the user has added your application.
if fb.added:
pass
else:
# If not redirect them to your application add page.
url = fb.get_add_url()
self.response.out.write('<fb:redirect url="' + url + '" />')
return
greeting = Greeting()
greeting.uid = fb.uid
greeting.content = self.request.get('content')
greeting.put()
self.redirect('/')
示例13: connect
def connect(self, api_key, secret_key):
facebook = Facebook(api_key, secret_key)
facebook.auth.createToken()
facebook.login()
print "After logging in, press enter..."
raw_input()
facebook.auth.getSession()
示例14: refresh_data
def refresh_data(self):
"""Refresh this user's data using the Facebook Graph API"""
me = Facebook().api(u'/me',
{u'fields': u'picture,friends', u'access_token': self.access_token})
self.dirty = False
self.name = me[u'name']
self.email = me.get(u'email')
self.picture = me[u'picture']
self.friends = [user[u'id'] for user in me[u'friends'][u'data']]
return self.put()
示例15: facebook_init
def facebook_init():
facebook = Facebook(API_KEY, SECRET)
facebook.auth.createToken()
facebook.login()
print 'After logging in, press any key...'
raw_input()
facebook.auth.getSession()
return facebook