retrive google contacts using google contactapi with django

Firstly we create  a project in google developer Console using following links:

https://console.developers.google.com/home/dashboard?project=brickit-1134&pli=1

After create project click on side panel in google developer console and select "API MANAGER" and select google contact api and enable the api .After enable the api click on side pannel on "credentials" and click on add credentials.

There are three options:
1. API key
2. OAuth 2.0 Client id
3. service account

click on second options and go to consent screen and fill up the product name
and save it after save click on web application and fill up the name and authorized redirect urls which is necessary "authorized redirect ur"l ==> your django application url where we redirect.


After save it that generate a "client id" and "client secret" please save it.

Now goes to your django application.

install gdata in your virtualenv

and paste code in your views:


class ViewRedirectUrl(RedirectView):

    permanent = False

    def get_redirect_url(self, *args, **kwargs):
        try:
            auth_token = gdata.gauth.OAuth2Token(
                client_id=GOOGLE_CLIENT_ID,
                client_secret=GOOGLE_CLIENT_SECRET,
                scope=GOOGLE_SCOPE,
                # This is from the headers sent to google when getting your
                # access token (they don't return it)
                user_agent=USER_AGENT
            )

            redirect_url = "%s%s" % (
                BASE_URL,
                reverse_lazy("contact:gcontact"))

            authorize_url = auth_token.generate_authorize_url(
                redirect_uri=redirect_url,
                response_type='token',
                access_type='online')

            return authorize_url

        except Exception as e:
            print("%s\nError occurred:\n %s" % ('=' * 34, e.__str__()))

        return reverse_lazy("contact:gcontact")



this code will generate the token for google contacts api


and after this in your view paste this code:


import collections
import json

from django.views.generic.base import TemplateView
import requests


class ViewGContacts(TemplateView):
   
    template_name = "contact/gcontacts.html"

    #===========================================================================
    # get access_token
    #===========================================================================
    def get(self, request, *args, **kwargs):
        self.access_token = request.GET.get('access_token')
        return TemplateView.get(self, request, *args, **kwargs)
   
    #===========================================================================
    # Get Google Contacts
    #===========================================================================
    def get_contacts(self):
        r = requests.get('https://www.google.com/m8/feeds/contacts/default/full?access_token=%s&alt=json&max-results=1000&start-index=1' % (self.access_token))
#         print("access_token: %s" %self.access_token)
        print(r.url)
        data = json.loads(r.text)
        contact_data = {}       
        for entry in data['feed']['entry']:
#             print('%s, %s\n' %(entry['title']['$t'],entry['gd$phoneNumber'][0].get('uri')))
            try:
                title = entry['title']['$t']
                phone = entry.get('gd$phoneNumber')
                email = entry.get('gd$email')
                email = email[0].get('address') if email else ''
                phone = phone[0].get('$t') if phone else None
                contact_data[title] = {
                                  'title': title,
                                   'phone': phone,
                                   'email': email
                                   }
            except KeyError:
                print('error: %s' % dir(entry))
                continue          
           
        # sorting contact data
        sorted_contact_data = collections.OrderedDict(sorted(contact_data.items()))
        print(sorted_contact_data)
        return sorted_contact_data


this will return contact of your google contacts..


Thanks



Comments

  1. Hello Gurmukh,

    I find your post very useful for my Django application and I want to use your code into it. But I do not know how to call the views and in which sequence? It seems that the token is retrieved in the ViewContacts view class, but what shall I call exactly? Your answer would really help me a lot! Thanks in advance!

    ReplyDelete
  2. Hello Alexander,

    you will create two differents views. The first view is RedirectView and it will generate token for your google contacts. and redirect to second view which are return google contacts which are saved in your google contacts.

    ReplyDelete
  3. Thanks for the clarification. Could you share your urls.py content as I am struggling to understand what to do with "contact:gcontact" and how to call the second view?

    ReplyDelete
  4. "contact:gcontact" is the url of second view. i dont know how you used urls. Simply you can redirect on second view from first view as your requirement.

    ReplyDelete
    Replies
    1. Thanks a lot for the quick responses, you have really helped me!

      Delete

Post a Comment

Popular posts from this blog

Google Calendar api with django application

Create cronjob for django management command async process

Google recaptcha integration with django applicaton