在@瓶Sijax处理回调app.before_request

问题描述:

我在@ app.before_request回调在我的瓶的应用程序。在@瓶Sijax处理回调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:被使用了两次,所以我无法注册特定于视图的回调。

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

在after_request事件中注册您的默认回调,并检查_callback字典是否为空,如果是,请在现有响应上注册默认回调else通过。

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) 
+0

该解决方案完美的作品,除了注册的所有回调执行两次,因为如果'g.sijax.is_sijax_request:...返回g.sijax.process_request()'使用了两次。有没有办法解决这个问题? –

+0

我更新了代码。 – pjcunningham

+0

谢谢,我只是实现了你的代码,视图中的回调工作。但是,如果在请求的视图中也存在回调时使用'@ app.after_request'中的回调函数,则它们不起作用。 –