Created
November 24, 2016 11:39
-
-
Save pgk/eed4ff661cda0a1b6ca61cf548e7c3bb to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from flask import Flask, request, jsonify | |
from time import sleep | |
def my_uber_func(num): | |
sleep(5) | |
return 3 * num | |
app = Flask(__name__) | |
@app.route("/", methods=('GET', 'POST')) | |
def index(): | |
if request.method == 'POST': | |
# normally you do a bunch of check for csrf, etc | |
# normally you also redirect | |
num = int(request.form.get('number', None)) # sanitize to int | |
if num is not None: | |
result = my_uber_func(num) | |
return jsonify({'result': result}) | |
return None | |
else: | |
# normally a jinja template, | |
# but flask is a microframework for a reason | |
return """ | |
<form id="theform" method="POST"> | |
<input type="number" id="number" name="number" placeholder="enter a number"> | |
<button id="the-form-button" type="submit">Calculate</button> | |
</form> | |
<div id="result"> | |
</div> | |
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script> | |
<script> | |
$(function () { | |
var form = $('#theform'); | |
var result = $('#result'); | |
$('#the-form-button').on('click', function (e) { | |
e.preventDefault(); | |
var val = parseInt($('#number').val(), 10); | |
result.html('Sending...'); | |
$.ajax('/', { | |
method: 'POST', | |
dataType: 'json', | |
data: {number: val}, | |
success: function (data) { | |
result.html('result: ' + data.result) | |
} | |
}); | |
}) | |
}) | |
</script> | |
""" | |
if __name__ == "__main__": | |
app.run(debug=True) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment