The Version 0.2.0 of pyfb has been released!. In the new version I have added a django application to show how you can integrate your web sites/applications with facebook using this library.
Let’s explain a few points of that application:
First at all, you need to register your application in facebook.
Then Facebook will provide you and aplication ID and a secret authentication key. You should put this data in the settings.py inside your django application.
Beside that you must define a redirect url, which is the url that Facebook will use to redirect the user’s browser when the authentication was completed.
# Facebook related Settings FACEBOOK_APP_ID = 'YOUR_APP_ID' FACEBOOK_SECRET_KEY = 'YOUR_APP_SECRET_CODE' FACEBOOK_REDIRECT_URL = 'http://www.YOUR_DOMAIN.com/facebook_login_success'
Ok, thats right. Now look the interesting part of this. Take a look at views.py file. It should look like this:
from pyfb import Pyfb from django.http import HttpResponse, HttpResponseRedirect from settings import FACEBOOK_APP_ID, FACEBOOK_SECRET_KEY, FACEBOOK_REDIRECT_URL def index(request): return HttpResponse("""<button onclick="location.href='/facebook_login'">Facebook Login</button>""") #This view redirects the user to facebook in order to get the code that allows #pyfb to obtain the access_token in the facebook_login_success view def facebook_login(request): facebook = Pyfb(FACEBOOK_APP_ID) return HttpResponseRedirect(facebook.get_auth_code_url(redirect_uri=FACEBOOK_REDIRECT_URL)) #This view must be refered in your FACEBOOK_REDIRECT_URL. For example: http://www.mywebsite.com/facebook_login_success/ def facebook_login_success(request): code = request.GET.get('code') facebook = Pyfb(FACEBOOK_APP_ID) facebook.get_access_token(FACEBOOK_SECRET_KEY, code, redirect_uri=FACEBOOK_REDIRECT_URL) me = facebook.get_myself() welcome = "Welcome <b>%s</b>. Your Facebook login has been completed successfully!" return HttpResponse(welcome % me.name)
Pretty simple. Isn’t it?. The first view, facebook_login will redirect the user’s browser to the facebook page asking for authentication.
When that process was completed, the browser will be redirected to the url that you have specified in the settings.py. Obviously, that url must refer to
Finally, you can get the access token and then request all information as you want (and Facebook provides) about the user.
The last step is just configuration. You need to map the urls to the correspondent view in the urls.py file:
urlpatterns = patterns('', (r'^$', 'djangoapp.django_pyfb.views.index'), (r'^facebook_login/$', 'djangoapp.django_pyfb.views.facebook_login'), (r'^facebook_login_success/$', 'djangoapp.django_pyfb.views.facebook_login_success'), )
You can download and install pyfb from pypi and get the complete source code of this example application:
sudo pip install pyfb
Hope this was usefull and explanatory for you.