Google Cloud Functions没有返回响应

时间:2019-05-28 09:12:47

标签: python-3.x curl flask google-cloud-platform google-cloud-functions

我正在Google云功能https://ocr.space/ocrapi上使用此api 这是我已部署的功能

def ocr_space_url(request):
    request_json = request.get_json()
    request_args = request.args


    if request_json and 'url' in request_json:
        url = request_json['url']

    elif request_args and 'url' in request_args: 
        url = request_args['url']
    else:
        url = 'http://www.africau.edu/images/default/sample.pdf'

    headers = {
        'apikey': 'helloworld',
    }
     payload = {'url': url,
               }
    r = requests.post('https://api.ocr.space/parse/image',
                      headers=headers, data=payload,
                      )

    return r.content.decode()


这样部署:
gcloud functions deploy ocr_space_url --runtime python37 --trigger-http

通过以下方式调用:
curl -X POST "https://us-central1-prefab-environs-241910.cloudfunctions.net/ocr_space_url" -H "Content-Type:application/json" -d "{"url": "http://dl.a9t9.com/ocrbenchmark/pdfscan.pdf"}"

当我使用内容类型调用它时,它给出了以下错误信息

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
<title>400 Bad Request</title>
<h1>Bad Request</h1>
<p>The browser (or proxy) sent a request that this server could not understand.</p>


如果我不使用内容类型来调用它,它将进入else,因为我得到了request_json = None,而对于其他URL,它给了我正确的结果

我有生以来第一次使用云功能,请帮忙

1 个答案:

答案 0 :(得分:1)

使用request作为参数,将您的POST数据解析为json(或您想要的任何内容)

#def ocr_space_url(url, overlay=False, api_key='helloworld', language='eng'):
def ocr_space_url(request):
    """ OCR.space API request with remote file.
        Python3.5 - not tested on 2.7
    :param url: Image url.
    :param overlay: Is OCR.space overlay required in your response.
                    Defaults to False.
    :param api_key: OCR.space API key.
                    Defaults to 'helloworld'.
    :param language: Language code to be used in OCR.
                    List of available language codes can be found on https://ocr.space/OCRAPI
                    Defaults to 'en'.
    :return: Result in JSON format.
    """

    request_json = request.get_json()
    if request_json and 'url' in request_json:
        url = request_json['url']
    else:
        url = 'http://www.africau.edu/images/defaultsample.pdf'

    payload = {'url': url,
               'isOverlayRequired': False,
               'apikey': 'helloworld',
               'language': 'eng',

               }
    r = requests.post('https://api.ocr.space/parse/image',
                      data=payload,
                      )
    return r.content.decode()

使用--data '{"url": "http://www.africau.edu/images/defaultsample.pdf"}' -H "Content-Type: application/json"

发出请求