2015-04-01 94 views
2

我是新來的Python以及Flask ...我已經開發了一個python文件,它設置了googele的Oauth2身份驗證並從GMAIL API獲取消息列表。這裏是我的代碼Python/Flask谷歌API集成

import json 
import flask 
import httplib2 
import base64 
import email 

from apiclient import discovery, errors 
from oauth2client import client 


app = flask.Flask(__name__) 


@app.route('/') 
def index(): 
    if 'credentials' not in flask.session: 
     return flask.redirect(flask.url_for('oauth2callback')) 
    credentials = client.OAuth2Credentials.from_json(flask.session['credentials']) 
    if credentials.access_token_expired: 
     return flask.redirect(flask.url_for('oauth2callback')) 
    else: 
     http_auth = credentials.authorize(httplib2.Http()) 
     gmail_service = discovery.build('gmail', 'v1', http_auth) 
     threads = gmail_service.users().threads().list(userId='me').execute() 
     return json.dumps(threads) 


@app.route('/oauth2callback') 
def oauth2callback(): 
    flow = client.flow_from_clientsecrets(
     'client_secrets.json', 
     scope='https://mail.google.com/', 
     redirect_uri=flask.url_for('oauth2callback', _external=True) 
    ) 
    if 'code' not in flask.request.args: 
     auth_uri = flow.step1_get_authorize_url() 
     return flask.redirect(auth_uri) 
    else: 
     auth_code = flask.request.args.get('code') 
     credentials = flow.step2_exchange(auth_code) 
     flask.session['credentials'] = credentials.to_json() 
     return flask.redirect(flask.url_for('index')) 

@app.route('/getmail') 
def getmail(): 
    if 'credentials' not in flask.session: 
     return flask.redirect(flask.url_for('oauth2callback')) 
    credentials = client.OAuth2Credentials.from_json(flask.session['credentials']) 
    if credentials.access_token_expired: 
     return flask.redirect(flask.url_for('oauth2callback')) 
    else: 
     http_auth = credentials.authorize(httplib2.Http()) 
     gmail_service = discovery.build('gmail', 'v1', http_auth) 
     query = 'is:inbox' 
     """List all Messages of the user's mailbox matching the query. 

     Args: 
     service: Authorized Gmail API service instance. 
     user_id: User's email address. The special value "me" 
     can be used to indicate the authenticated user. 
     query: String used to filter messages returned. 
     Eg.- 'from:[email protected]_domain.com' for Messages from a particular sender. 

     Returns: 
     List of Messages that match the criteria of the query. Note that the 
     returned list contains Message IDs, you must use get with the 
     appropriate ID to get the details of a Message. 
     """ 
     try: 
      response = gmail_service.users().messages().list(userId='me', q=query).execute() 
      messages = [] 
      if 'messages' in response: 
       print 'test %s' % response 
       messages.extend(response['messages']) 
      while 'nextPageToken' in response: 
       page_token = response['nextPageToken'] 
       response = gmail_service.users().messages().list(userId='me', q=query, pageToken=page_token).execute() 
       messages.extend(response['messages']) 

      return messages 
     except errors.HttpError, error: 
      print 'An error occurred: %s' % error 

if __name__ == '__main__': 
    import uuid 
    app.secret_key = str(uuid.uuid4()) 
    app.debug = True 
    app.run() 

認證工作正常,當我去/getmail URL我收到此錯誤TypeError: 'list' object is not callable

任何思考什麼,我做錯了什麼?

+4

參見[這個答案](http://stackoverflow.com/questions/27608987/typeerror-list-object-is - 不可調用瓶)也許它有幫助。 – doru 2015-04-01 09:06:57

+0

非常感謝你,你真棒:D – 2015-04-01 09:11:17

+0

很高興幫助:) – doru 2015-04-01 09:18:20

回答

2

我將Flask中的返回對象從return messages更改爲這段代碼。

首先,我導入到from flask.json import jsonify

try: 
    response = gmail_service.users().messages().list(userId='me', q=query).execute() 
    messages = [] 
    if 'messages' in response: 
     print 'test %s' % response 
     messages.extend(response['messages']) 
    while 'nextPageToken' in response: 
     page_token = response['nextPageToken'] 
     response = gmail_service.users().messages().list(userId='me', q=query, pageToken=page_token).execute() 
     messages.extend(response['messages']) 

    return jsonify({'data': messages}) # changed here 
except errors.HttpError, error: 
    print 'An error occurred: %s' % error 

都歸功於@doru