Flask Sijax处理回调@申请前申请

2024-10-16 20:44:03 发布

您现在位置:Python中文网/ 问答频道 /正文

我有回拨电话@申请前申请在我的烧瓶申请。在

@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:被使用了两次,所以我无法注册特定于视图的回调。在

有没有解决这个问题的方法?谢谢。在


Tags: register视图appmessageif烧瓶isresponse
1条回答
网友
1楼 · 发布于 2024-10-16 20:44:03

在after\u 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)   

相关问题 更多 >