I am trying to do something which I think is quite simple however I am a Flask newbie so I was hoping that someone could point me in the right direction.
I am making a Python Flask application for a user to manage their share portfolio.
I need to fetch share information from the yahoo finance server and render this on a page, however fetching this data can take a few seconds at which point the page is blank until the GET requests have been received at which point the page renders.
I want to load the page without the share data and then once the data has been received generate some HTML and insert this HTML into my page.
I have written a route that fetches all of the data and passes it to a Jinja2 template
@app.route('/sharedata')
def sharedata():
js = share_data.getalljsonshares(current_user.username)
io = StringIO()
data= json.dumps(js, io)
return render_template('sharedata.html', data=share_data.getalljsonshares(current_user.username))
I then use the following code in sharedata.html to render the HTML
{% if data %}
<h2>You own the following shares</h2>
{% for share in data %}
<li>
Ticker: {{share.symbol}}<br>
Name: {{share.name}}<br>
Quantity: {{share.quantity}} <br>
Price: {{share['price']}}
</li>
{% endfor %}
{% endif %}
Which results in the following page being rendered
You own the following shares
Ticker: AAPL
Name: APPLE inc
Quantity: 1
Price: 102.71
I want to know how I can automatically insert this HTML into my template, I am sure that I need to use AJAX and JQuery but I am at a bit of a loss as to how I can directly insert HTML into my page once the GET requests have completed. Thanks
Flask sends form data to template Flask to send form data to the template we have seen that http method can be specified in the URL rule. Form data received by the trigger function can be collected in the form of a dictionary object and forwarded to the template to render it on the corresponding web page.
In this article, I will show how to use AJAX with Flask, a Python framework, to receive and display the values entered in a form asynchronously. I added the source code that we need at the end of the article.
html template file in a directory called templates inside your flask_app directory. Flask looks for templates in the templates directory, which is called templates , so the name is important. Make sure you're inside the flask_app directory and run the following command to create the templates directory: mkdir templates.
You have to use JavaScript. With jQuery this is a simple task.
In your main.html
you have to write something like that:
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
</head>
<body>
<div id="result"></div>
<script>
$.on('ready', function() {
$('#result').load('/sharedata')
})
</script>
</body>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With