Preload social account data in your views
This is useful if you need to display data retrieved from the service’s
API in your views, for example if you want to display the username and
profile picture of the current user in the service.
First you need to set the fields that will be retrieved from the service
and stored in a cookie (cookies are used to avoid the data not to be
updated if the user updates its profile in the service, cookies are by
default set to live for 15 minutes before a new requests to the
service’s API is made).
# my_project/settings.py
SOCIALNETWORKS_CONFIGURATION = {
...
...
'FACEBOOK': {
'APP_ID': 'my-facebook-app-id',
'APP_SECRET': 'my-facebook-app-secret',
'SCOPE': ['first_name', 'last_name', 'username'],
'SESSION_FIELDS': ['username', 'picture.type(normal)']
},
...
...
}
Note that since these methods make requests to the service’s APIs is
highly probably that the applied views results in slower rendering or
timeout errors.
# my_project/views.py
from socialnetworks.facebook.decorators import fetch_facebook_data
from socialnetworks.facebook.utils import read_facebook_data
class MyDecoratedView(TemplateView):
def get_context_data(self, **kwargs):
context = super(MyDecoratedView, self).get_context_data(**kwargs)
# Read the social data previously stored in a cookie and makes it
# available in the view's context.
context['facebook_data'] = read_facebook_data(self.request)
return context
# Prefetch the social data for the current authenticated user and store it
# in a cookie.
@method_decorator(fetch_facebook_data)
def dispatch(self, request, *args, **kwargs):
return super(MyDecoratedView, self).dispatch(request, *args, **kwargs)
Then render the retrieved data in the view’s template.
...
...
<span>{{ facebook_data.username }}</span>
<img src="{{ facebook_data.picture.data.url }}" />
...
...
Making requests to the service’s APIs
First you need to initialize a client, then call the proper get or
post method for the action you want to make passing the resource and
the parameters or the data tu retrive/put.
Nothe that this is a work in progress, GET requests should work ok,
but POST must have some caveats depending on the service.*
from socialnetwork.facebook.clients import FacebookClient
client = Facebook.client(user.facebookoauthprofile)
# Retrieve data
data = client.get('me', params={'fields': 'first_name', 'last_name'})
print data
>>> {'first_name': 'John', 'last_name': 'Smith'}
# Post data
client.post('me', data={'first_name': 'Juan'})
data = client.get('me', params={'fields': 'first_name', 'last_name'})
print data
>>> {'first_name': 'Juan', 'last_name': 'Smith'}