我的公司已经构建了一个库,可以将 Facebook 集成到您的 Django 应用程序中变得非常简单(我们可能已经使用该库构建了 10-20 个应用程序,其中一些应用程序具有大量流量,因此它已经过实战测试)。
pip install ecl-facebook==1.2.7
在您的设置中,为您的 FACEBOOK_KEY、FACEBOOK_SECRET、FACEBOOK_SCOPE、FACEBOOK_REDIRECT_URL 和 PRIMARY_USER_MODEL 添加值。您还需要将ecl_facebook.backends.FacebookAuthBackend 添加到您的AUTHENTICATION_BACKENDS。例如,在 settings.py 中:
# These aren't actual keys, you'll have to replace them with your own :)
FACEBOOK_KEY = "256064624431781"
FACEBOOK_SECRET = "4925935cb93e3446eff851ddaf5fad07"
FACEBOOK_REDIRECT_URL = "http://example.com/oauth/complete"
FACEBOOK_SCOPE = "email"
# The user model where the Facebook credentials will be stored
PRIMARY_USER_MODEL = "app.User"
AUTHENTICATION_BACKENDS = (
# ...
'ecl_facebook.backends.FacebookAuthBackend',
)
在您的 views.py 中添加一些视图来处理身份验证前和身份验证后的逻辑。
from django.contrib.auth import authenticate, login
from django.http import HttpResponseRedirect
from ecl_facebook.django_decorators import facebook_begin, facebook_callback
from ecl_facebook import Facebook
from .models import User
# ...
@facebook_begin
def oauth_facebook_begin(request):
# Anything you want to do before sending the user off to Facebook
# for authorization can be done here.
pass
@facebook_callback
def oauth_facebook_complete(request, access_token, error):
if error is None:
facebook = Facebook(token)
fbuser = facebook.me()
user, _ = User.objects.get_or_create(facebook_id=fbuser.id, defaults={
'access_token': access_token})
user = authenticate(id=user.id)
login(request, user)
return HttpResponseRedirect("/")
else:
# Error is of type ecl_facebook.facebook.FacebookError. We pass
# the error back to the callback so that you can handle it
# however you want.
pass
现在只需将这些 URL 连接到您的 urls.py 文件中即可。
# ...
urlpatterns = patterns('app.views',
# ...
url(r'^oauth/facebook/begin$', 'oauth_facebook_begin'),
url(r'^oauth/facebook/complete$', 'oauth_facebook_complete'),
)
希望这会有所帮助!
附:你可以阅读其余的文档here。