Wxpython applications use google gauth Certification

Source: Internet
Author: User
Tags oauth

Recently, wxpyhon google Contacts were used, and oauth verification was unavoidable.

Google provides the following four OAuth 2.0 methods:

  • The Client-side Applications flow for JavaScript applications running in a browser

This flow applies to Javascript-based web apps, which are based on javascript and do not require maintain state over time (for example, session is not required to store state ).


  • The Web Server Applications flow for web applications with servers that can securely store persistent information

This flow is meant for web applications with servers that can keep secrets and maintain state.


  • The Installed Applications flow for desktop and mobile applications

This flow is meant for mobile, and desktop installed applications that wantaccess to user data.


  • TheOAuth 2.0 for DevicesFlow.

This flow applies to applications that want to access google data that run on the device, but cannot perform user authorization (e.g. game consoles les or media hubs). You must use another PC or device to perform user authorization.

This flow is suitable for applications executing on devices which wantaccess to user data, but don't have an easy data-entry method (e.g. game consoles les or media hubs), and where the end-user has separate access to a user-agent on another computer or device (e.g. home computer, a latop, or asmart phone ).

Since wxpython is the third installed application, let's just talk about how to use it.

There are two methods to obtain the access token,One is to use http requests, and the other is to use gdata. gauth

Http requests are flexible, but they are more suitable for online use. It is also troublesome to save tokens. First, let's talk about how to use http requests.

Step 1 send user information to OAuth

# Example def gen_url (url, data): ''' generate url-''' params = '&'. join ([str (arg) + '=' + str (val) for arg, val in data. items ()]) url = url + '? '+ Params return urlurl = "https://accounts.google.com/o/oauth2/auth" datas = {'client _ id' = '0000.appsusercontent.com' 'redirect _ ur' = 'urn: ietf: wg: oauth: 21302922996: oob ''scope '= 'https: // www.google.com/m8/feeds/''response _ type' = Code'} auth_url = gen_url (url, data) webbrowser. open (auth_url)

 

Parameters

Id of the application created by client_id (if no application has been created, click the above link to see how to create the Application)

Step 2 when the above request is sent

 

"access_token":"1/fFAGRNJru1FTz70BzhT3Zg""expires_in":3600"token_type":"Bearer""refresh_token":"1/6BMfW9j53gdGImsixUH6kU5RsR4zwI9lUVX-tqf8JXQ"

Then you can use access_token as the parameter to access the api.

The preceding method is used to obtain the token in http mode.

Now we will introduce the second method to obtain the data using gdata. gauth.

Use the code to explain it clearly.

#! /Usr/bin/python # * coding: utf8 * ''' File: contact_login.pyAuthor: goodspeedDate: 20130505 17:00:36 CSTDescription: google contacts login model ''' from _ ure _ import unicode_literals import wx import webbrowser import gdata. gauthimport atom. http_core APP_NAME = 'your App name' CLIENT _ ID = 'your CLIENT_ID 'client _ SECRET = 'your CLIENT_SECRET 'SCOPE = 'https: // www.google.com/m8/feeds/'REDIRECT_URI =' Urn: ietf: wg: oauth: 2.0: oob 'oauth _ URL = 'https: // region = 'https: // accounts.google.com/o/oauth2/token'USER_AGENT = 'dummysample' def get_auth_code (): ''' get authorization code ''' auth_token = gdata. gauth. OAuth2Token (client_id = CLIENT_ID, client_secret = CLIENT_SECRET, scope = SCOPE, user_agent = '',) redirect_uri = REDIRECT_URI auth_url = auth_token.generate_aut Horize_url (redirect_uri = redirect_uri) # Open the url in the browser and complete the logon authorization step to obtain the authorization code webbrowser. open (auth_url) def get_access_token (auth_token, auth_code): ''' get the access token using the obtained authorization code and save ''' redirect_url = '% s? Code = % s' % (REDIRECT_URI, auth_code) url = atom. http_core.ParseUri (redirect_url) token = auth_token.get_access_token (url. query) token = gdata. gauth. token_to_blob (auth_token) return auth_token # login portal def singin (): # retrieve saved token weak no token = None try: with open ('Token', 'R') as: token =. read () try: token = gdata. gauth. token_from_blob (token) Does T gdata. gauth. unsupportedTokenType, e: raise e failed T: Ken = None # first determine whether a saved token exists # if a saved token is used directly, if it is not re-obtained, if token: auth_token = token else: auth_token = get_auth_code () auth_code = enter_auth_code () auth_token = get_access_token (auth_token, auth_code) return auth_token # copy the authorization code to the diization and return the wxpytondef enter_auth_code (): dialog = wx. textEntryDialog (None, 'enter authorization code! ', 'Enter authorization Code', '', style = wx. OK | wx. CANCEL) if dialog. showModal () = wx. ID_ OK: # return authorization code return dialog. getValue () dialog. destroy ()


If _ name _ = '_ main __':
Singin ()

 

Now you can use auth_token to access the API.

#!/usr/bin/python                                                               # -*- coding: utf-8 -*-                                                         '''                                                                             File: contacts_operate.py                                                       Author: goodspeed                                                               Date: 2013-05-07 20:13:14 CST                                                   Description: contacts data operate                                              '''                                                                                                                                                             from __future__ import unicode_literals                                                                                                                         import gdata.contacts.client as gd                                                                                                                              from login_contact import APP_NAME                                                                                                                                                                                                              def query_contacts(auth_token):                                                     gd_client = gd.ContactsClient(source=APP_NAME)                                  gd_client = auth_token.authorize(gd_client)                                     query = gd.ContactsQuery(max_results=200)                                       feed = gd_client.GetContacts(q = query)                                                                                        for i, entry in enumerate(feed.entry):                                                                        if entry.name:                                                                      print i, entry.name.full_name.text

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.