---
title: "GAE-oAuth-python"
author: "iamsk"
date: "2010-12-02T11:02:06Z"
tags: []
categories: ["编程语言"]
slug: "gae-oauth-python"
draft: false
lastmod: "2010-12-02T11:02:06Z"
id: 831234
url: "https://iamsk.iteye.com/blog/831234"
---

转自 gae group

 

I know the question of GAE + OAuth has come up before.  In case it is   
useful to anyone, here is the code I used to get access to GMail inbox   
with OAuth.  I use the base OAuth client classes from   
[http://oauth.googlecode.com/svn/code/python/](http://www.google.com/url?sa=D&q=http%3A%2F%2Foauth.googlecode.com%2Fsvn%2Fcode%2Fpython%2F&usg=AFQjCNHzmbmQNrZArdP5Tc5a9AKCVoGd-w) , but unlike the example   
code (which uses httplib) I use urlfetch. 

I use the GAE webapp framework, and I have left out the code not   
directly related to OAuth: 

REQUEST\_TOKEN\_URL = '[https://www.google.com/accounts/](http://www.google.com/url?sa=D&q=https%3A%2F%2Fwww.google.com%2Faccounts%2F&usg=AFQjCNGdkGP5kciJMpZwDYlekwJ4r-Mocg)    
OAuthGetRequestToken'   
ACCESS\_TOKEN\_URL = '[https://www.google.com/accounts/](http://www.google.com/url?sa=D&q=https%3A%2F%2Fwww.google.com%2Faccounts%2F&usg=AFQjCNGdkGP5kciJMpZwDYlekwJ4r-Mocg)    
OAuthGetAccessToken'   
AUTHORIZATION\_URL = '[https://www.google.com/accounts/](http://www.google.com/url?sa=D&q=https%3A%2F%2Fwww.google.com%2Faccounts%2F&usg=AFQjCNGdkGP5kciJMpZwDYlekwJ4r-Mocg)    
OAuthAuthorizeToken'   
CALLBACK\_URL = 'http://&lt;yourapp&gt;.appspot.com/oauth/token\_ready'   
RESOURCE\_URL = '[https://mail.google.com/mail/feed/atom'](http://www.google.com/url?sa=D&q=https%3A%2F%2Fmail.google.com%2Fmail%2Ffeed%2Fatom%27&usg=AFQjCNFcHm02-07PSU0COtFN6Abdx-WVLA)    
SCOPE = '[https://mail.google.com/mail/feed/atom'](http://www.google.com/url?sa=D&q=https%3A%2F%2Fmail.google.com%2Fmail%2Ffeed%2Fatom%27&usg=AFQjCNFcHm02-07PSU0COtFN6Abdx-WVLA)    
CONSUMER\_KEY = &lt;your consumer key&gt;   
CONSUMER\_SECRET = '&lt;your consumer secret&gt; 

class OAuthToken(db.Model):   
    user = db.UserProperty()   
    token\_key = db.StringProperty(required=True)   
    token\_secret = db.StringProperty(required=True)   
    type = db.StringProperty(required=True)   
    scope = db.StringProperty(required=True) 

\# the home page displays the nwest messages from the users inbox   
\# it looks for a saved access token, and if there is not one,   
redirects   
\# to /oauth to begin the dance...   
class HomePage(BaseRequestHandler):   
  @login\_required   
  def get(self):   
      mail\_feed = ''   
      t = OAuthToken.all()   
      t.filter("user =",users.GetCurrentUser())   
      t.filter("scope =", SCOPE)   
      t.filter("type =", 'access')   
      results = t.fetch(1)   
      for oauth\_token in results:   
          if oauth\_token.token\_key:   
              key = oauth\_token.token\_key   
              mail\_feed = oauth\_token.token\_key   
              secret = oauth\_token.token\_secret   
              token = oauth.OAuthToken(key,secret)   
              consumer = oauth.OAuthConsumer(CONSUMER\_KEY,   
CONSUMER\_SECRET)   
              oauth\_request =   
oauth.OAuthRequest.from\_consumer\_and\_token(consumer, 

token=token, 

http\_url=SCOPE)   
              signature\_method = oauth.OAuthSignatureMethod\_HMAC\_SHA1   
()   
              oauth\_request.sign\_request(signature\_method, consumer,   
token)   
              result = urlfetch.fetch(url=SCOPE,   
                                      method=urlfetch.GET,   
                                      headers=oauth\_request.to\_header   
())   
              # I use a custom atom wrapper for displaying the feed   
              mail\_feed = atomlib.atom03.Atom.from\_text   
(result.content)   
      if not mail\_feed:   
            self.redirect('/oauth')   
      self.generate('index.html', {   
          'mail\_feed' : mail\_feed,   
      }) 

\# this class (probably should not be called a "page")   
\# gets a request token and authorizes it   
class OAuthPage(BaseRequestHandler):   
  def get(self):   
    scope = {'scope':SCOPE}   
    consumer = oauth.OAuthConsumer(CONSUMER\_KEY, CONSUMER\_SECRET)   
    oauth\_request = oauth.OAuthRequest.from\_consumer\_and\_token   
(consumer, 

token=None, 

http\_url=REQUEST\_TOKEN\_URL,parameters=scope)   
    signature\_method = oauth.OAuthSignatureMethod\_HMAC\_SHA1()   
    oauth\_request.sign\_request(signature\_method, consumer, None)   
    url = oauth\_request.to\_url()   
    result = urlfetch.fetch(url)   
    if result.status\_code == 200:   
        token = oauth.OAuthToken.from\_string(result.content)   
        #persist token   
        saved\_token = OAuthToken(user=users.GetCurrentUser(),   
                                 token\_key = token.key,   
                                 token\_secret = token.secret,   
                                 scope = SCOPE,   
                                 type = 'request',   
                                )   
        saved\_token.put()   
        #now authorize token   
        oauth\_request = oauth.OAuthRequest.from\_token\_and\_callback   
(token=token, 

callback=CALLBACK\_URL, 

http\_url=AUTHORIZATION\_URL)   
        url = oauth\_request.to\_url()   
        self.redirect(url)   
    else:   
      self.response.out.write('no request token') 

#this class is where we exchange the request token   
\# for an access token   
class OAuthReadyPage(BaseRequestHandler):   
  def get(self):   
      t = OAuthToken.all()   
      t.filter("user =",users.GetCurrentUser())   
      t.filter("token\_key =", self.request.get('oauth\_token'))   
      t.filter("scope =", SCOPE)   
      t.filter("type =", 'request')   
      results = t.fetch(1)   
      for oauth\_token in results:   
          if oauth\_token.token\_key:   
              key = oauth\_token.token\_key   
              secret = oauth\_token.token\_secret   
              token = oauth.OAuthToken(key,secret)   
              #get access token   
              consumer = oauth.OAuthConsumer(CONSUMER\_KEY,   
CONSUMER\_SECRET)   
             oauth\_request = oauth.OAuthRequest.from\_consumer\_and\_token   
(consumer, 

token=token, 

http\_url=ACCESS\_TOKEN\_URL)   
              signature\_method = oauth.OAuthSignatureMethod\_HMAC\_SHA1   
()   
              oauth\_request.sign\_request(signature\_method, consumer,   
token)   
              url = oauth\_request.to\_url()   
              result = urlfetch.fetch(url)   
              if result.status\_code == 200:   
                  token = oauth.OAuthToken.from\_string(result.content)   
                  oauth\_token.token\_key = token.key   
                  oauth\_token.token\_secret = token.secret   
                  oauth\_token.type = 'access'   
                  oauth\_token.put()   
                  self.redirect('/')   
              else:   
                  self.response.out.write(result.content)   
          else:   
                  self.response.out.write('no go')   
def main():   
  application = webapp.WSGIApplication([   
    ('/', HomePage),   
    ('/oauth', OAuthPage),   
    ('/oauth/token\_ready', OAuthReadyPage),   
  ], debug=\_DEBUG)   
  wsgiref.handlers.CGIHandler().run(application) 

if \_\_name\__ == '\_\_main\_\_':   
  main() 

--peter keane