本文整理汇总了Python中django_facebook.api.FacebookUserConverter类的典型用法代码示例。如果您正苦于以下问题:Python FacebookUserConverter类的具体用法?Python FacebookUserConverter怎么用?Python FacebookUserConverter使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了FacebookUserConverter类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: build_graph_view
def build_graph_view(request, graph):
if graph:
try:
graph.is_authenticated()
except:
update_connection(request,graph)
user = FacebookUserConverter(graph)
friends = user.get_friends()
friend_requests = [
u'me/mutualfriends/{0}'.format(friend['id'])
for friend in friends
]
mutual_friends = []
batch_size = 50
batches = defaultdict(list)
for i,friend_request in enumerate(friend_requests):
batch_request = {
'method': 'GET','relative_url':friend_request
}
batches[i/batch_size].append(batch_request)
counter = 0
for batch in batches.values():
batch = json.dumps(batch)
responses = graph.request(
"", post_data = {'batch':batch}, fields='id'
)
mutual_friends += responses
print counter, 'success'
counter += 1
print len(mutual_friends)
json_data = process_fb_response(friends, mutual_friends, graph)
else:
return HttpResponse('Error')
return HttpResponse(json_data, mimetype='text/javascript')
示例2: connect_user
def connect_user(self):
"""Main functionality
"""
#TODO, instead of using access_token this should probably accept a facebook_graph as well
user = None
facebook = self.facebook_graph or get_facebook_graph(self.request, self.access_token)
assert facebook.is_authenticated(), 'Facebook not authenticated'
facebook_user_converter = FacebookUserConverter(facebook)
facebook_data = facebook_user_converter.facebook_profile_data()
force_registration = self.request.REQUEST.get('force_registration') or self.request.REQUEST.get('force_registration_hard')
logger.debug('force registration is set to %s', force_registration)
if self.request.user.is_authenticated() and not force_registration:
action = CONNECT_ACTIONS.CONNECT
user = self._connect_user(facebook)
else:
email = facebook_data.get('email', False)
email_verified = facebook_data.get('verified', False)
kwargs = {}
if email and email_verified:
kwargs = {'facebook_email': email}
authenticated_user = authenticate(facebook_id=facebook_data['id'], **kwargs)
if authenticated_user and not force_registration:
action = CONNECT_ACTIONS.LOGIN
## Has the user registered without Facebook, using the verified FB email address?
# It is after all quite common to use email addresses for usernames
if not authenticated_user.get_profile().facebook_id:
update = True
else:
update = getattr(authenticated_user, 'fb_update_required', False)
user = self._login_user(facebook, authenticated_user, update=update)
else:
action = CONNECT_ACTIONS.REGISTER
user = self._register_user(facebook)
#store likes and friends if configured
sid = transaction.savepoint()
try:
if facebook_settings.FACEBOOK_STORE_LIKES:
likes = facebook.get_likes()
facebook.store_likes(user, likes)
if facebook_settings.FACEBOOK_STORE_FRIENDS:
friends = facebook.get_friends()
facebook.store_friends(user, friends)
transaction.savepoint_commit(sid)
except IntegrityError, e:
logger.warn(u'Integrity error encountered during registration, probably a double submission %s' % e,
exc_info=sys.exc_info(), extra={
'request': request,
'data': {
'body': unicode(e),
}
})
transaction.savepoint_rollback(sid)
示例3: test_check_connect_facebook
def test_check_connect_facebook(self):
graph = get_facebook_graph(access_token='new_user')
facebook = FacebookUserConverter(graph)
data = facebook.facebook_registration_data()
self.assertEqual(data['gender'], 'm')
response = self.client.get(reverse('login:index'))
示例4: _connect
def _connect(request, facebook_login):
'''
Handles the view logic around connect user
- (if authenticated) connect the user
- login
- register
'''
backend = get_registration_backend()
context = RequestContext(request)
if facebook_login:
logger.info('trying to connect using Facebook')
graph = require_persistent_graph(request)
authenticated = False
if graph:
logger.info('found a graph object')
facebook = FacebookUserConverter(graph)
authenticated = facebook.is_authenticated()
if authenticated:
logger.info('Facebook is authenticated')
facebook_data = facebook.facebook_profile_data()
#either, login register or connect the user
try:
action, user = connect_user(request)
logger.info('Django facebook performed action: %s', action)
except facebook_exceptions.IncompleteProfileError, e:
#show them a registration form to add additional data
warning_format = u'Incomplete profile data encountered with error %s'
warn_message = warning_format % e.message
send_warning(warn_message, e=e,
facebook_data=facebook_data)
context['facebook_mode'] = True
context['form'] = e.form
return render_to_response(
facebook_settings.FACEBOOK_REGISTRATION_TEMPLATE,
context_instance=context,
)
except facebook_exceptions.AlreadyConnectedError, e:
user_ids = [u.id for u in e.users]
ids_string = ','.join(map(str, user_ids))
return error_next_redirect(
request,
additional_params=dict(already_connected=ids_string))
if action is CONNECT_ACTIONS.CONNECT:
#connect means an existing account was attached to facebook
messages.info(request, _("You have connected your account "
"to %s's facebook profile") % facebook_data['name'])
elif action is CONNECT_ACTIONS.REGISTER:
#hook for tying in specific post registration functionality
response = backend.post_registration_redirect(
request, user)
#compatibility for Django registration backends which return redirect tuples instead of a response
if not isinstance(response, HttpResponse):
to, args, kwargs = response
response = redirect(to, *args, **kwargs)
return response
示例5: connect_user
def connect_user(request, access_token=None, facebook_graph=None):
'''
Given a request either
- (if authenticated) connect the user
- login
- register
'''
user = None
graph = facebook_graph or get_facebook_graph(request, access_token)
facebook = FacebookUserConverter(graph)
assert facebook.is_authenticated()
facebook_data = facebook.facebook_profile_data()
force_registration = request.REQUEST.get('force_registration') or\
request.REQUEST.get('force_registration_hard')
connect_facebook = to_bool(request.REQUEST.get('connect_facebook'))
logger.debug('force registration is set to %s', force_registration)
if connect_facebook and request.user.is_authenticated() and not force_registration:
#we should only allow connect if users indicate they really want to connect
#only when the request.CONNECT_FACEBOOK = 1
#if this isn't present we just do a login
action = CONNECT_ACTIONS.CONNECT
user = _connect_user(request, facebook)
else:
email = facebook_data.get('email', False)
email_verified = facebook_data.get('verified', False)
kwargs = {}
if email and email_verified:
kwargs = {'facebook_email': email}
auth_user = authenticate(facebook_id=facebook_data['id'], **kwargs)
if auth_user and not force_registration:
action = CONNECT_ACTIONS.LOGIN
# Has the user registered without Facebook, using the verified FB
# email address?
# It is after all quite common to use email addresses for usernames
update = getattr(auth_user, 'fb_update_required', False)
if not auth_user.get_profile().facebook_id:
update = True
#login the user
user = _login_user(request, facebook, auth_user, update=update)
else:
action = CONNECT_ACTIONS.REGISTER
# when force registration is active we should remove the old profile
try:
user = _register_user(request, facebook,
remove_old_connections=force_registration)
except facebook_exceptions.AlreadyRegistered, e:
#in Multithreaded environments it's possible someone beats us to
#the punch, in that case just login
logger.info('parallel register encountered, slower thread is doing a login')
auth_user = authenticate(
facebook_id=facebook_data['id'], **kwargs)
action = CONNECT_ACTIONS.LOGIN
user = _login_user(request, facebook, auth_user, update=False)
示例6: connect
def connect(request):
'''
Handles the view logic around connect user
- (if authenticated) connect the user
- login
- register
'''
backend = get_registration_backend()
context = RequestContext(request)
assert context.get('FACEBOOK_APP_ID'), 'Please specify a facebook app id '\
'and ensure the context processor is enabled'
facebook_login = bool(int(request.REQUEST.get('facebook_login', 0)))
if facebook_login:
logger.info('trying to connect using facebook')
graph = require_persistent_graph(request)
if graph:
logger.info('found a graph object')
facebook = FacebookUserConverter(graph)
if facebook.is_authenticated():
logger.info('facebook is authenticated')
facebook_data = facebook.facebook_profile_data()
#either, login register or connect the user
try:
action, user = connect_user(request)
logger.info('Django facebook performed action: %s', action)
except facebook_exceptions.IncompleteProfileError, e:
#show them a registration form to add additional data
warning_format = u'Incomplete profile data encountered with error %s'
warn_message = warning_format % e.message
send_warning(warn_message, e=e,
facebook_data=facebook_data)
context['facebook_mode'] = True
context['form'] = e.form
return render_to_response(
facebook_settings.FACEBOOK_REGISTRATION_TEMPLATE,
context_instance=context,
)
except facebook_exceptions.AlreadyConnectedError, e:
user_ids = [u.id for u in e.users]
ids_string = ','.join(map(str, user_ids))
return next_redirect(request, next_key=['error_next', 'next'],
additional_params=dict(already_connected=ids_string))
if action is CONNECT_ACTIONS.CONNECT:
#connect means an existing account was attached to facebook
messages.info(request, _("You have connected your account "
"to %s's facebook profile") % facebook_data['name'])
elif action is CONNECT_ACTIONS.REGISTER:
#hook for tying in specific post registration functionality
response = backend.post_registration_redirect(request, user)
#compatability for django registration backends which return tuples instead of a response
#alternatively we could wrap django registration backends, but that would be hard to understand
response = response if isinstance(response, HttpResponse) else redirect(response)
return response
示例7: connect
def connect(request):
'''
Handles the view logic around connect user
- (if authenticated) connect the user
- login
- register
'''
backend = get_registration_backend()
context = RequestContext(request)
assert context.get('FACEBOOK_APP_ID'), 'Please specify a facebook app id '\
'and ensure the context processor is enabled'
facebook_login = bool(int(request.REQUEST.get('facebook_login', 0)))
if facebook_login:
require_persistent_graph(request)
logger.info('trying to connect using facebook')
graph = get_persistent_graph(request)
if graph:
logger.info('found a graph object')
facebook = FacebookUserConverter(graph)
if facebook.is_authenticated():
logger.info('facebook is authenticated')
facebook_data = facebook.facebook_profile_data()
#either, login register or connect the user
try:
action, user = connect_user(request)
logger.info('Django facebook performed action: %s', action)
except facebook_exceptions.IncompleteProfileError, e:
warn_message = u'Incomplete profile data encountered '\
u'with error %s' % e.message.decode('utf-8', 'replace')
send_warning(warn_message, e=e,
facebook_data=facebook_data)
context['facebook_mode'] = True
context['form'] = e.form
return render_to_response(
facebook_settings.FACEBOOK_REGISTRATION_TEMPLATE,
context_instance=context,
)
if action is CONNECT_ACTIONS.CONNECT:
messages.info(request, _("You have connected your account "
"to %s's facebook profile") % facebook_data['name'])
elif action is CONNECT_ACTIONS.REGISTER:
response = backend.post_registration_redirect(request, user)
return response
else:
if 'attempt' in request.GET:
return next_redirect(request, next_key=['error_next', 'next'],
additional_params=dict(fb_error_or_cancel=1))
else:
logger.info('Facebook authentication needed for connect, ' \
'raising an error')
raise OpenFacebookException('please authenticate')
return next_redirect(request)
示例8: test_open_facebook
def test_open_facebook(request):
from django_facebook.api import FacebookUserConverter
fb = get_persistent_graph(request)
instace = FacebookUserConverter(fb)
# Get Friends
return HttpResponse(instace.get_friends())
示例9: connect
def connect(request):
'''
Handles the view logic around connect user
- (if authenticated) connect the user
- login
- register
'''
#test code time to remove
uri = 'http://%s%s?facebook_login=1' % (request.META['HTTP_HOST'],
request.path)
if request.GET.get('redirect'):
return facebook_login_required(uri, scope='read_stream')
context = RequestContext(request)
assert context.get('FACEBOOK_APP_ID'), 'Please specify a facebook app id '\
'and ensure the context processor is enabled'
facebook_login = bool(int(request.REQUEST.get('facebook_login', 0)))
if facebook_login:
graph = get_facebook_graph(request)
if graph:
facebook = FacebookUserConverter(graph)
if facebook.is_authenticated():
facebook_data = facebook.facebook_profile_data()
#either, login register or connect the user
try:
action, user = connect_user(request)
except facebook_exceptions.IncompleteProfileError, e:
warn_message = u'Incomplete profile data encountered '\
'with error %s' % e
logger.warn(warn_message,
exc_info=sys.exc_info(), extra={
'request': request,
'data': {
'username': request.user.username,
'facebook_data': facebook.facebook_profile_data(),
'body': unicode(e),
}
})
context['facebook_mode'] = True
context['form'] = e.form
return render_to_response(
'registration/registration_form.html',
context_instance=context,
)
if action is CONNECT_ACTIONS.CONNECT:
messages.info(request, _("You have connected your account "
"to %s's facebook profile") % facebook_data['name'])
elif action is CONNECT_ACTIONS.REGISTER:
return user.get_profile().post_facebook_registration(request)
else:
return next_redirect(request, next_key=['error_next', 'next'],
additional_params=dict(fb_error_or_cancel=1))
return next_redirect(request)
示例10: connect_user
def connect_user(request, access_token=None, facebook_graph=None):
'''
Given a request either
- (if authenticated) connect the user
- login
- register
'''
user = None
graph = facebook_graph or get_facebook_graph(request, access_token)
facebook = FacebookUserConverter(graph)
assert facebook.is_authenticated()
facebook_data = facebook.facebook_profile_data()
force_registration = request.REQUEST.get('force_registration') or\
request.REQUEST.get('force_registration_hard')
connect_facebook = bool(int(request.REQUEST.get('connect_facebook', 0)))
logger.debug('force registration is set to %s', force_registration)
if connect_facebook and request.user.is_authenticated() and not force_registration:
#we should only allow connect if users indicate they really want to connect
#only when the request.CONNECT_FACEBOOK = 1
#if this isn't present we just do a login
action = CONNECT_ACTIONS.CONNECT
user = _connect_user(request, facebook)
else:
email = facebook_data.get('email', False)
email_verified = facebook_data.get('verified', False)
kwargs = {}
if email and email_verified:
kwargs = {'facebook_email': email}
auth_user = authenticate(facebook_id=facebook_data['id'], **kwargs)
if auth_user and not force_registration:
action = CONNECT_ACTIONS.LOGIN
# Has the user registered without Facebook, using the verified FB
# email address?
# It is after all quite common to use email addresses for usernames
if not auth_user.get_profile().facebook_id:
update = True
else:
update = getattr(auth_user, 'fb_update_required', False)
user = _login_user(request, facebook, auth_user, update=update)
else:
action = CONNECT_ACTIONS.REGISTER
# when force registration is active we should clearout
# the old profile
user = _register_user(request, facebook,
remove_old_connections=force_registration)
_update_likes_and_friends(request, user, facebook)
_update_access_token(user, graph)
return action, user
示例11: retrieve_friends
def retrieve_friends(request, field='uid'):
try:
open_graph = get_persistent_graph(request)
converter = FacebookUserConverter(open_graph)
friends = converter.get_friends()
friends_data = [u[field] for u in friends]
return friends_data
except Exception as e:
return []
print e
示例12: retrieve_friends_dict
def retrieve_friends_dict(request):
try:
open_graph = get_persistent_graph(request)
converter = FacebookUserConverter(open_graph)
friends = converter.get_friends()
friends_data = {u['name'].strip().upper(): u['uid'] for u in friends}
return friends_data
except Exception as e:
return {}
print e
示例13: connect
def connect(request):
"""
Handles the view logic around connect user
- (if authenticated) connect the user
- login
- register
"""
context = RequestContext(request)
assert context.get("FACEBOOK_APP_ID"), (
"Please specify a facebook app id " "and ensure the context processor is enabled"
)
facebook_login = bool(int(request.REQUEST.get("facebook_login", 0)))
if facebook_login:
# code to redirect if we don't have adequate permissions
from django_facebook.utils import test_permissions
scope_list = facebook_settings.FACEBOOK_DEFAULT_SCOPE
# standardizing the url to prevent things like attempt from being included
redirect_uri = request.build_absolute_uri(request.path) + "?facebook_login=1"
oauth_url, redirect_uri = get_oauth_url(request, scope_list, redirect_uri=redirect_uri)
if not test_permissions(request, scope_list, redirect_uri):
return HttpResponseRedirect(oauth_url)
graph = get_persistent_graph(request)
if graph:
facebook = FacebookUserConverter(graph)
if facebook.is_authenticated():
facebook_data = facebook.facebook_profile_data()
# either, login register or connect the user
try:
action, user = connect_user(request)
logger.info("Django facebook, action was %s", action)
except facebook_exceptions.IncompleteProfileError, e:
warn_message = u"Incomplete profile data encountered " u"with error %s" % e
send_warning(warn_message, e=e, facebook_data=facebook.facebook_profile_data())
context["facebook_mode"] = True
context["form"] = e.form
return render_to_response(
facebook_settings.FACEBOOK_REGISTRATION_TEMPLATE, context_instance=context
)
if action is CONNECT_ACTIONS.CONNECT:
messages.info(
request,
_("You have connected your account " "to %s's facebook profile") % facebook_data["name"],
)
elif action is CONNECT_ACTIONS.REGISTER:
return user.get_profile().post_facebook_registration(request)
else:
return next_redirect(request, next_key=["error_next", "next"], additional_params=dict(fb_error_or_cancel=1))
return next_redirect(request)
示例14: connect_user
def connect_user(request, access_token=None, facebook_graph=None):
"""
Given a request either
- (if authenticated) connect the user
- login
- register
"""
user = None
graph = facebook_graph or get_facebook_graph(request, access_token)
facebook = FacebookUserConverter(graph)
assert facebook.is_authenticated()
facebook_data = facebook.facebook_profile_data()
force_registration = request.REQUEST.get("force_registration") or request.REQUEST.get("force_registration_hard")
logger.debug("force registration is set to %s", force_registration)
if request.user.is_authenticated() and not force_registration:
action = CONNECT_ACTIONS.CONNECT
user = _connect_user(request, facebook)
else:
email = facebook_data.get("email", False)
email_verified = facebook_data.get("verified", False)
kwargs = {}
if email and email_verified:
kwargs = {"facebook_email": email}
auth_user = authenticate(facebook_id=facebook_data["id"], **kwargs)
if auth_user and not force_registration:
action = CONNECT_ACTIONS.LOGIN
# Has the user registered without Facebook, using the verified FB
# email address?
# It is after all quite common to use email addresses for usernames
if not auth_user.get_profile().facebook_id:
update = True
else:
update = getattr(auth_user, "fb_update_required", False)
user = _login_user(request, facebook, auth_user, update=update)
else:
action = CONNECT_ACTIONS.REGISTER
user = _register_user(request, facebook)
# store likes and friends if configured
sid = transaction.savepoint()
try:
if facebook_settings.FACEBOOK_STORE_LIKES:
likes = facebook.get_likes()
facebook.store_likes(user, likes)
if facebook_settings.FACEBOOK_STORE_FRIENDS:
friends = facebook.get_friends()
facebook.store_friends(user, friends)
transaction.savepoint_commit(sid)
except IntegrityError, e:
logger.warn(
u"Integrity error encountered during registration, " "probably a double submission %s" % e,
exc_info=sys.exc_info(),
extra={"request": request, "data": {"body": unicode(e)}},
)
transaction.savepoint_rollback(sid)
示例15: test_gender_matching
def test_gender_matching(self):
request = RequestMock().get('/')
request.session = {}
request.user = AnonymousUser()
graph = get_persistent_graph(request, access_token='paul')
converter = FacebookUserConverter(graph)
base_data = converter.facebook_profile_data()
self.assertEqual(base_data['gender'], 'male')
data = converter.facebook_registration_data()
self.assertEqual(data['gender'], 'm')
action, user = connect_user(self.request, facebook_graph=graph)
self.assertEqual(user.get_profile().gender, 'm')