2016-07-21 72 views
0

我在@ 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:被使用了兩次,所以我無法註冊特定於視圖的回調。

是否有解決此問題的方法?謝謝。

回答

1

在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'中的回調函數,則它們不起作用。 –