Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/344.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python/googleapi集成_Python_Flask_Google Api_Google Api Python Client - Fatal编程技术网

Python/googleapi集成

Python/googleapi集成,python,flask,google-api,google-api-python-client,Python,Flask,Google Api,Google Api Python Client,我对Python和Flask都是新手。。。我开发了一个python文件,它使用googele设置Oauth2身份验证,并从GMAIL API获取消息列表。这是我的密码 import json import flask import httplib2 import base64 import email from apiclient import discovery, errors from oauth2client import client app = flask.Flask(__nam

我对Python和Flask都是新手。。。我开发了一个python文件,它使用googele设置Oauth2身份验证,并从GMAIL 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:user@some_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”对象不可调用


你知道我做错了什么吗?

我将Flask中的return对象从
return messages
更改为这段代码

首先,我从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

看看它是否有帮助。非常感谢你,你太棒了:D