我正在学习 Python 和 Flask,我的经验很少,但这是不可能的。用通常的 AJAX 没有任何问题,但我决定试试 sijax,连一个简单的例子都行不通。我确定这是由于连接和初始化不正确,因为我从官方存储库 git hub 做了 git clone,一切正常。
在三个示例中,sijax 在一个文件应用程序中工作和初始化,我想在蓝图中使用
如果我单击<a href="javascript://"onclick="Sijax.request('say_hi');">Say Hi!</a>
Traceback 返回:127.0.0.1 - - [12/Sep/2016 14:19:56] "POST / HTTP/1.1" 400 -
应用程序初始化.py
import os
from flask import (Flask,
redirect,
url_for,
session)
# from flask_login import LoginManager
from flask_wtf.csrf import CsrfProtect
from os import path
from .database import db
from werkzeug.contrib.fixers import ProxyFix
import flask_sijax
import hmac
from hashlib import sha1
def create_app(config=None):
app = Flask(__name__)
app.config.from_object(os.environ['APP_SETTINGS'])
app.wsgi_app = ProxyFix(app.wsgi_app)
db.init_app(app)
app.config["SIJAX_STATIC_PATH"] = os.path.join('.', os.path.dirname(__file__), 'static/js/sijax/')
app.config["SIJAX_JSON_URI"] = '/static/js/sijax/json2.js'
'''
if app.debug == True:
try:
from flask_debugtoolbar import DebugToolbarExtension
toolbar = DebugToolbarExtension(app)
except:
pass
'''
with app.test_request_context():
db.create_all()
from .general import controllers as general
from .shop import controllers as shop
from .test import controllers as test
app.register_blueprint(shop.module)
app.register_blueprint(general.module)
app.register_blueprint(test.module)
flask_sijax.Sijax(app)
CsrfProtect(app)
@app.template_global('csrf_token')
def csrf_token():
"""
Generate a token string from bytes arrays. The token in the session is user
specific.
"""
if "_csrf_token" not in session:
session["_csrf_token"] = os.urandom(128)
return hmac.new(app.secret_key, session["_csrf_token"],
digestmod=sha1).hexdigest()
@app.route('/')
def index():
return redirect(url_for('test.index'))
return app
测试蓝图controllers.py
from flask import (render_template,
Blueprint,
g)
import flask_sijax
module = Blueprint('test',
__name__)
@flask_sijax.route(module, '/')
def index():
def say_hi(obj_response):
obj_response.alert('Hi there!')
if g.sijax.is_sijax_request:
g.sijax.register_callback('say_hi', say_hi)
return g.sijax.process_request()
return render_template('test/hello.html')
模板 hello.html
<!doctype html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script src="{{ url_for('static', filename='js/sijax/sijax.js') }}"></script>
<script src="{{ url_for('static', filename='js/sijax/json2.js') }}"></script>
<script>{{ g.sijax.get_js()|safe }}</script>
</head>
<body>
<a href="javascript://" onclick="Sijax.request('say_hi');">Say Hi!</a>
</body>
</html>