简体   繁体   English

如何将信息从客户端发送到服务器(Flask-python)

[英]How to send information from client to server (Flask - python)

How do you send information from a client to a server? 您如何将信息从客户端发送到服务器? I kinda need to send some data from the client to server on a button click. 我有点需要通过单击按钮将一些数据从客户端发送到服务器。 Basically, I have this page where there are a couple of buttons, and I want to try to send information about each button (and some extra information about the status of the client, but that's not exactly necessary) to the server when it's pressed. 基本上,我在此页面上有几个按钮,并且我想尝试在按下按钮时将有关每个按钮的信息(以及有关客户端状态的一些额外信息,但这不是完全必要)发送到服务器。 The server should then process that information, and send a processed version to all connected clients. 然后,服务器应处理该信息,并将已处理的版本发送给所有连接的客户端。

It's crucial that the client does not refresh because then we would lose the data in the javascript game engine, and the user would have to start over. 客户端不刷新至关重要,因为这样我们将丢失javascript游戏引擎中的数据,并且用户将不得不重新开始。

Would ajax be appropriate? 阿贾克斯合适吗? If it is, can someone include a short, generic example both with the javascript (client side) and Flask (server side) functions / code ? 如果是这样,有人可以在javascript(客户端)和Flask(服务器端)函数/代码中都包含一个简短的通用示例吗?

Out of the box, you can't use persistent requests or websockets with something like Flask. 开箱即用,您不能将持续性请求或websocket与Flask等一起使用。 However, you don't necessarily need this - you can use AJAX with a simple polling mechanism. 但是,您不一定需要这样做-您可以将AJAX与简单的轮询机制一起使用。

Client side: 客户端:

$('button').click(function() {
    var state = $(this).attr('data-state');

    $.post('/clients/', { state: state });
});

// Check for messages every 1 second
var checkDelay = 1000;
var lastMessageSeen = new Date().getTime();

setInterval(function() {
    $.get('/clients/', function(result) {
        if(result.ready and result.timestamp > lastMessageSeen) {
            lastMessageSeen = result.timestamp;
            console.log('Message received: ' + result.msg);
        }
    });
}, checkDelay);

Server side: 服务器端:

from flask import request, jsonify

@app.route('/clients/', methods=['POST'])
def client_broadcast():
    state = request.form['state']

    # here you can store the message under a key in Memcached, Redis or another in-memory cache server
    store_in_cache(state)

    return jsonify(stored=True)

@app.route('/clients/', methods=['GET'])
def client_retrieve():
    # retrieve messages from cache
    msg, timestamp = retrieve_from_cache()

    if msg:
        return jsonify(ready=True, msg=msg, timestamp=timestamp)
    else:
        return jsonify(ready=False)

I've left out the store_in_cache and retrieve_from_cache functions, because it depends on how you want to handle these messages. 我省略了store_in_cacheretrieve_from_cache函数,因为它取决于您如何处理这些消息。 Are they global to all browser clients? 它们对所有浏览器客户端都是全局的吗? Do you want to have a queue of messages? 您是否要排队留言?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM