Python/Flask 谷歌 API 集成

标签 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(__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' object is not callable

有什么想法我做错了吗?

最佳答案

我将 Flask 中的返回对象从返回消息更改为这段代码。

首先我导入到 fromflask.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

关于Python/Flask 谷歌 API 集成,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29386727/

相关文章:

python - 向下滚动列表 instagram selenium 和 python

python - 将 float 转换为逗号分隔的字符串

python - Keras Tensorflow val_acc始终为1或从0跳到1

python - 无法从 flask 中的 send_from_directory() 检索文件

javascript - 将 Select2 与 flask-wtforms 一起使用

java - SMS Retriever API 中发布的 APK 上的 HASH 字符串 key

python - 在包含列表的列表上搜索并删除我们搜索的特定列表

python - Flask-Security 的上下文处理器的返回值是如何使用的?

node.js - 谷歌API日历 watch 不起作用,但 channel 已创建

python - 在 Google Places api 中搜索附近的 lat_lng (python)