簡體   English   中英

在谷歌雲平台 Function 中啟用 CORS Python

[英]Enabling CORS Python in Google Cloud Platform Function

我已經關注了一些 Medium 文章以及 Google 自己的教程,但仍然無法在此 function 上使用 flask 啟用 CORS:(

我缺少什么代碼來啟用 CORS? 我想要 * 的通配符,因為我希望所有服務/域都能夠訪問此功能和其他功能。

我聽說 GCP 不適用於 @app。 為什么,我不太確定。

請注意,我已經成功地直接在瀏覽器的 url 欄上測試輸出,並在 GCP 本身內觸發 JSON 測試。

我的預期用途僅用於 GET 請求。

from flask import Flask
import re

def hello_method(request):
    from flask import abort

    if request.method == 'GET':
        
        headers = {
            'Access-Control-Allow-Origin': '*',
            'Access-Control-Allow-Methods': 'GET',
            'Access-Control-Allow-Headers': 'Content-Type',
            'Access-Control-Max-Age': '3600'
        }

        request_json = request.get_json()
        pattern = re.compile("([0-9]+(\.[0-9]+)?)")
        
        if request.args and 'x' and 'y' in request.args:
            x_str = request.args.get('x')
            y_str = request.args.get('y')

            if not (pattern.match(x_str)):
                rtn = "{\"error\":true,\"string\":" + "NaN" + "*" + y_str + "=" + "NaN" + ",\"answer\":" + "NaN" +"}"
                return (rtn, 204, headers)
            if not (pattern.match(y_str)):
                rtn = "{\"error\":true,\"string\":" + x_str + "*" + "NaN" + "=" + "NaN" + ",\"answer\":" + "NaN" +"}"
                return (rtn, 204, headers)

            x = float(x_str)
            y = float(y_str)
            print("Args X: " + str(x))
            print("Args Y: " + str(y))
            ans = x * y
            print("Args Answer: " + str(ans))
            rtn = "{\"error\":false,\"string\":" + str(x) + "*" + str(y) + "=" + str(ans) + ",\"answer\":" + str(ans) +"}"
            return (rtn, 204, headers)
        elif request_json and 'x' and 'y' in request_json:
            x_str = request.args.get('x')
            y_str = request.args.get('y')

            if not (pattern.match(x_str)):
                rtn = "{\"error\":true,\"string\":" + "NaN" + "*" + y_str + "=" + "NaN" + ",\"answer\":" + "NaN" +"}"
                return (rtn, 204, headers)
            if not (pattern.match(y_str)):
                rtn = "{\"error\":true,\"string\":" + x_str + "*" + "NaN" + "=" + "NaN" + ",\"answer\":" + "NaN" +"}"
                return (rtn, 204, headers)

            print("JSON: ", request_json)
            x = float(request_json['x'])
            y = float(request_json['y'])
            print("JSON X: ", str(x)) 
            print("JSON Y: ", str(y))
            ans = x * y
            print("JSON Answer 2: " + str(ans))
            rtn = "{\"error\":false,\"string\":" + str(x) + "*" + str(y) + "=" + str(ans) + ",\"answer\":" + str(ans) +"}"
            return (rtn, 204, headers)
        else:
            return f"Please pass 2 variables x and y as http"

    elif request.method == 'PUT':
        return abort(403)
    else:
        return abort(405)

我似乎知道 CORS 的理論,但我的實踐還不夠強大,而且 GCP 似乎以不同的方式與 flask-cors 一起工作。

首先,不要使用 Flask。 每個 function 都旨在成為單個操作,Cloud Functions 已經負責請求路由和框架處理。

至於 CORS 問題,Cloud Functions 文檔中提供了有關如何處理 CORS 的示例。


在更新的代碼中,您拒絕 PUT 請求並在 GET 方法而不是 OPTIONS 方法中返回 CORS 標頭。 這不是上面鏈接的文檔所做的,請仔細檢查。 Cloud Function 的架構應如下所示:

def the_function(request):
    # Return CORS headers on OPTIONS request.
    if request.method == 'OPTIONS':
        headers = {
            'Access-Control-Allow-Origin': '*',
            'Access-Control-Allow-Methods': 'GET',
            'Access-Control-Allow-Headers': 'Content-Type',
            'Access-Control-Max-Age': '3600'
        }
        return ('', 204, headers)
    
    # If the request is GET then handle it normally
    if request.method == 'GET':
        x = request.args('x')
        y = request.args('x')
        result = int(x) * int(y)
        headers = {
            'Access-Control-Allow-Origin': '*'
        }
        return (result, 200, headers)
     else:
        # If the request is not GET or OPTIONS, deny.
        return '', 400

我了解您只想允許對 function 的 GET 請求。 但是,必須允許 OPTIONS HTTP 方法才能使 CORS 正常工作。 當網頁向另一個域請求內容時,瀏覽器可能會向目標域(在這種情況下為 Cloud Function)發送預檢請求,詢問是否允許實際的 GET/POST/etc.. 請求。 為了實現這一點,一個 OPTIONS 請求被發送到服務器,服務器必須響應確認允許的 HTTP 方法。 因此,要讓 function 按預期工作,它必須:

  1. 返回 OPTIONS 方法的Access-Control-Allow-XXX標頭。
  2. 接受任何其他返回實際響應的方法,在這種情況下為 GET。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM