1

我正在尝试在 Google Cloud Function 中将 Google Cloud Platform Natural Language API 与 Python 一起使用。每当我使用Google 教程中提供的代码来分析使用 Cloud Storage 中的文本进行实体分析时,都会收到以下错误消息:

 File "/user_code/main.py", line 9, in entity_sentiment_file
    type=enums.Document.Type.PLAIN_TEXT)
TypeError: <Request 'http://25e4801f1004e4eb41d11633d9b2e9e9-dot-ad6bdc7c397c15e62-tp.appspot.com/'
[POST]> has type LocalProxy, but expected one of: bytes, unicode

在成功部署函数并单击“测试函数”并触发空大括号 {} 事件后,我收到该错误消息,然后转到查看日志页面。

我尝试过提供如下所示的测试事件参数,但得到了相同的结果。

{"gcs_uri":"gs://test-news-articles/news-article-1.txt"}

这是我的整个功能:

from google.cloud import language
from google.cloud.language import enums
from google.cloud.language import types

def entity_sentiment_file(gcs_uri,request=None):
    print('gcs_uri: {}'.format(gcs_uri))
    client = language.LanguageServiceClient()
    document = types.Document(
        gcs_content_uri=gcs_uri,
        type=enums.Document.Type.PLAIN_TEXT)

    # Detect and send native Python encoding to receive correct word offsets.
    encoding = enums.EncodingType.UTF32
    if sys.maxunicode == 65535:
        encoding = enums.EncodingType.UTF16

    result = client.analyze_entity_sentiment(document, encoding)

    for entity in result.entities:
        print(u'Name: "{}"'.format(entity.name))
        for mention in entity.mentions:
            print(u'  Begin Offset : {}'.format(mention.text.begin_offset))
            print(u'  Content : {}'.format(mention.text.content))
            print(u'  Magnitude : {}'.format(mention.sentiment.magnitude))
            print(u'  Sentiment : {}'.format(mention.sentiment.score))
            print(u'  Type : {}'.format(mention.type))
        print(u'Salience: {}'.format(entity.salience))
        print(u'Sentiment: {}\n'.format(entity.sentiment))

任何帮助将非常感激。

4

1 回答 1

2

响应 HTTP 请求的函数需要具有签名:

def my_function(request):
    ...

requestCloud Functions 运行时针对每个新请求提供。

现在,gcs_uri被设置为request值(这是一种LocalProxy类型),然后你试图用它格式化一个字符串,这会导致异常。

我不确定您希望gcs_uri从哪里来,但它不会作为参数提供给函数。如果您使用 JSON 发出请求,则可以使用request.json['gcs_uri']. 有关详细信息,请参阅“编写 HTTP 函数”。

于 2019-03-26T20:13:10.883 回答