一段时间以来,我正在尝试学习如何在Flask中使用Ajax。 在flask的官方网站上有一个示例:</ p>


app = Flask(__ name__)

@ app.route('/ _ add_numbers')
def add_numbers():
     一个= request.args.get('a',0,type = int)
     b = request.args.get('b',0,type = int)
     返回jsonify(result = a + b)

@ app.route('/')
def index():
</ code> </ pre>

对我来说很好。 但是我正在寻找以下程序:</ p>

  1. jQuery代码将初始编号发送到python应用</ li>
  2. python应用程序存储该数字并响应“已收到:[数字]” </ li>
  3. 同时为真:</ code> python应用程序等待请求“增加”,为此请求将数字加1并返回</ li>
    </ ol>

    jQuery部分无关紧要,我可以做到,但是我不确定如何实现python部分:</ p>

      @ app.route('/ _ inc_number')
    def inc_number():
         n = request.args.get('n',0,type = int)
             req = request.args.get('req',0,type = string)
             如果req =='增加':
                 n = n + 1
                 return n#退出函数。 如何不辞而别?
    </ code> </ pre>

    请向我解释如何返回数据? 我也是Ajax和Flask的新手,我怀疑它不是“真正的” Ajax ...是吗? 如何在flask中实现具有相同功能的简单功能?</ p>
         </ div>



For a while now I am trying to learn how to use Ajax with Flask. On the official website of flask there is an example:

from flask import Flask, jsonify, render_template, request
app = Flask(__name__)

def add_numbers():
    a = request.args.get('a', 0, type=int)
    b = request.args.get('b', 0, type=int)
    return jsonify(result=a + b)

def index():
    return render_template('index.html')

It works for me well. But I am looking for the following program:

  1. a jQuery code sends an initial number to the python app
  2. the python app stores the number and responds 'received: [the number]'
  3. while true: the python app waits for requests 'increase' for which it adds 1 to the number and returns it

The jQuery part doesn't matter, I can do that but I am not sure how to implement the python part:

def inc_number():
    n = request.args.get('n', 0, type=int)
    while true:
        req = request.args.get('req', 0, type=string)
        if req == 'increase':
            n = n + 1
            return n #It exits the function. how respond without quit?

Please explain me how I can data back? I am new to both Ajax and Flask too, and I suspect that it is not "real" ajax...Is that right? How would you implement a simple function with the same functionality in flask?


我认为您所缺少的是,每当客户请求增加号码时,都会有一个独立的请求。 您的 inc_number </ code>处理程序的编码如下:</ p>

  @ app.route('/ _ inc_number')
def inc_number():
     n = request.args.get('n',0,type = int)
     n = n + 1
</ code> </ pre>

然后在jQuery端,每次要增加数量时,您都必须调用一个独立的Ajax请求。</ p>

请注意,使用这种解决方案时,jQuery应用程序会跟踪计数器的当前值,并且必须在每次请求时将其发送到Flask。 另一种可能是让Flask一方在用户会话中记住该号码。 对于这种解决方案,您的Flask应用将具有两个视图功能:</ p>



@ app.route('/ set_number')
def set_number():
     session ['n'] = request.args.get('n',0,type = int)

@ app.route('/ inc_number')
def inc_number():
     会话['n'] =会话['n'] + 1
</ code> </ pre>

现在,使用此解决方案,jQuery可以设置编号,而不必每次调用 inc_number </ code>时都发送它。</ p>

我希望这会有所帮助。</ p>
     </ div>



I think what you are missing is that each time the client requests a number increase there is an independent request. Your inc_number handler would be coded as follows:

def inc_number():
    n = request.args.get('n', 0, type=int)
    n = n + 1
    return n

Then from the jQuery side you have to invoke an independent Ajax request each time you want to increase the number.

Note that with this type of solution the jQuery app is the one that keeps track of the current value of the counter, and it has to send it to Flask with each request. Another possibility would be to have the Flask side remember the number in a user session. For that type of solution your Flask app would have two view functions:

from flask import session
# you need to set a SECRET_KEY in configuration, used to sign the user session

def set_number():
    # store n in the user session
    session['n'] = request.args.get('n', 0, type=int)

def inc_number():
    session['n'] = session['n'] + 1
    return session['n']

With this solution now jQuery can set the number and not have to send it every time when it invokes inc_number.

I hope this helps.

HTTP请求没有内存,它们彼此独立。 这意味着当您的Python应用程序收到请求时,它会执行某些操作,立即发送响应并退出。 这就是HTTP的本质。</ p>

如果您希望一些持久的内容(例如您的号码)能够通过更多请求而存在,那么您需要:</ p>

  • 服务器上的永久存储。 它可以是文件,数据库,或者就Flask而言,可以仅仅是内存中的一个对象(变量)。</ li>
  • 在单独的请求之间标识用户。 这就是会话处理和cookie的目的。</ li>
    </ ul>

    一种非常原始的方法(不应在生产系统上使用):</ p>

    • 永久存储:在 main()</ code> </ li>中创建全局字典(称为 num </ code>)
    • index()</ code>中:

      • 创建随机会话标识符( si </ code>)</ li>
      • 设置 num [si] = 0 </ code> </ li>
      • si </ code>发送为cookie </ li>
        </ ul> </ li>
      • inc_number()</ code>中使用cookie中的 si </ code>(由浏览器发送回)来增加适当的 num [si] </ code> </ li >
        </ ul>
             </ div>



HTTP requests don't have a memory, they are independent of each other. It means when your Python app gets a request, it does something, sends a response immediately and quits. That's the nature of HTTP.

If you want something persistent (like your number) that lives through more requests, you need:

  • Persistent storage on the server. It can be a file, a database, or in case of Flask simply an object (variable) in memory.
  • Identify the user between separate requests. That's what session handling and cookies are for.

A very primitive method (shouldn't be used on production system):

  • persistent storage: create a global dict (called num) in main()
  • in index():
    • create a random session identifier (si)
    • set num[si] = 0
    • send si as a cookie
  • in inc_number() use si from cookie (sent back by the browser) to increase the appropriate num[si]

Csdn user default icon