Flask Sijax在@ app.before_request中处理回调

时间:2016-07-21 23:32:13

标签: python ajax flask sijax

我在Flask应用程序中的@ app.before_request中有回调。

@app.before_request
def before_request():

  def alert(response):
    response.alert('Message')

  if g.sijax.is_sijax_request:
    g.sijax.register_callback('alert', alert)
    return g.sijax.process_request()

我之所以这样,是因为我的应用程序中的每个页面都存在Ajax请求。这很好用,直到我想要一个特定于页面的回调,即在视图中用Sijax定义一个AJAX请求,因为if g.sijax.is_sijax_request:被使用了两次,所以我无法注册特定于视图的回调。

此问题是否有解决方法?感谢。

1 个答案:

答案 0 :(得分:1)

在after_request事件中注册默认回调并检查_callback字典是否为空,如果是,则注册默认回调,否则传递现有响应。

import os
from flask import Flask, g, render_template_string
import flask_sijax

path = os.path.join('.', os.path.dirname(__file__), 'static/js/sijax/')

app = Flask(__name__)
app.config['SIJAX_STATIC_PATH'] = path
app.config['SIJAX_JSON_URI'] = '/static/js/sijax/json2.js'

flask_sijax.Sijax(app)


@app.after_request
def after_request(response):

    def alert(obj_response):
        print 'Message from standard callback'
        obj_response.alert('Message from standard callback')

    if g.sijax.is_sijax_request:
        if not g.sijax._sijax._callbacks:
            g.sijax.register_callback('alert', alert)
            return g.sijax.process_request()
        else:
            return response
    else:
        return response

_index_html = '''
<html>
<head>
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js"></script>
    <script type="text/javascript" src="/static/js/sijax/sijax.js"></script>
    <script type="text/javascript"> {{ g.sijax.get_js()|safe }}</script>
</head>
<body>
    <a href="javascript://" onclick="Sijax.request('alert');">Click here</a>
</body>
</html>
'''

_hello_html = '''
<html>
<head>
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js"></script>
    <script type="text/javascript" src="/static/js/sijax/sijax.js"></script>
    <script type="text/javascript"> {{ g.sijax.get_js()|safe }}</script>
</head>
<body>
    <a href="javascript://" onclick="Sijax.request('say_hi');">Click here</a>
</body>
</html>
'''


@app.route('/')
def index():
    return render_template_string(_index_html)


@flask_sijax.route(app, '/hello')
def hello():
    def say_hi(obj_response):
        print 'Message from hello callback'
        obj_response.alert('Hi there from hello callback!')

    if g.sijax.is_sijax_request:
        g.sijax._sijax._callbacks = {}
        g.sijax.register_callback('say_hi', say_hi)
        return g.sijax.process_request()

    return render_template_string(_hello_html)


if __name__ == '__main__':
    app.run(port=7777, debug=True)