How to render Flask Web App with Javascript [duplicate]

2024/10/6 20:32:54

Edit: Hi I've checked the duplicates of this question, they do not ask about SPA (client vs server rendering)

I am trying to change my Flask Web App to be rendered client-side in JS instead of server-side with Jinja templating. An interviewer told me that the problem with my Flask Web App, is that the Application server usually only should be serving pure Json APIs and not try to render any existing static content (example the website content that doesn't change, the theme, css, logos, pictures etc), since it'll be a waste of the computing resources of the application server.

With regards to my web app, what it does is it makes calls to 2 different APIs and returns you carpark availability lots based on a user input(e.g your place of residence)

I've done some research into using AJAX with Flask. It seems using XMLHttpRequest based off https://developer.mozilla.org/en-US/docs/Web/Guide/AJAX/Getting_Started is the way to go. Based off my limited understanding, if implemented correctly, would it be possible to switch my web app into one that essentially replicates the functionality of a SPA? (no page refreshes, client-side rendering)

Currently struggling with the implementation, any help would be great!

A .py script below

# one of Four routes in my "Main" Flask Script
@app.route('/address',methods = ['POST', 'GET'])
def address1():if request.method == 'POST':desired_CP_Address = request.form["address"]response = requests.get("https://data.gov.sg/api/action/datastore_search?resource_id=139a3035-e624-4f56-b63f-89ae28d4ae4c&q=" + desired_CP_Address)r = response.json()CP_Info = r['result']['records']return render_template("address1.html", text=CP_Info)

A snippet of the resulting html page

<body>
<h1>carpark.py</h1><!-- if invalid input display bottom -->
{% if text %}   <h3>Click on your desired carpark number</h3>
<hr>{% for x in text %}<p>{{ x["address"] }} : <strong><a href="">{{ x["car_park_no"] }}</a></strong> </p>{% endfor %}
Answer

if you want to make an spa, you can host the spa html/js in a html file. then you serve the json in the /address route

@app.route('/address',methods = ['POST', 'GET'])
def address1():if request.method == 'POST':desired_CP_Address = request.form["address"]response = requests.get("https://data.gov.sg/api/action/datastore_search?resource_id=139a3035-e624-4f56-b63f-89ae28d4ae4c&q=" + desired_CP_Address)r = response.json()return jsonify(r['result']['records'])@app.route('/spa',methods = ['GET'])
def spa():return render_template('spa.html')

now, your spa.html can use javascript xhr to query the json from /address (cfr https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch ), eg.

<script>fetch('/address', {method: "POST", // *GET, POST, PUT, DELETE, etc.mode: "cors", // no-cors, cors, *same-origincache: "no-cache", // *default, no-cache, reload, force-cache, only-if-cachedcredentials: "same-origin", // include, same-origin, *omitheaders: {"Content-Type": "application/json; charset=utf-8",// "Content-Type": "application/x-www-form-urlencoded",},redirect: "follow", // manual, *follow, errorreferrer: "no-referrer", // no-referrer, *clientbody: JSON.stringify(data), // body data type must match "Content-Type" header
}).then(function(response) {return response.json();}).then(function(myJson) {console.log(JSON.stringify(myJson));});
</script>

I'd suggest you use a framework for the javascript frontend (eg. react) instead of writing everything from scratch.

https://en.xdnf.cn/q/118909.html

Related Q&A

Use start and stop function with same button in Tkinter

With the help of the command button, I am able to disconnect the frame in Tkinter. But is there any way which helps to use the same button to start also?import tkinter as tk counter = 0 def counter_la…

How to restrict my students to dont access teacher area in django? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.Want to improve this question? Update the question so it focuses on one problem only by editing this post.Closed 4…

invert edge values in python boolean list

I have a list of booleans likel = [False, False, False, True, True, True, False, False, True, False, False]and want to invert every edge value that is False like[True, True, True, True, True, True, Fal…

Unable to write text on mouseclick area on Image

I am trying to draw text on Image where the user clicks. Getting this error:Exception in Tkinter callback Traceback (most recent call last):File "C:\Users\Admin\AppData\Local\Programs\Python\Pytho…

Google Cloud Storage: __init__() got an unexpected keyword argument total_size

I am developping a tool to transcribe interviews for a contract I have. For that I develop a code with the following flow:After input validation, the audio file (in m4a) is converted to wav and stored …

Selenium, Intercept HTTP Request?

Using selenium 4.12 in Python, how can I intercept an HTTP request to see what its body or headers look like? Please Note, that Im not asking for code but rather for resources/ideas of different or su…

Flask server returns 404 on localhost:5000 w/ Twilio

Im following this guide (Python Quickstart: Replying to SMS and MMS Messages) to try and set up a flask server, but when I try to connect to http://localhost:5000 I get a 404 error. I can ping 127.0.0.…

printing values and keys from a dictionary in a specific format (python)

I have this dictionary (name and grade):d1 = {a: 1, b: 2, c: 3}and I have to print it like this:|a | 1 | C | |b | 2 | B | |c | 3 | …

stdscr.getstr() ignore keys, just string

I just need convert entered text(bytes) to string. But if i on cyrillic press Backspace and some character, python throw me this error:UnicodeDecodeError: utf-8 codec cant decode byte 0xd0 in position …

What is wrong with the following program code, attempting to initialize a 4 x 4 matrix of integers?

What is wrong with the following program code, attempting to initialize a 4 x 4 matrix of integers? How should the initialization be done?line = [0] * 4 matrix = [line, line, line, line]