SlideShare a Scribd company logo
1 of 37
Integrating Facebook Connect
 authentication in your Django
          application
      Michael Trosen
      mrtrosen@lab305.com
      http://www.twitter.com/mrtrosen
      Lab305, LLC
      http://www.lab305.com
      http://djangonyc.lab305.com
      Django-NYC Presentation
      July 2nd, 2009
Django Reinhardt




•   Prominent European Jazz Musician
•   January 1910 – May 1953
•   Hurt in a fire when he was 18, played solos with only 2 fingers!
•   cofounded the Quintette du Hot Club de France
     – Information obtained from Wikipedia

          Michael Trosen – Lab305.com mrtrosen@lab305.com http://www.twitter.com/mrtrosen
?
Sorry, wrong meeting!



   Michael Trosen – Lab305.com mrtrosen@lab305.com http://www.twitter.com/mrtrosen
• Django is a high-level Python Web
  framework that encourages rapid
  development and clean, pragmatic design
• Django focuses on automating as much
  as possible and adhering to the DRY
  (Don't Repeat Yourself) principle.
• http://www.djangoproject.com
      Michael Trosen – Lab305.com mrtrosen@lab305.com http://www.twitter.com/mrtrosen
With the Facebook Connect APIs you gain access to
  ● Identity

       ●   A user's name, photos, and more
  ●   Friends
       ●   Data about a users friends
  ●   Distribution
       ●   All of the integration points within Facebook, like
           stream stories and notifications
  ●   Integration
       ●   Profile boxes, profile tabs, and publishers, just like
           apps on Facebook.


              Michael Trosen – Lab305.com mrtrosen@lab305.com http://www.twitter.com/mrtrosen
What’s involved?
•   Create a Facebook Application
•   Install PyFacebook
•   Install Ryan Mark’s django-facebook app
•   Create a new django project
•   Configure your settings.py
•   Configure your urls.py
•   Create some templates
•   Create your views
•   Run your application!


       Michael Trosen – Lab305.com mrtrosen@lab305.com http://www.twitter.com/mrtrosen
Assumptions
•   Using Ubuntu for development
•   Already have Django installed
•   You have git-core installed
•   You have subversion installed
•   You have mysql installed
•   You install packages to /usr/local
•   You have basic Django knowledge
•   You know what Facebook is

       Michael Trosen – Lab305.com mrtrosen@lab305.com http://www.twitter.com/mrtrosen
Add the Facebook Developer
        Application
http://www.facebook.com/developers/




     Michael Trosen – Lab305.com mrtrosen@lab305.com http://www.twitter.com/mrtrosen
Create a Facebook App
      Setup new application




  Michael Trosen – Lab305.com mrtrosen@lab305.com http://www.twitter.com/mrtrosen
Create a Facebook App




  Michael Trosen – Lab305.com mrtrosen@lab305.com http://www.twitter.com/mrtrosen
Configure Facebook App

                                                         Edit Settings




                                  IMPORTANT – API
                                  Keys

  Michael Trosen – Lab305.com mrtrosen@lab305.com http://www.twitter.com/mrtrosen
Configure Facebook Connect
          Settings




  Connect URL: http://localhost:8000
  Connect Logo – shown in connect dialog
  box when user is validating
   Michael Trosen – Lab305.com mrtrosen@lab305.com http://www.twitter.com/mrtrosen
Create your database
• #> mysql –u root –p
• mysql> create database djangonyc;
• mysql> quit;




       Michael Trosen – Lab305.com mrtrosen@lab305.com http://www.twitter.com/mrtrosen
Install PyFacebook
• PyFacebook GitHub location
  – http://github.com/sciyoshi/pyfacebook/tree/master

• PyFacebook Tutorial:
  – http://wiki.developers.facebook.com/index.php/PythonPyFacebookTutorial

• Install PyFacebook
  – #> git clone git://github.com/sciyoshi/pyfacebook.git
  – #> cd pyfacebook
  – #> python setup.py install
  – Ensure it’s working, open a python shell and try:
      • import facebook.djangofb



              Michael Trosen – Lab305.com mrtrosen@lab305.com http://www.twitter.com/mrtrosen
Install Ryan Mark’s
       django-facebookconnect
• Website
  – http://code.google.com/p/django-facebookconnect
• SVN Download
  – #> svn checkout http://django-facebookconnect.googlecode.com/svn/trunk/
    django-facebookconnect

• Please Note:
  – I've modified the django-facebookconnect
    django app to be a bit more functional and to
    obtain more data from facebook. This
    modified version is included in the sample
    application download
             Michael Trosen – Lab305.com mrtrosen@lab305.com http://www.twitter.com/mrtrosen
Create a new Django Application
• #> django-admin startproject djangonyc
• #> django-admin startapp exampleapp

• Copy the django-facebookconnect app
  into your new project
  – #> cp -R /usr/local/django-facebookconnect/django-
               facebookconnect/facebookconnect ./djangonyc/




            Michael Trosen – Lab305.com mrtrosen@lab305.com http://www.twitter.com/mrtrosen
Configure your settings.py
            Add your apps to INSTALLED_APPS


INSTALLED_APPS = (
  ‘django.contrib.auth',
    ‘django.contrib.sessions',
    ‘djangonyc.exampleapp',
    ‘djangonyc.facebookconnect',
)




               Michael Trosen – Lab305.com mrtrosen@lab305.com http://www.twitter.com/mrtrosen
Configure your settings.py
  Add the FacebookConnectMiddleware to your
              middleware_classes:
                             (order is important)


MIDDLEWARE_CLASSES =
( 'django.contrib.sessions.middleware.SessionMiddleware',
'facebook.djangofb.FacebookMiddleware',
'django.middleware.common.CommonMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'facebookconnect.middleware.FacebookConnectMiddleware', )



            Michael Trosen – Lab305.com mrtrosen@lab305.com http://www.twitter.com/mrtrosen
Configure your settings.py
add facebook to your authentication backends



 AUTHENTICATION_BACKENDS = (
     'facebookconnect.models.FacebookBackend',
     'django.contrib.auth.backends.ModelBackend',
 )




         Michael Trosen – Lab305.com mrtrosen@lab305.com http://www.twitter.com/mrtrosen
Configure your templates dir
TEMPLATE_DIRS = (
     os.path.join(os.path.dirname(__file__), 'templates').replace('','/'),
)


   Note: This determines the path of the templates directory based of
   the location of the settings.py file




              Michael Trosen – Lab305.com mrtrosen@lab305.com http://www.twitter.com/mrtrosen
Configure your database
  DATABASE_ENGINE = 'mysql'
  DATABASE_NAME = 'djangonyc'
  DATABASE_USER = 'user'
  DATABASE_PASSWORD = 'password'
  DATABASE_HOST = ''
  DATABASE_PORT = ''

Note: set the database username and password accordingly
Note: a blank host and port defaults to localhost and 3306
respectively for mysql




          Michael Trosen – Lab305.com mrtrosen@lab305.com http://www.twitter.com/mrtrosen
Configure your settings.py
       Configure Facebook Keys and Timeout
• FACEBOOK_CACHE_TIMEOUT = 1800
• FACEBOOK_API_KEY = '00000000000000000000000000000000'
• FACEBOOK_SECRET_KEY = '00000000000000000000000000000000‘
• FACEBOOK_INTERNAL = True

    Note: Set your facebook api and secret keys from the values created
    when you created your facebook application in the Facebook
    Developer Application on http://www.facebook.com




              Michael Trosen – Lab305.com mrtrosen@lab305.com http://www.twitter.com/mrtrosen
Configure some URLs
urlpatterns = patterns('',
   (r'^/?$', 'djangonyc.exampleapp.views.index'),
   (r'^accounts/profile', 'djangonyc.exampleapp.views.profile'),
   (r'^xd_receiver.html$', 'djangonyc.exampleapp.views.xd_receiver'),
   (r'^facebook/', include('facebookconnect.urls')),
)




              Michael Trosen – Lab305.com mrtrosen@lab305.com http://www.twitter.com/mrtrosen
Sync your database
• #> python manage.py syncdb
• We need to alter the auth_user table to
  change the size of the email column:
   – #> mysql -u root -p
   – mysql> use djangonyc;
   – mysql> alter table auth_user modify column email
     varchar(255);
 Note: In this example, do not create a super user when requested. All
 user creation is done when a user connects via facebook connect.

 Note: the email column needs to be modified because the email address
 from facebook is a proxy address that can be fairly long. You never
 receive a users 'real' email address from facebook.
             Michael Trosen – Lab305.com mrtrosen@lab305.com http://www.twitter.com/mrtrosen
Create a templates dir
   #> mkdir djangonyc/templates
Note: this is the directory we pointed to in the settings.py file




      Michael Trosen – Lab305.com mrtrosen@lab305.com http://www.twitter.com/mrtrosen
Create your facebook
               xd_receiver.html file

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
   "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
    <body>
    <script
        src="http://static.ak.connect.facebook.com/js/api_lib/v0.4/XdCommRece
        iver.js" type="text/javascript">
    </script>
    </body>
</html>


        Note: this file is put in the templates directory
        (djangonyc/templates/xd_receiver.html)



               Michael Trosen – Lab305.com mrtrosen@lab305.com http://www.twitter.com/mrtrosen
create your base.html file
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
    xmlns:fb="http://www.facebook.com/2008/fbml">
{% load facebook_tags %}
<head>
  {% facebook_js %}
  {% initialize_facebook_connect %}
</head>
<body>
  <div id='user'>
     {% if USER_LOGGED_IN %}
       <table border='0'> <tr> <td>
           Welcome {% show_facebook_first_name user %} {% show_logout %} <br />
           {% show_facebook_photo user %}
        </td> </tr>
        </table>
    {% else %}
      <table border='0'><tr>
            <td nowrap valign='middle' align='center'> {% show_connect_button %} </td>
            <td valign='middle' align='center'></td>
            </tr> </table>
    {% endif %}
   </div>
   {% block 'content' %} Page content here. {% endblock %}
</body>
</html>
                 Michael Trosen – Lab305.com mrtrosen@lab305.com http://www.twitter.com/mrtrosen
create your index.html file

  {% extends 'base.html' %}




   Michael Trosen – Lab305.com mrtrosen@lab305.com http://www.twitter.com/mrtrosen
Create your profile.html page
{% extends 'base.html' %}                       Any page that uses the templates
{% load facebook_tags %}                        must load the tags
{% block 'content' %}
<div>
<form action="/accounts/profile/" method="post" name="profileForm" id="profileForm"> <table>
   <tr><td> <table border='0'>
    <tr>
    <td colspan='2'>
     <span>
        <label for="Fname">Name:</label><br>
        <input id="nameUser" name="nameUser" type="text" readonly
                value="{% show_facebook_full_name user %}">
    </span>
   </td>                                                              Facebook tag
  </tr>
  </table>
   </td>
   <td align='center' valign='top'>
            Facebook Profile Image<br />
            {% show_facebook_large_photo user %}
   </td>
   </tr></table>
</form> </div> </div>
{% endblock %}

                  Michael Trosen – Lab305.com mrtrosen@lab305.com http://www.twitter.com/mrtrosen
Create your views
                       Imports

•from django.http import HttpResponseRedirect
•from django.shortcuts import render_to_response
•from django.conf import settings
•from django.template import RequestContext




       Michael Trosen – Lab305.com mrtrosen@lab305.com http://www.twitter.com/mrtrosen
Create your views
                              index
def index(request):
  user = ''
  if request.user.is_authenticated():
      user = request.user.facebook_profile
  return render_to_response(
      "index.html",
      {
      'USER_LOGGED_IN': request.user.is_authenticated(),
      'user': user,
      },
      context_instance=RequestContext(request)
  )

               Michael Trosen – Lab305.com mrtrosen@lab305.com http://www.twitter.com/mrtrosen
Create your views
                              profile
def profile(request):
  page = 'profile'
  user = ''

  if request.user.is_authenticated():
      user = request.user.facebook_profile
      friendList = request.user.facebook_profile.get_friends_profiles()
  else:
      print "REDIRECTING"
      return HttpResponseRedirect("/")
  return render_to_response(
      "profile.html",
      {
          'page': page,
          'USER_LOGGED_IN': request.user.is_authenticated(),
          'user': user,
          'friendList': friendList,
      },
      context_instance=RequestContext(request)
  )
Create your views
                            xd_receiver

def xd_receiver(request):
       return render_to_response('xd_receiver.html')




             Michael Trosen – Lab305.com mrtrosen@lab305.com http://www.twitter.com/mrtrosen
Run your new application
• #> python manage.py runserver
 Note: the default port will be 8000. We pointed the Connect setting in your
 facebook application to be: http://localhost:8000

 You can view the running local app at: http://localhost:8000 on your local
 computer.




               Michael Trosen – Lab305.com mrtrosen@lab305.com http://www.twitter.com/mrtrosen
facebookconnect info
• Pluggable App
• Various settings/facebook values located
  in the facebookconnect
• I modified Ryan Marks code and added in
  more facebook values, and return all
  values from facebook




        Michael Trosen – Lab305.com mrtrosen@lab305.com http://www.twitter.com/mrtrosen
Location of all dependencies
• Django
  – http://www.djangoproject.com
• Pyfacebook
  – http://wiki.developers.facebook.com/index.php/Python
• Django-facebookconnect
  – http://ryan-mark.com/2009/04/02/django-facebook-connect/
• Sample App Source Code
  – http://media.lab305.com/djangonyc-1.0.tgz




           Michael Trosen – Lab305.com mrtrosen@lab305.com http://www.twitter.com/mrtrosen
Any Questions
• Example app can be viewed at:
  – http://djangonyc.lab305.com
• Full source code of example site is locate
  available
  – http://media.lab305.com/djangonyc-1.0.tgz
• Please send a tweet or email if you found
  this useful or if you have any questions, or
  if you want to hire us to help you!
  – http://www.twitter.com/mrtrosen
  – mrtrosen@lab305.com
         Michael Trosen – Lab305.com mrtrosen@lab305.com http://www.twitter.com/mrtrosen

More Related Content

Similar to Lab305 Django Facebook Connect Integration Example

Power Up Your PLN Revised
Power Up Your PLN RevisedPower Up Your PLN Revised
Power Up Your PLN Revised
Jennifer Dorman
 
Building Things Fast - and getting approval
Building Things Fast - and getting approvalBuilding Things Fast - and getting approval
Building Things Fast - and getting approval
Simon Willison
 

Similar to Lab305 Django Facebook Connect Integration Example (20)

FLUID Templating in EXT:solr
FLUID Templating in EXT:solrFLUID Templating in EXT:solr
FLUID Templating in EXT:solr
 
Apache Solr for TYPO3 what's new 2018
Apache Solr for TYPO3 what's new 2018Apache Solr for TYPO3 what's new 2018
Apache Solr for TYPO3 what's new 2018
 
The social media developer
The social media developer The social media developer
The social media developer
 
So what's a web app? introduction to the chrome web store
So what's a web app? introduction to the chrome web storeSo what's a web app? introduction to the chrome web store
So what's a web app? introduction to the chrome web store
 
Technology tips for educators
Technology tips for educatorsTechnology tips for educators
Technology tips for educators
 
Developing SP 2013 Display Templates
Developing SP 2013 Display TemplatesDeveloping SP 2013 Display Templates
Developing SP 2013 Display Templates
 
Django - basics
Django - basicsDjango - basics
Django - basics
 
Develop High Performance Windows 8 Application with HTML5 and JavaScriptHigh ...
Develop High Performance Windows 8 Application with HTML5 and JavaScriptHigh ...Develop High Performance Windows 8 Application with HTML5 and JavaScriptHigh ...
Develop High Performance Windows 8 Application with HTML5 and JavaScriptHigh ...
 
WordCamp Bournemouth 2014 - Designing with data in WordPress
WordCamp Bournemouth 2014 - Designing with data in WordPressWordCamp Bournemouth 2014 - Designing with data in WordPress
WordCamp Bournemouth 2014 - Designing with data in WordPress
 
Power Up Your PLN Revised
Power Up Your PLN RevisedPower Up Your PLN Revised
Power Up Your PLN Revised
 
Pathways to Future Learning - Keynote #smootau13
Pathways to Future Learning - Keynote #smootau13Pathways to Future Learning - Keynote #smootau13
Pathways to Future Learning - Keynote #smootau13
 
Dbs-Week5-Class-Exercises
Dbs-Week5-Class-ExercisesDbs-Week5-Class-Exercises
Dbs-Week5-Class-Exercises
 
Technology Tips for Administrators
Technology Tips for AdministratorsTechnology Tips for Administrators
Technology Tips for Administrators
 
PowerUpYour PPLN
PowerUpYour PPLNPowerUpYour PPLN
PowerUpYour PPLN
 
Power Up Your Professional Learning Network
Power Up Your Professional Learning NetworkPower Up Your Professional Learning Network
Power Up Your Professional Learning Network
 
Puppet and your Metadata - PuppetCamp London 2015
Puppet and your Metadata - PuppetCamp London 2015Puppet and your Metadata - PuppetCamp London 2015
Puppet and your Metadata - PuppetCamp London 2015
 
Building Things Fast - and getting approval
Building Things Fast - and getting approvalBuilding Things Fast - and getting approval
Building Things Fast - and getting approval
 
Whats new-in-solr-8-typo3-camp
Whats new-in-solr-8-typo3-campWhats new-in-solr-8-typo3-camp
Whats new-in-solr-8-typo3-camp
 
Stop Reinventing The Wheel - The Ruby Standard Library
Stop Reinventing The Wheel - The Ruby Standard LibraryStop Reinventing The Wheel - The Ruby Standard Library
Stop Reinventing The Wheel - The Ruby Standard Library
 
Now That's What I Call WordPress Security 2010
Now That's What I Call WordPress Security 2010Now That's What I Call WordPress Security 2010
Now That's What I Call WordPress Security 2010
 

Recently uploaded

Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Safe Software
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
WSO2
 

Recently uploaded (20)

A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challenges
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
 
Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptx
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
A Beginners Guide to Building a RAG App Using Open Source Milvus
A Beginners Guide to Building a RAG App Using Open Source MilvusA Beginners Guide to Building a RAG App Using Open Source Milvus
A Beginners Guide to Building a RAG App Using Open Source Milvus
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 

Lab305 Django Facebook Connect Integration Example

  • 1. Integrating Facebook Connect authentication in your Django application Michael Trosen mrtrosen@lab305.com http://www.twitter.com/mrtrosen Lab305, LLC http://www.lab305.com http://djangonyc.lab305.com Django-NYC Presentation July 2nd, 2009
  • 2. Django Reinhardt • Prominent European Jazz Musician • January 1910 – May 1953 • Hurt in a fire when he was 18, played solos with only 2 fingers! • cofounded the Quintette du Hot Club de France – Information obtained from Wikipedia Michael Trosen – Lab305.com mrtrosen@lab305.com http://www.twitter.com/mrtrosen
  • 3. ? Sorry, wrong meeting! Michael Trosen – Lab305.com mrtrosen@lab305.com http://www.twitter.com/mrtrosen
  • 4. • Django is a high-level Python Web framework that encourages rapid development and clean, pragmatic design • Django focuses on automating as much as possible and adhering to the DRY (Don't Repeat Yourself) principle. • http://www.djangoproject.com Michael Trosen – Lab305.com mrtrosen@lab305.com http://www.twitter.com/mrtrosen
  • 5. With the Facebook Connect APIs you gain access to ● Identity ● A user's name, photos, and more ● Friends ● Data about a users friends ● Distribution ● All of the integration points within Facebook, like stream stories and notifications ● Integration ● Profile boxes, profile tabs, and publishers, just like apps on Facebook. Michael Trosen – Lab305.com mrtrosen@lab305.com http://www.twitter.com/mrtrosen
  • 6. What’s involved? • Create a Facebook Application • Install PyFacebook • Install Ryan Mark’s django-facebook app • Create a new django project • Configure your settings.py • Configure your urls.py • Create some templates • Create your views • Run your application! Michael Trosen – Lab305.com mrtrosen@lab305.com http://www.twitter.com/mrtrosen
  • 7. Assumptions • Using Ubuntu for development • Already have Django installed • You have git-core installed • You have subversion installed • You have mysql installed • You install packages to /usr/local • You have basic Django knowledge • You know what Facebook is Michael Trosen – Lab305.com mrtrosen@lab305.com http://www.twitter.com/mrtrosen
  • 8. Add the Facebook Developer Application http://www.facebook.com/developers/ Michael Trosen – Lab305.com mrtrosen@lab305.com http://www.twitter.com/mrtrosen
  • 9. Create a Facebook App Setup new application Michael Trosen – Lab305.com mrtrosen@lab305.com http://www.twitter.com/mrtrosen
  • 10. Create a Facebook App Michael Trosen – Lab305.com mrtrosen@lab305.com http://www.twitter.com/mrtrosen
  • 11. Configure Facebook App Edit Settings IMPORTANT – API Keys Michael Trosen – Lab305.com mrtrosen@lab305.com http://www.twitter.com/mrtrosen
  • 12. Configure Facebook Connect Settings Connect URL: http://localhost:8000 Connect Logo – shown in connect dialog box when user is validating Michael Trosen – Lab305.com mrtrosen@lab305.com http://www.twitter.com/mrtrosen
  • 13. Create your database • #> mysql –u root –p • mysql> create database djangonyc; • mysql> quit; Michael Trosen – Lab305.com mrtrosen@lab305.com http://www.twitter.com/mrtrosen
  • 14. Install PyFacebook • PyFacebook GitHub location – http://github.com/sciyoshi/pyfacebook/tree/master • PyFacebook Tutorial: – http://wiki.developers.facebook.com/index.php/PythonPyFacebookTutorial • Install PyFacebook – #> git clone git://github.com/sciyoshi/pyfacebook.git – #> cd pyfacebook – #> python setup.py install – Ensure it’s working, open a python shell and try: • import facebook.djangofb Michael Trosen – Lab305.com mrtrosen@lab305.com http://www.twitter.com/mrtrosen
  • 15. Install Ryan Mark’s django-facebookconnect • Website – http://code.google.com/p/django-facebookconnect • SVN Download – #> svn checkout http://django-facebookconnect.googlecode.com/svn/trunk/ django-facebookconnect • Please Note: – I've modified the django-facebookconnect django app to be a bit more functional and to obtain more data from facebook. This modified version is included in the sample application download Michael Trosen – Lab305.com mrtrosen@lab305.com http://www.twitter.com/mrtrosen
  • 16. Create a new Django Application • #> django-admin startproject djangonyc • #> django-admin startapp exampleapp • Copy the django-facebookconnect app into your new project – #> cp -R /usr/local/django-facebookconnect/django- facebookconnect/facebookconnect ./djangonyc/ Michael Trosen – Lab305.com mrtrosen@lab305.com http://www.twitter.com/mrtrosen
  • 17. Configure your settings.py Add your apps to INSTALLED_APPS INSTALLED_APPS = ( ‘django.contrib.auth', ‘django.contrib.sessions', ‘djangonyc.exampleapp', ‘djangonyc.facebookconnect', ) Michael Trosen – Lab305.com mrtrosen@lab305.com http://www.twitter.com/mrtrosen
  • 18. Configure your settings.py Add the FacebookConnectMiddleware to your middleware_classes: (order is important) MIDDLEWARE_CLASSES = ( 'django.contrib.sessions.middleware.SessionMiddleware', 'facebook.djangofb.FacebookMiddleware', 'django.middleware.common.CommonMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'facebookconnect.middleware.FacebookConnectMiddleware', ) Michael Trosen – Lab305.com mrtrosen@lab305.com http://www.twitter.com/mrtrosen
  • 19. Configure your settings.py add facebook to your authentication backends AUTHENTICATION_BACKENDS = ( 'facebookconnect.models.FacebookBackend', 'django.contrib.auth.backends.ModelBackend', ) Michael Trosen – Lab305.com mrtrosen@lab305.com http://www.twitter.com/mrtrosen
  • 20. Configure your templates dir TEMPLATE_DIRS = ( os.path.join(os.path.dirname(__file__), 'templates').replace('','/'), ) Note: This determines the path of the templates directory based of the location of the settings.py file Michael Trosen – Lab305.com mrtrosen@lab305.com http://www.twitter.com/mrtrosen
  • 21. Configure your database DATABASE_ENGINE = 'mysql' DATABASE_NAME = 'djangonyc' DATABASE_USER = 'user' DATABASE_PASSWORD = 'password' DATABASE_HOST = '' DATABASE_PORT = '' Note: set the database username and password accordingly Note: a blank host and port defaults to localhost and 3306 respectively for mysql Michael Trosen – Lab305.com mrtrosen@lab305.com http://www.twitter.com/mrtrosen
  • 22. Configure your settings.py Configure Facebook Keys and Timeout • FACEBOOK_CACHE_TIMEOUT = 1800 • FACEBOOK_API_KEY = '00000000000000000000000000000000' • FACEBOOK_SECRET_KEY = '00000000000000000000000000000000‘ • FACEBOOK_INTERNAL = True Note: Set your facebook api and secret keys from the values created when you created your facebook application in the Facebook Developer Application on http://www.facebook.com Michael Trosen – Lab305.com mrtrosen@lab305.com http://www.twitter.com/mrtrosen
  • 23. Configure some URLs urlpatterns = patterns('', (r'^/?$', 'djangonyc.exampleapp.views.index'), (r'^accounts/profile', 'djangonyc.exampleapp.views.profile'), (r'^xd_receiver.html$', 'djangonyc.exampleapp.views.xd_receiver'), (r'^facebook/', include('facebookconnect.urls')), ) Michael Trosen – Lab305.com mrtrosen@lab305.com http://www.twitter.com/mrtrosen
  • 24. Sync your database • #> python manage.py syncdb • We need to alter the auth_user table to change the size of the email column: – #> mysql -u root -p – mysql> use djangonyc; – mysql> alter table auth_user modify column email varchar(255); Note: In this example, do not create a super user when requested. All user creation is done when a user connects via facebook connect. Note: the email column needs to be modified because the email address from facebook is a proxy address that can be fairly long. You never receive a users 'real' email address from facebook. Michael Trosen – Lab305.com mrtrosen@lab305.com http://www.twitter.com/mrtrosen
  • 25. Create a templates dir #> mkdir djangonyc/templates Note: this is the directory we pointed to in the settings.py file Michael Trosen – Lab305.com mrtrosen@lab305.com http://www.twitter.com/mrtrosen
  • 26. Create your facebook xd_receiver.html file <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" > <body> <script src="http://static.ak.connect.facebook.com/js/api_lib/v0.4/XdCommRece iver.js" type="text/javascript"> </script> </body> </html> Note: this file is put in the templates directory (djangonyc/templates/xd_receiver.html) Michael Trosen – Lab305.com mrtrosen@lab305.com http://www.twitter.com/mrtrosen
  • 27. create your base.html file <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xmlns:fb="http://www.facebook.com/2008/fbml"> {% load facebook_tags %} <head> {% facebook_js %} {% initialize_facebook_connect %} </head> <body> <div id='user'> {% if USER_LOGGED_IN %} <table border='0'> <tr> <td> Welcome {% show_facebook_first_name user %} {% show_logout %} <br /> {% show_facebook_photo user %} </td> </tr> </table> {% else %} <table border='0'><tr> <td nowrap valign='middle' align='center'> {% show_connect_button %} </td> <td valign='middle' align='center'></td> </tr> </table> {% endif %} </div> {% block 'content' %} Page content here. {% endblock %} </body> </html> Michael Trosen – Lab305.com mrtrosen@lab305.com http://www.twitter.com/mrtrosen
  • 28. create your index.html file {% extends 'base.html' %} Michael Trosen – Lab305.com mrtrosen@lab305.com http://www.twitter.com/mrtrosen
  • 29. Create your profile.html page {% extends 'base.html' %} Any page that uses the templates {% load facebook_tags %} must load the tags {% block 'content' %} <div> <form action="/accounts/profile/" method="post" name="profileForm" id="profileForm"> <table> <tr><td> <table border='0'> <tr> <td colspan='2'> <span> <label for="Fname">Name:</label><br> <input id="nameUser" name="nameUser" type="text" readonly value="{% show_facebook_full_name user %}"> </span> </td> Facebook tag </tr> </table> </td> <td align='center' valign='top'> Facebook Profile Image<br /> {% show_facebook_large_photo user %} </td> </tr></table> </form> </div> </div> {% endblock %} Michael Trosen – Lab305.com mrtrosen@lab305.com http://www.twitter.com/mrtrosen
  • 30. Create your views Imports •from django.http import HttpResponseRedirect •from django.shortcuts import render_to_response •from django.conf import settings •from django.template import RequestContext Michael Trosen – Lab305.com mrtrosen@lab305.com http://www.twitter.com/mrtrosen
  • 31. Create your views index def index(request): user = '' if request.user.is_authenticated(): user = request.user.facebook_profile return render_to_response( "index.html", { 'USER_LOGGED_IN': request.user.is_authenticated(), 'user': user, }, context_instance=RequestContext(request) ) Michael Trosen – Lab305.com mrtrosen@lab305.com http://www.twitter.com/mrtrosen
  • 32. Create your views profile def profile(request): page = 'profile' user = '' if request.user.is_authenticated(): user = request.user.facebook_profile friendList = request.user.facebook_profile.get_friends_profiles() else: print "REDIRECTING" return HttpResponseRedirect("/") return render_to_response( "profile.html", { 'page': page, 'USER_LOGGED_IN': request.user.is_authenticated(), 'user': user, 'friendList': friendList, }, context_instance=RequestContext(request) )
  • 33. Create your views xd_receiver def xd_receiver(request): return render_to_response('xd_receiver.html') Michael Trosen – Lab305.com mrtrosen@lab305.com http://www.twitter.com/mrtrosen
  • 34. Run your new application • #> python manage.py runserver Note: the default port will be 8000. We pointed the Connect setting in your facebook application to be: http://localhost:8000 You can view the running local app at: http://localhost:8000 on your local computer. Michael Trosen – Lab305.com mrtrosen@lab305.com http://www.twitter.com/mrtrosen
  • 35. facebookconnect info • Pluggable App • Various settings/facebook values located in the facebookconnect • I modified Ryan Marks code and added in more facebook values, and return all values from facebook Michael Trosen – Lab305.com mrtrosen@lab305.com http://www.twitter.com/mrtrosen
  • 36. Location of all dependencies • Django – http://www.djangoproject.com • Pyfacebook – http://wiki.developers.facebook.com/index.php/Python • Django-facebookconnect – http://ryan-mark.com/2009/04/02/django-facebook-connect/ • Sample App Source Code – http://media.lab305.com/djangonyc-1.0.tgz Michael Trosen – Lab305.com mrtrosen@lab305.com http://www.twitter.com/mrtrosen
  • 37. Any Questions • Example app can be viewed at: – http://djangonyc.lab305.com • Full source code of example site is locate available – http://media.lab305.com/djangonyc-1.0.tgz • Please send a tweet or email if you found this useful or if you have any questions, or if you want to hire us to help you! – http://www.twitter.com/mrtrosen – mrtrosen@lab305.com Michael Trosen – Lab305.com mrtrosen@lab305.com http://www.twitter.com/mrtrosen