【问题标题】:Request has type LocalProxy, but expected one of: bytes, unicode请求的类型为 LocalProxy,但预期为以下之一:字节、unicode
【发布时间】:2019-03-26 04:02:15
【问题描述】:

我正在尝试在 Google Cloud Function 中将 Google Cloud Platform Natural Language API 与 Python 结合使用。每当我使用 this 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))

任何帮助将不胜感激。

【问题讨论】:

    标签: python-3.x google-cloud-platform nlp google-cloud-functions google-natural-language


    【解决方案1】:

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

    def my_function(request):
        ...
    

    其中 request 由 Cloud Functions 运行时针对每个新请求提供。

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

    我不确定您期望gcs_uri 来自哪里,但它不会作为参数提供给函数。如果您使用 JSON 发出请求,则可以使用 request.json['gcs_uri']。详情请参阅“Writing HTTP Functions”。

    【讨论】:

    • 谢谢!我现在知道了。我将函数参数设为“请求”,将测试事件设为 {“gcs_uri”:“gs://test-news-articles/news-article-1.txt”},并且可以使用 request_json['gcs_uri' 访问 gcs_uri ].
    猜你喜欢
    • 2021-01-12
    • 1970-01-01
    • 2020-10-19
    • 1970-01-01
    • 1970-01-01
    • 2021-05-29
    • 2021-12-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多