【问题标题】:How to send information from client to server (Flask - python)如何将信息从客户端发送到服务器(Flask - python)
【发布时间】:2014-02-16 03:11:48
【问题描述】:

如何将信息从客户端发送到服务器? 我有点需要通过单击按钮将一些数据从客户端发送到服务器。 基本上,我有这个页面,其中有几个按钮,我想尝试在按下时向服务器发送有关每个按钮的信息(以及有关客户端状态的一些额外信息,但这不是完全必要的)。然后服务器应处理该信息,并将处理后的版本发送给所有连接的客户端。

客户端不刷新至关重要,因为那样我们会丢失 javascript 游戏引擎中的数据,用户将不得不重新开始。

ajax 合适吗?如果是的话,有人可以在 javascript(客户端)和 Flask(服务器端)函数/代码中包含一个简短的通用示例吗?

【问题讨论】:

    标签: javascript jquery python ajax client-server


    【解决方案1】:

    开箱即用,您不能将持久请求或 websockets 与 Flask 之类的东西一起使用。但是,您不一定需要这个 - 您可以使用带有简单轮询机制​​的 AJAX。

    客户端:

    $('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);
    

    服务器端:

    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)
    

    我省略了store_in_cacheretrieve_from_cache 函数,因为这取决于您要如何处理这些消息。它们对所有浏览器客户端都是全局的吗?你想要一个消息队列吗?

    【讨论】:

      猜你喜欢
      • 2017-08-16
      • 2014-05-12
      • 1970-01-01
      • 2018-02-05
      • 2023-03-08
      • 2016-09-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多