Archive for the 'Web Development' Category

Django Facebook 3.0 – OAuth migration – Time to upgrade!

Facebook is migrating to HTTPS and OAuth to increase the safety of their users. Unfortunately these changes aren’t backwards compatible and will require some effort to follow. To support the new Facebook system you need to upgrade to Django Facebook 3.0 before October 1st.

In addition to the required migrations, this version also includes several new features. The largest change is the underlying Facebook API client. You can read about the improvements here or skip down to the upgrade instructions.

Open Facebook – New Python Facebook client

Open Facebook is a python client to the Facebook graph API. Currently it’s included in Django Facebook, but in time it will be spun of as a separate project. The client is supported, tested and up to date with the current version of Facebook’s graph API.
It handles connection issues cleanly and raises separate error classes for various Facebook error scenarios.
The syntax is very straightforward to use:

open_facebook = OpenFacebook(token)
#info about me
open_facebook.me()

#retrieving a page
open_facebook.get('fashiolista')

#retrieving your albums
open_facebook.get('me/albums')

#posting a message on your wall
open_facebook.set('me/feed', message='Check out Fashiolista', picture=image_url)

#setting a like
open_facebook.set('fashiolista/likes')

#fql example
result = open_facebook.fql('SELECT name FROM user WHERE uid = me()')

#authorization is handled separately from the API class
token = FacebookAuthorization.get_app_access_token()
test_user = FacebookAuthorization.create_test_user(token)

Album upload Example

Uploading pictures to Facebook is as simple as this:

open_facebook = get_facebook_graph(request)
photo_urls = [
    'http://d.fashiocdn.com/images/entities/0/6/t/p/d/0.365x365.jpg',
    'http://e.fashiocdn.com/images/entities/0/5/E/b/Q/0.365x365.jpg',
]
for photo in photo_urls:
    uploaded = open_facebook.set('me/photos', url=photo,
        message='Fashiolista is awesome', name='FashiolistaTest'
    )

So there are good reasons to upgrade even if Facebook didn’t force us to :)

How to upgrade to 3.0

First Step – Install Django Facebook 3.0
Follow the installation instructions.

Javascript changes
In your Facebook initialization code enable OAuth.

FB.init({appId: facebookAppId, status: false, cookie: true, xfbml: true, oauth: true});

Perms has been renamed to scope.

FB.login(function() {}, {'scope' : 'offline_access'});

Django Facebook changes
The get_facebook_graph function is no longer persistent by default, if you want the old behavior use get_persistent_graph.
Furthermore the FacebookUserConverter class and the core Facebook API client are now separated. get_facebook_graph returns the core facebook API client. To go from the API class to the user converter class use something like

graph = get_facebook_graph(request)
facebook = FacebookUserConverter(graph)

That should be all.
If you are encountering problems feel free to let me know in the comments.

Last Step – Enable the new Facebook Migrations
Go to the Facebook Apps page and enable the OAuth migration.
Select your app -> About -> Advanced -> Migrations
Enable Force OAuth
Enable OAuth Migration

Background reading

Moving to OAuth 2.0 + HTTPS
Updated JavaScript SDK and OAuth 2.0 Roadmap
New Facebook Authentication Docs
PHP SDK v.3.1.1
PHP SDK v3.0.0

We’re hiring!

Do you also see the beauty in clean code? Are you experienced with high scalability web apps? Currently we’re looking for additional talent over at our Amsterdam office. Feel free to drop me a line at my personal email for more information: thierryschellenbach[at]gmail.com

Django & Facebook & Fashiolista & Javascript & Python & Web Development tschellenbach 13 Aug 2011 18 Comments

Django Facebook 2.0 – Integrating Facebook

It’s been a year since Facebook changed the web with the open graph API and their like button. Unfortunately Facebook didn’t have much developer love for the python/django platform. Django Facebook aims to make it easy to build facebook apps and integrate facebook with your website.

Key functionality

One of the strong points of Django Facebook is the ability to register users using Facebook. It ports all of Facebook’s user data to the Django user and profile models. This allows you to have a secure register/connect/login flow using Facebook, greatly reducing the barriers to start using your application. Below an example of me registering for Fashiolista using the Facebook register flow.

Me on Facebook

Me on Fashiolista

In this blog post I will explain how to get started implementing a Facebook connect flow. Django Facebook can however do quite a bit more, as you can see in the feature list below. Development over at the github repo is very active. I strongly appreciate help on improving the functionality so please fork and contribute.

Features

  • Register users using the Facebook open graph API
    • Full profile data birthday, gender, website, about me, username, email and picture
    • Support for mobile authentication
    • Fallback to registration form for entering additional data when required
  • Build Facebook Canvas applications
  • Mobile registration using Facebook
  • Execute Facebook FQL queries
  • Upload pictures to Facebook
  • Find your Facebook friends

Getting Started

Now let’s get started with building a Facebook login/connect/register flow. This post will guide you through it step by step.

Prerequisites

Create a Facebook app

Have django registration installed (other registration systems will require some small code changes)

pip install django_facebook :)

A.) Settings and more

Define these settings in your settings file.
FACEBOOK_API_KEY
FACEBOOK_APP_ID
FACEBOOK_APP_SECRET

add django facebook to your installed apps
‘django_facebook’,
add this line to your url config
(r’^facebook/’, include(‘django_facebook.urls’)),
add this line to your context processors
‘django_facebook.context_processors.facebook’,
add this to your AUTHENTICATION_BACKENDS
‘django_facebook.auth_backends.FacebookBackend’,

B.) Adjust your user Profile model

