![](/img/trans.png)
[英]Application context errors when locally testing a (Python) Google Cloud Function
[英]Testing Google Cloud PubSub push endpoints locally
試圖找出在本地測試 PubSub 推送端點的最佳方法。 我們嘗試使用 ngrok.io,但您必須擁有該域才能列入白名單(這樣做的工具也已損壞……導致無限重定向循環)。 我們還嘗試在本地模擬 PubSub。 我可以發布和拉取,但我無法讓推送訂閱正常工作。 我們正在使用本地 Flask 網絡服務器,如下所示:
@app.route('/_ah/push-handlers/events', methods=['POST'])
def handle_message():
print request.json
return jsonify({'ok': 1}), 200
以下不會產生任何結果:
client = pubsub.Client()
topic = client('events')
topic.create()
subscription = topic.subscription('test_push', push_endpoint='http://localhost:5000/_ah/push-handlers/events')
subscription.create()
topic.publish('{"test": 123}')
當我們嘗試創建對 HTTP 端點的訂閱時,它確實會對我們大喊大叫(而如果您不使用 HTTPS,則實時 PubSub 會這樣做)。 也許這是設計使然? Pull 工作得很好……關於如何最好地在本地開發 PubSub 推送端點有什么想法嗎?
根據撰寫本文時最新的 PubSub 庫文檔,以下示例使用推送配置創建訂閱。
我已經按照以下要求進行了測試:
requirements.txt
):flask==1.1.1
google-cloud-pubsub==1.3.1
export PUBSUB_PROJECT_ID=fake-project
gcloud beta emulators pubsub start --project=$PUBSUB_PROJECT_ID
默認情況下,PubSub 模擬器在端口 8085 上啟動。項目參數可以是任何內容,無關緊要。
考慮以下server.py
:
from flask import Flask, jsonify, request
app = Flask(__name__)
@app.route('/_ah/push-handlers/events', methods=['POST'])
def handle_message():
print(request.json)
return jsonify({'ok': 1}), 200
if __name__ == "__main__":
app.run(port=5000)
運行服務器(在端口 5000 上啟動):
python server.py
考慮以下pubsub.py
:
import sys
from google.cloud import pubsub_v1
if __name__ == "__main__":
project_id = sys.argv[1]
# 1. create topic (events)
publisher_client = pubsub_v1.PublisherClient()
topic_path = publisher_client.topic_path(project_id, "events")
publisher_client.create_topic(topic_path)
# 2. create subscription (test_push with push_config)
subscriber_client = pubsub_v1.SubscriberClient()
subscription_path = subscriber_client.subscription_path(
project_id, "test_push"
)
subscriber_client.create_subscription(
subscription_path,
topic_path,
push_config={
'push_endpoint': 'http://localhost:5000/_ah/push-handlers/events'
}
)
# 3. publish a test message
publisher_client.publish(
topic_path,
data='{"test": 123}'.encode("utf-8")
)
最后,運行這個腳本:
PUBSUB_EMULATOR_HOST=localhost:8085 \
PUBSUB_PROJECT_ID=fake-project \
python pubsub.py $PUBSUB_PROJECT_ID
然后,您可以在 Flask 服務器的日志中看到結果:
{'subscription': 'projects/fake-project/subscriptions/test_push', 'message': {'data': 'eyJ0ZXN0IjogMTIzfQ==', 'messageId': '1', 'attributes': {}}}
127.0.0.1 - - [22/Mar/2020 12:11:00] "POST /_ah/push-handlers/events HTTP/1.1" 200 -
請注意,您可以檢索發送的消息,這里以 base64 ( message.data
) 編碼:
$ echo "eyJ0ZXN0IjogMTIzfQ==" | base64 -d
{"test": 123}
當然,你也可以用 Python 進行解碼。
我未能讓 PubSub 模擬器在我的本地環境中工作(失敗並出現各種 java 異常)。 我什至沒有嘗試使用 auth 推送等各種功能。所以我最終使用ngrok公開我的本地開發服務器,並在 PubSub 訂閱中使用來自 ngrok 的公共 https URL。
我對 Q 中描述的白名單和重定向沒有任何問題。因此可能對其他人有幫助。
這可能是模擬器中的一個已知錯誤(即將修復),其中與訂閱一起創建的推送端點不起作用。 該錯誤僅影響初始推送配置; 修改現有訂閱的推送配置應該可以工作。 你可以試試嗎?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.