私はPythonとFlaskを学んでいます。経験はほとんどありませんが、不可能なことです。通常の AJAX では問題ありませんが、sijax を試してみることにしました。単純な例でさえ機能しません。これは、接続と初期化が正しくないことが原因であると確信しています。公式リポジトリの git ハブから git clone を実行し、すべてが機能したためです。
3つの例では、1ファイルのアプリケーションで動作および初期化されたsijaxを、設計図で使用したい
トレースバックリターンをクリックすると<a href="javascript://"onclick="Sijax.request('say_hi');">Say Hi!</a>
: 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
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>