簡體   English   中英

如何使用Flask在Python中將數據從服務器發送到客戶端?

[英]How to send data from server to client in Python using Flask?

我正在制作一個將數據發送到客戶端的應用程序,然后客戶端打印數據。

我使用Flask作為處理服務器端的后端框架,並使用另一個python腳本為當前客戶端生成隨機ID,客戶端每4秒檢查一次是否有新數據進入,如果有新數據則應打印該數據。

后端代碼

@app.route('/data/api/interact/<string:client_id>', methods=['GET', 'POST'])
@login_required
def interact(client_id):
    global data

    form = Interact()
    data = ''

    if form.is_submitted():
        get_data = form.ct.data

        if get_data == 'hello':
            data = 'Hi how are you?'

        return redirect(url_for('data_handler', client_id=client_id, data=form.ct.data))

    return render_template('interact.html', form=form, client_id=client_id)

@app.route('/data/api/interact/handler/', methods=['GET', 'POST'])
def data_handler():
    client_id = request.args.get('client_id')
    get_data = request.args.get('data')
    return json.dumps({'client_id': client_id, 'data': get_data})

客戶端腳本

handler_url = 'http://192.168.0.102:5000/data/api/interact/handler/'

class check_data(threading.Thread):
    def __init__(self, client_id):
        threading.Thread.__init__(self)
        self.event = threading.Event()
        self.client_id = client_id

    def run(self):
        global handler_url

        try:
            while not self.event.is_set():
                file = urllib2.urlopen(handler_url)
                xml = file.read()
                print xml
                file.close()
        except:
            pass

        self.event.wait(4)

def new_client():
        client_id = 'ClientId' + str(random.randrange(1, 500))
        return client_id

client_id = 'null'

while client_id == 'null':
    client_id = new_client()

    if 'null' not in client_id:
        break

print 'Client ID: ' + client_id

client = check_data(client_id)
client.start()

一切正常,但是如果我將數據從服務器發送到客戶端,它將打印:

{'data': '', 'client_id': null}

在這段代碼中:

@app.route('/data/api/interact/handler', methods=['GET', 'POST'])
def data_handler():
    client_id = request.args.get('client_id')
    get_data = request.args.get('data')
    return json.dumps({'client_id': client_id, 'data': get_data})

您將返回帶有client_iddata值的JSON,這些值是從查詢參數( request.args )獲取的,但不發送這些參數( urllib2.urlopen(handler_url) )。

client_id未傳遞到服務器,服務器希望將client_iddata作為查詢參數。 相反,您訪問的網址沒有任何參數

file = urllib2.urlopen(handler_url)

可以通過以下方式將查詢字符串參數傳遞給GET請求:

url = handler_url + '?client_id' + self.client_id +'&data=YOURDATA_HERE'
file = urllib2.urlopen(url)

您可能可以使用urlencode使其更優雅。

暫無
暫無

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

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