python - 如何向汤森路透 Open Calais API 提交 Python 请求

标签 python google-app-engine

我在 Google App Engine (gae) 上有一些 Python 代码,它向汤森路透 Open Calais API 发出请求:它发送一些纯文本作为数据,并且应该返回一个带有与文本对应的标签的 JSON 对象。不幸的是,我在 gae 控制台中收到的只是错误 500 以及以下错误消息:

enter image description here

上述错误似乎发生在 Werkzeug 中,Werkzeug 是一个 Python WSGI 实用程序库(无论 WSGI 意味着什么!)。错误出现在第 117 行 here ,所以也许这意味着字符集丢失,但我不知道应该在Python代码中的哪里设置字符集。

如果有人能帮助我解决这个问题,我将不胜感激。

这是我的 Python 代码:

from google.appengine.api import urlfetch
from flask import Flask, request

app = Flask(__name__)

calais_url = "https://api.thomsonreuters.com/permid/calais"

@app.route('/', methods=['POST'])
def main():
    data = "The 'In' camp holds a one-point lead ahead of Britain's June 23 referendum on whether the country should remain in the European Union, according to an online opinion poll by YouGov released on Friday.The poll found support for 'In' stood at 40 percent, while 39 percent intended to vote 'Out', 16 percent were undecided and 5 percent did not intend to vote.The poll of 3,371 people was conducted between April 12 and 14 and the results were similar to those seen in other recent YouGov polls. The previous one, conducted on April 11-12, found 'In' and 'Out' were tied on 39 percent with 17 percent undecided."
    headers = {'X-AG-Access-Token' : 'my_secret_key', 'Content-Type' : 'text/raw', 'outputFormat' : 'application/json', 'omitOutputtingOriginalText' : 'true'}
    try:
        sendArticleText(data, headers)
    except Exception ,e:
        return 'Error in connect ' , e

def sendArticleText(_data, _headers):
    response = urlfetch.fetch(calais_url, payload=_data , method=POST, headers=_headers, deadline=60)
    content = response.text
    if response.status_code == 200:
        return content.json()

@app.errorhandler(404)
def page_not_found(e):
    """Return a custom 404 error."""
    return 'Sorry, Nothing at this URL.', 404

@app.errorhandler(500)
def page_not_found(e):
    """Return a custom 500 error."""
    return 'Sorry, unexpected error:\n{}'.format(e), 500

提前谢谢您。

最佳答案

发生这种情况是因为您从 main 返回一个元组,并且如果 View 函数返回一个元组,则 Flask 期望元组中的第二个成员是 http 状态代码,而不是异常值。

而不是

return 'Error in connect ' , e

第 15 行应该是这样的:

return 'Error in connect: {}'.format(e)

这将使您看到真正的错误。

关于python - 如何向汤森路透 Open Calais API 提交 Python 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36700411/

相关文章:

python - 导入/包含配置 Python

python - 在 Python 中运行命令

python - 允许用户使用 GAE 匿名投票

google-app-engine - Datanucleus 在 Google App Engine 1.7 中使用了错误的增强器

python - session 不可用,因为未设置 key 。将应用程序上的 secret_key 设置为唯一且 secret 的内容。 flask /英雄

node.js - 为什么子文件夹没有部署到 Google App Engine Nodejs 应用程序

google-app-engine - 我们可以在谷歌应用引擎基础设施中使用 cassandra/couchdb/mongodb 吗?

python - 如何在 pandas Series 对象上并行化 `map` 函数?

python - Django Rest Framework 设置默认 PrimaryKeyRelated 字段值?

python - pandas 中的花式索引