简体   繁体   English

ajax的python-flask示例

[英]python-flask example for ajax

For a while now I am trying to learn how to use Ajax with Flask. 有一段时间我正在尝试学习如何在Flask中使用Ajax。 On the official website of flask there is an example: 在烧瓶的官方网站上有一个例子:

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

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

@app.route('/')
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 jQuery代码将初始编号发送到python应用程序
  2. the python app stores the number and responds 'received: [the number]' python应用程序存储数字并响应'收到:[数字]'
  3. while true: the python app waits for requests 'increase' for which it adds 1 to the number and returns it while true: python应用程序等待请求'增加',它为数字加1并返回它

The jQuery part doesn't matter, I can do that but I am not sure how to implement the python part: jQuery部分没关系,我可以这样做,但我不知道如何实现python部分:

@app.route('/_inc_number')
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? 我也是Ajax和Flask的新手,我怀疑它不是“真正的”ajax ......是吗? How would you implement a simple function with the same functionality in flask? 如何在烧瓶中实现具有相同功能的简单功能?

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: 您的inc_number处理程序将按如下方式编码:

@app.route('/_inc_number')
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. 然后从jQuery端,每次要增加数量时都必须调用一个独立的Ajax请求。

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. 请注意,对于这种类型的解决方案,jQuery应用程序是跟踪计数器当前值的应用程序,它必须随每个请求将其发送到Flask。 Another possibility would be to have the Flask side remember the number in a user session. 另一种可能性是让Flask端记住用户会话中的号码。 For that type of solution your Flask app would have two view functions: 对于这种类型的解决方案,Flask应用程序将具有两个视图功能:

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

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

@app.route('/inc_number')
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 . 有了这个解决方案,现在jQuery可以设置数字,而不必每次调用inc_number时发送它。

I hope this helps. 我希望这有帮助。

HTTP requests don't have a memory, they are independent of each other. HTTP请求没有内存,它们彼此独立。 It means when your Python app gets a request, it does something, sends a response immediately and quits. 这意味着当您的Python应用程序收到请求时,它会执行某些操作,立即发送响应并退出。 That's the nature of HTTP. 这就是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. 它可以是文件,数据库,或者在Flask中只是内存中的对象(变量)。
  • Identify the user between separate requests. 识别不同请求之间的用户。 That's what session handling and cookies are for. 这就是会话处理和cookie的用途。

A very primitive method (shouldn't be used on production system): 一种非常原始的方法(不应该用于生产系统):

  • persistent storage: create a global dict (called num ) in main() 持久存储:在main()创建一个全局字典(称为num main()
  • in index() : index()
    • create a random session identifier ( si ) 创建随机会话标识符( si
    • set num[si] = 0 set num[si] = 0
    • send si as a cookie 发送si作为cookie
  • in inc_number() use si from cookie (sent back by the browser) to increase the appropriate num[si] inc_number()使用来自cookie的si (由浏览器发回)来增加相应的num[si]

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

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