I've been trying to get this jQuery Flask example found here to work, but for some reason I can't! I've changed the files a bit so they work with how I've set up my Flask application... where the structure of everything is:
~/test
|-- run.py
|__ /venv
|__ /app
|-- __init__.py
|__ /templates
|-- layout.html
|-- index.html
|__ /views
|-- addnumbers.py
With run.py:
from flask_failsafe import failsafe
@failsafe
def create_app():
from app import app
return app
if __name__ == '__main__':
create_app().run(debug=True)
__init__.py:
from flask import Flask, render_template
import os, sys
app = Flask(__name__)
def is_module(path):
init_path = os.path.join(path, '__init__.py')
if os.path.isdir(path) and os.path.exists(init_path):
return True
elif os.path.isfile(path) and os.path.splitext(path)[1] == '.py':
return True
return False
def import_module(name, globals=globals(), locals=locals(),
fromlist=[], level=-1):
__import__(name)
return sys.modules[name]
def register_views(app, path, extension=''):
app_path = os.path.dirname(os.path.abspath(app.root_path))
for filename in os.listdir(path):
file_path = os.path.join(path, filename)
if is_module(file_path):
module_name = os.path.splitext(file_path)[0]
module_name = os.path.relpath(module_name, app_path)
module_name = module_name.replace('/', '.')
blueprint = getattr(import_module(module_name), 'blueprint', None)
if blueprint:
app.register_blueprint(blueprint)
path = os.path.dirname(os.path.abspath(__file__))
register_views(app, os.path.join(path, 'views'))
addnumbers.py
from flask import Flask
from flask import render_template, jsonify, request, Blueprint
blueprint = Blueprint("addnumbers", __name__)
@blueprint.route('/_add_numbers')
def add_numbers():
"""Add two numbers server side, ridiculous but well..."""
a = request.args.get('a', 0, type=int)
b = request.args.get('b', 0, type=int)
return jsonify(result=a + b)
@blueprint.route('/')
def index():
return render_template('index.html')
and layout.html and index.html are taken from the example above. I can see the example fine as shown below, but it just doesn't work and I don't know why. When I click the calculate server side link it doesn't do anything, so instead of adding the two numbers and showing the result it just keeps showing the ?. The console in Chrome gives the following error:
jquery.min.js:4 GET http://localhost:5000/_add_numbers?a=1&b=2 404 (NOT FOUND)
I create the application by running run.py for anyone that wants to try it out.
Aucun commentaire:
Enregistrer un commentaire