Google Cloud PubSub未在Python中正确调用

问题描述 投票:2回答:2

我正在挤压我的大脑,但我不知道为什么这个问题正在发生,我无法弄清楚原因。我正在尝试读取图像并将其传递给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没有定义。你能就此提出建议吗?

python google-app-engine flask google-cloud-platform google-cloud-pubsub
2个回答
1
投票

如果你要打电话给全局,你必须在函数中声明:

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

2
投票

这里的问题是subscriber.subscribe(subscription, callback)正在建立对callback的异步调用。

这意味着当您发布新主题时,您实际上是在首先执行flash(...)调用还是回调之间设置竞争条件。由于回调可能需要一些时间才能完成,因此flash线获胜,但val1尚未创建,因此您的错误。

There are ways to control the concurrency可能通过阻止用户的未来来实现你想要做的事情。

然而,在尝试之前,我会问你为什么要在这里尝试使用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')
© www.soinside.com 2019 - 2024. All rights reserved.