This article is a followup to my previous post, Facebook apps in Python and Pylons part 1. I'm going to talk a little more about what is interesting about Facebook apps and how they work in practice. At the end, I provide a little code sample and a convenience decorator to save you some hassle.
Why write a Facebook app?
Even if you are pretty familiar with using Facebook, you would be easily forgiven if you didn't fully understand what the capabilities of a Facebook application are, and how the flow works. Facebook applications essentially offer you:
- The ability to put your own content on a user's profile.
- The ability to update a user's news feed.
def require_login(f):
''' This decorator first checks to see
if the user is authenticated.
If not, it redirects them
in the appropriate fashion to the
log in page. If they are authenticated,
it sets up the PyFacebook Facebook
object and passes it down to our wrapped method. '''
def redirect(fb, url):
if fb.in_canvas:
log.info("doing fbml redirect 302")
return ' ' %(url, )
else:
log.info("sending a 302")
response.status_int = 302
response.headers['location'] = url
return 'Moved temporarily'
api_key = config['pyfacebook.apikey']
secret_key = config['pyfacebook.secret']
appid = config['pyfacebook.appid']
auth_token = request.params.get('auth_token', None)
fb = Facebook(api_key, secret_key, app_name='myapp',
callback_path='/myapp/callback',
auth_token=auth_token)
if not fb.check_session(request) or not auth_token:
log.info("got an unauthenticated session request")
return lambda a: redirect(fb, fb.get_login_url())
return lambda a: f(a, fb=fb)
class FacebookController(BaseController):
def index(self):
return 'Hello World'
@require_login
def post_add(self, fb=None):
fb.auth.getSession()
log.info("got a valid session from user %s", fb.uid)
fb.profile.setFBML(' ')
@require_login
def callback(self, fb=None):
c.uid = fb.uid
return render('/canvas.fbml')
Hopefully that is enough to get you started. I'll be writing more about this subject so stay tuned. If you have any specific questions, feel free to post a comment!
Niall O'Higgins is an author, event organizer and software consultant. He wrote the book MongoDB and Python, published by O'Reilly. Events he organizes include We Have Tablets, the #1 Bay Area Tablet Computing Meet-up and PyWebSF. He also offers consulting services for Mobile, Tablet and Cloud Computing.