Secondly we need to be able to store the Facebook data on your user profile.
The easiest way to do this is to add the abstract model in django_facebook/models.py called FacebookProfileModel to your profile model.
After your profile is ready to store Facebook data you should have a working example at /facebook/connect/.
Let me know in the comments if something went wrong up to this point :)

C.) Design and integration

You can style the facebook form and button anyway you see fit. Over at Fashiolista we added a nice facepile for example. The basic markup is located in the example file connect.html.
We use the facebook javascript SDK for a smooth user integration. You can load the facebook JS like this:

<script src="{{ MEDIA_URL }}js/original/facebook.js" type="text/javascript"></script>
<script>
facebookAppId = '{{ FACEBOOK_APP_ID }}';
function facebookJSLoaded(){
FB.init({appId: facebookAppId, status: false, cookie: true, xfbml: true});
}
window.fbAsyncInit = facebookJSLoaded;
F = new facebookClass(facebookAppId);
F.load();
</script>

Subsequently implement a form which calls Facebook via javascript. Note that you can control which page to go to after connect using the next input field.

<form action="{% url facebook_connect %}?facebook_login=1" method="post">
<a href="javascript:void(0);" style="font-size: 20px;" onclick="F.connect(this.parentNode);">Register, login or connect with facebook</a>
<input type="hidden" value="{{ request.path }}" name="next" />
</form>
<div id="fb-root"></div>

That was all, you should now have a working registration flow using Facebook. Let me know in the comments if you encounter any difficulties.
If you want to go one step further and understand the facebook API, you can find the Facebook documentation here.
Django Facebook received tons of improvements from the python community. I’m certainly missing a few authors, but I would like to thank a few specifically:

Many thanks to (amongst many others)

More posts coming up

  • Building a facebook canvas app using Django Facebook
  • Find and invite friends using Django Facebook

We’re hiring!

Do you also see the beauty in clean code? Are you experienced with high scalability web apps? Currently we’re looking for additional talent over at our Amsterdam office. Feel free to drop me a line at my personal email for more information: thierryschellenbach[at]gmail.com

Css & Django & Events & Facebook & Fashiolista & Prototype & Python & Web Development tschellenbach 23 Jun 2011 70 Comments

Mock Django Request for testing

When testing your applications I sometimes find myself needing to mock a request object. Unfortunately it is quite hard to find a good fake request factory which mimics a normal request.

Django has a class included for this purpose called RequestFactory. However it doesn’t fake the session object, breaking most of my test code. To fix this I wrote a tiny snippet implementing the RequestFactory with session and user support. Hope it helps :)

from django.core.handlers.base import BaseHandler
from django.test.client import RequestFactory

class RequestMock(RequestFactory):
    def request(self, **request):
        "Construct a generic request object."
        request = RequestFactory.request(self, **request)
        handler = BaseHandler()
        handler.load_middleware()
        for middleware_method in handler._request_middleware:
            if middleware_method(request):
                raise Exception("Couldn't create request mock object - "
                                "request middleware returned a response")
        return request

See the gist here.

Django & Fashiolista & Web Development tschellenbach 18 Apr 2011 17 Comments

Fashiolista raises $500,000 from Atomico :)

Some good news while new code is compiling :)
Champagne moment over here!

TechCrunch – Fashiolista raises funding from Skype founders

Business & Fashiolista & Web Development tschellenbach 12 Jan 2011 99 Comments

Twitter button to pull down the internet?

I was thrilled to see twitter releasing their own button. This is good news all around for us bloggers looking to promote our content. After looking at their code snippets a warning is in place though. The current twitter button implementation will severely break your site if their servers face load issues. Fortunately you can work around this issues by slightly modifying their implementation.

Technical explanation

For Fashiolista.com we have been writing a lot about the various techniques for implementing these type of buttons. Especially important here is the way the javascript is loaded. Twitter uses a simple blocking script approach, where as digg, facebook and fashiolista use the async dynamic script approach. There are two large differences:

  1. Blocking script loads make your site slower
  2. If twitter goes down, your site joins in

Example

In this example we are faking slow twitter servers. (By routing it through google’s app engine and delaying the response). You can see the difference for yourself (be patient and be sure to clear your browser cache using CTRL F5).

Default twitter version
(note that site content is not loading until the twitter button is loaded)

Async twitter script
(everything loads and then we wait for twitter)

Solution

Solving this is quite simple. Simply change the way the twitter javascript is loaded from the first example to the second version.

Twitter version


<script type="text/javascript" src="http://platform.twitter.com/widgets.js"></script>

Async twitter implementation

<script type="text/javascript">
  //async script, twitter button fashiolista.com style
  (function() {
   var s = document.createElement('SCRIPT');
   var c = document.getElementsByTagName('script')[0];
   s.type = 'text/javascript';
   s.async = true;
   s.src = 'http://platform.twitter.com/widgets.js';
   c.parentNode.insertBefore(s, c);
  })();
</script>

Hope the difference won’t matter and Twitter will stay up :)

Follow me at:
@tschellenbach

Thanks for spreading the word:
NextWeb

Business & Fashiolista & Google app engine & Javascript & Web Development & YouTellMe tschellenbach 13 Aug 2010 80 Comments

Django open inviter – contact importer – python

Django open inviter is a python port of the PHP api client for openinviter.com’s contact importer to work with Django. I build it for our fashion community, Fashiolista.com, where it is currently in production usage and fully functional. If you are a member of Fashiolista (which I highly doubt given the different audiences) you can test it by clicking find friends in your profile.

Usage is extremly straight forward:

from django_open_inviter.open_inviter import OpenInviter
o = OpenInviter()
contacts = o.contacts('example@example.com', 'test')

Get the code here.

Django & Fashiolista & PHP & Python & Web Development & YouTellMe tschellenbach 09 Aug 2010 15 Comments

« Previous PageNext Page »