簡體   English   中英

無法在Python中正確調用Google Cloud PubSub

[英]Google Cloud PubSub not being called properly in Python

我擠我的大腦,但我不明白為什么這個問題正在發生,我無法找出原因。 我正在嘗試讀取圖像並將其傳遞給pubsub。 通過pubsub發送消息后,會將其重定向到AutoML模型以識別或預測給定圖像。 下面是代碼片段

global val1   
@app.route("/", methods=['GET', 'POST'])
doc_type=request.form.get('submit_button')
        file_name = secure_filename(file.filename)
        blob=file.read()
        flash('File upload successful', 'info')
        # Initializing PubSub
        publisher,subscriber,topic,subscription=pubsub_init(doc_type) 
        blob=blob+bytes(doc_type,'utf-8')
        subscriber.subscribe(subscription,callback)
        publisher.publish(topic,blob)
        flash("the uploaded file is "+val1,'info')

初始化功能:

def pubsub_init(doctype):
    publisher=pubsub.PublisherClient()
    subscriber=pubsub.SubscriberClient()
    if doctype=="License":
        subscription=<<sub name>>
    elif doctype=="Credit":
        subscription=<<subname>>
    elif doctype=="Passport":
        subscription=<<subname>>
    else:
        print("invalid choice"
  topic=<<topic>>
print(subscription)
return (publisher,subscriber,topic,subscription)

我的回電:

def callback(message):
    #print("hello",flush=True)
     print("making global")
     project_id=<<proj id>>
     val1,val2=predict_value(new_message,model_id,project_id,compute_region)
     message.ack()

但是我收到了類似val1的錯誤,但未定義。 您能對此提出建議嗎?

這里的問題是subscriber.subscribe(subscription, callback)正在設置對callback的異步調用。

這意味着在發布新主題時,實際上是在設置是否首先執行對flash(...)的調用或回調之間的競爭條件。 由於回調可能要花一些時間才能完成,所以flash行很成功,但是尚未創建val1 ,因此會出現錯誤。

有多種控制並發的方法,這些方法可能會阻止訂閱者的未來,從而使您嘗試執行的操作成為可能。

但是,在嘗試該操作之前,我會問您為什么首先嘗試在此處使用pub / sub。 似乎您只是在設置發布者和訂閱者來發布一條消息,然后嘗試對該消息的結果進行處理。 為什么不全部全部內聯?

@app.route("/", methods=['GET', 'POST'])
def your_function(request):
    doc_type=request.form.get('submit_button')
    file_name = secure_filename(file.filename)
    blob=file.read()
    flash('File upload successful', 'info')
    blob=blob+bytes(doc_type,'utf-8')
    # turn a blob into new_message, get model_id from somewhere?
    project_id=<<proj id>>
    val1,val2=predict_value(new_message,model_id,project_id,compute_region)
    flash("the uploaded file is "+val1,'info')

如果要調用全局變量,則必須在函數中聲明為:

def callback(message):
    global val1
    global val2
    ...
    val1, val2 = predict_value(new_message,model_id,project_id,compute_region)

暫無
暫無

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

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