weixin_33730836 2013-08-26 13:29 采纳率: 0%
浏览 54

ajax的python烧瓶示例

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__)

@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
  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:

@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? How would you implement a simple function with the same functionality in flask?

  • 写回答

2条回答 默认 最新

  • weixin_33747129 2013-08-26 14:44
    关注

    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]
    评论

报告相同问题?

悬赏问题

  • ¥15 我想在一个软件里添加一个优惠弹窗,应该怎么写代码
  • ¥15 fluent的在模拟压强时使用希望得到一些建议
  • ¥15 STM32驱动继电器
  • ¥15 Windows server update services
  • ¥15 关于#c语言#的问题:我现在在做一个墨水屏设计,2.9英寸的小屏怎么换4.2英寸大屏
  • ¥15 模糊pid与pid仿真结果几乎一样
  • ¥15 java的GUI的运用
  • ¥15 Web.config连不上数据库
  • ¥15 我想付费需要AKM公司DSP开发资料及相关开发。
  • ¥15 怎么配置广告联盟瀑布流