Last active
August 4, 2023 03:55
-
-
Save mentix02/6d8a3764373520589e9c2249962e4a52 to your computer and use it in GitHub Desktop.
This file contains hidden or 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, render_template, request, jsonify | |
app = Flask(__name__) | |
@app.route("/") | |
def home(): | |
return render_template("index.html") | |
@app.route("/square/", methods=["POST"]) | |
def square(): | |
try: | |
n = int(request.form.get("n", 0)) | |
except ValueError: | |
return jsonify({"error": "provide a valid number for n"}), 400 | |
return jsonify({"n_squared": str(n * n)}) |
This file contains hidden or 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
<h2>Arbitrarily Precise Square Calculator</h2> | |
<form id="squareForm"> | |
<label for="n">number: </label> | |
<input type="number" name="n" id="n"> | |
<button type="submit">submit</button> | |
</form> | |
<label for="result">result: </label> | |
<input placeholder="result" type="number" id="result" readonly> | |
<script> | |
const numEl = document.querySelector("#n"); | |
const resultEl = document.querySelector("#result"); | |
const squareForm = document.querySelector("#squareForm"); | |
const handleSubmit = async function(e) { | |
e.preventDefault(); | |
const payload = new FormData(); | |
payload.set("n", numEl.value); | |
const resp = await fetch("/square/", { | |
method: "POST", | |
body: payload, | |
}); | |
if (!resp.ok) alert("something went wrong!"); | |
else { | |
const data = await resp.json(); | |
resultEl.value = data.n_squared; | |
} | |
}; | |
squareForm.addEventListener("submit", handleSubmit); | |
</script> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment