I have processed the data retrieved from some API in a flask route, extracted the json needed and then stored it in a dictionary. Now, how do I make the processed data appear in a new HTML? Is it a good way to preprocess the data in a flask function, what if the preprocess takes a lot of steps?
Flask python code x.py
:
@app.route('/test', methods = ['GET'])
def get_from_api():
url = "https://xxxx"
API_KEY = "xxxx"
params = {
'token' : API_KEY
}
response = requests.get(url, params).json()
city = response['city']
state = response['region']
postal = response['postal']
conutry = response['country']
location = response['loc']
data = {
"city" : city,
"state" : state,
"postal" : postal,
"country" : conutry,
"location" : location
}
Next is the x.html
for displaying the data
<div class = "element_val">
<li><div id = "city">null</div></li>
<li><div id = "state">null</div></li>
...
<li><div id = "location">null</div></li>
</div>
How to retrieve the data in flask and put the data in html, and make the html be rendered in '/test'
?
CodePudding user response:
@app.route('/test')
def test_route():
user_details = {
'name': 'John',
'email': '[email protected]'
}
return render_template('test.html', user=user_details)
<!DOCTYPE html>
<html>
<head>
<title>test</title>
</head>
<body>
<!-- use {{}} to access the render_template vars-->
<p>{{user.name}}</p>
<p>{{user.email}}</p>
</body>
</html>