i'm trying to get my python script below working as a dynamic web application that uses a HTML form for users to type in a certain carpark number which would then return the information about the number of lots available for that given carpark based on a Government-Website's API.
Python Script:
import requests
import json
# Do the HTTP get request
response = requests.get("https://api.data.gov.sg/v1/transport/carpark-availability")
jack = response.json()
daniel = jack['items'][0]["carpark_data"]
for d in daniel:
if d["carpark_number"] == carpark_No:
print("\nFor Carpark No. " + carpark_No + ":\n")
print(d["carpark_info"])
I want the variable "carpark_No" to be a user_inputted value from a HTML Form.
E.g. If i set "carpark_No" to be "HG55", my output from this script will be:
For Carpark No. HG55:
[ { 'total_lots': '82' , 'lot_type': 'C', 'lots_available': '79'} ]
However, this python script is completely terminal based as you may have guessed. I want this to work as a dynamic web app that allows users to return carpark lot information from an API. I researched into Flask and managed to get the following working on localhost.
Main Flask App:
from flask import Flask, render_template, request
app = Flask(__name__)
@app.route('/')
def student():
return render_template('student.html')
@app.route('/result',methods = ['POST', 'GET'])
def result():
if request.method == 'POST':
result = request.form
return render_template("result.html",result = result)
if __name__ == '__main__':
app.run(debug = True)
Flask App1: # after starting python script above and opening localhost:5000 on browser. (student.html)
<!doctype html>
<html>
<body>
<form action = "http://localhost:5000/result" method = "POST">
<p>Carpark No: <input type = "text" name = "Carpark" /></p>
<p><input type = "submit" value = "submit" /></p>
</form>
</body>
</html>
Flask App2: (result.html)
<!doctype html>
<html>
<body>
<table border = 1>
{% for key, value in result.items() %}
<tr>
<th> {{ key }} </th>
<td> {{ value }} </td>
</tr>
{% endfor %}
</table>
</body>
</html>
The problem with the flask scripts above is that I can plug in my values of "Carpark_No" as "HG55" and it perfectly returns me the data in a table but that's not what I want.
I would like to change my Main Flask App script in a way that will enable the final page at "/results" to be a rendered page of the Python Script I had going for me at the start.
In other words, I would like to use the data from my form submission in student.html and plug it into my first Python Script so I would get an output like this:
For Carpark No. HG55: # should be dynamic data that can be changed from student.html or Flask App 1
[ { 'total_lots': '82' , 'lot_type': 'C', 'lots_available': '79'} ]
However, I haven't the faintest idea of where to start, could someone point me in the right direction?