我正在学习Python和Flask,我的经验很少,但这是不可能的。 与通常的AJAX没有任何问题,但我决定尝试sijax,甚至一个简单的例子都行不通。我确定这是由于错误的连接和初始化,因为我从官方存储库git hub做了git clone,一切正常。
在三个例子中,sijax在单文件应用程序中工作和初始化,我想在蓝图中使用
如果我点击<a href="javascript://"onclick="Sijax.request('say_hi');">Say Hi!</a>
回溯:127.0.0.1 - - [12 / Sep / 2016 14:19:56]&#34; POST / HTTP / 1.1&#34; 400 -
app init .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
测试blueprint 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>
答案 0 :(得分:0)
原因是没有使用sijax,事实是{{csrf_token()}}不活跃
有必要这样做:<a href="javascript://" onclick="Sijax.request('say_hi', { data: { csrf_token: '{{ csrf_token() }}' } });">Say Hi!</a>
连接到html文件:
<script type="text/javascript">
var csrfToken = "{{ csrf_token() }}"
</script>