0

我在我的 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 请求出现在我的应用程序的每个页面上。这很好用,直到我想要一个特定于页面的回调,即在视图if g.sijax.is_sijax_request:中使用 Sijax 定义 AJAX 请求,因为使用了两次,所以我无法注册特定于视图的回调。

这个问题有解决方法吗?谢谢。

4

1 回答 1

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)   
于 2016-07-25T14:52:37.863 回答