python - flask jquery GET 404 -
i'm playing jquery in flask , have been making use of simple example found on runnable of adding 2 numbers together.
i'm using flask-appbuilder , have view setup display template, works fine. included jquery code template , displays should.
on flask side created view, , functions in view render template , receive variables in jquery request.
when click jquery link on template add 2 number together, see 404 error in python console.
[07/apr/2017 09:48:53] "get /_add_numbers?a=1&b=1 http/1.1" 404 -
here's have in template:
{% extends "appbuilder/base.html" %} {% block content %} <script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script> <link href="//netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css" rel="stylesheet"> <script type=text/javascript> $(function() { $('a#calculate').bind('click', function() { $.getjson('/_add_numbers', { a: $('input[name="a"]').val(), b: $('input[name="b"]').val() }, function(data) { $("#result").text(data.result); }); return false; }); }); </script> <body> <div class="container"> <div class="header"> <h3 class="text-muted">how manage json requests</h3> </div> <hr/> <div> <p> <input type="text" size="5" name="a"> + <input type="text" size="5" name="b"> = <span id="result">?</span> <p><a href="javascript:void();" id="calculate">calculate server side</a> </form> </div> </div> </body> </html> {% endblock %}
my flask view looks this:
class myview(baseview): default_view = 'sale' @expose('/sale', methods=['get']) @has_access def sale(self): return self.render_template('sale.html') @expose('/_add_numbers', methods=['get', 'post']) @has_access def add_numbers(self): = request.args.get('a', 0, type=int) b = request.args.get('b', 0, type=int) return jsonify(result=a + b)
any guidance appreciated.
get screenshot - https://imgur.com/a/0rxin
post screenshot - http://imgur.com/ns1beke
you using flask-appbuilder , syntax suggested is:
class myview(baseview): route_base = "/myview" @expose('/method1/<string:param1>') def method1(self, param1): # param1 # , return return param1
which results in url looking this: http://<your_host>/myview/method1/<awaiting string param>
that interferes url.
a bit more thorough explanation:
get request tries locate /_add_numbers?a=1&b=1
url far back-end concerned not match exposed url.
should try defining exposed url follows:
@expose('/_add_numbers?<int:a>&<int:b>', methods=['get', 'post'])
if flask-appbuilder
gives problems, try experiment default flask , see if works you, knowledge move forward.
note:
typically not get post request.
you can try simple jquery $.post()
call instead of getjson
:
$.post('http://localhost:5000/_add_numbers',{ a: $('input[name="a"]').val(), b: $('input[name="b"]').val() }, function(data) { $("#result").text(data.result); });
the no 'access-control-allow-origin' header present on requested resource.
error has been referred , answered thoroughly in posts:
Comments
Post a Comment