I'm new to programming and I started a Flask project. I have encountered a problem.
I've managed to display information from an API with one endpoint and render it using Flask. For the next partm I have to display information with several endpoints.
This is the code I managed to render, it looks ugly but it works.
def home():
page = request.args.get('page', 1, type=int)
posts = Post.query.order_by(Post.date_posted.desc()).paginate(page=page, per_page=5)
oficial = requests.get('https://api-dolar-argentina.herokuapp.com/api/dolaroficial')
blue = requests.get('https://api-dolar-argentina.herokuapp.com/api/dolarblue')
dataoficial = json.loads(oficial.content)
datablue = json.loads(blue.content)
return render_template('home.html', posts=posts, data=dataoficial, datablue=datablue)
For my next page, I have to do the same with multiples endpoint on the API. This is the script for reference of what I want:
symbol = ['dolaroficial', 'dolarblue', 'contadoliqui', 'dolarpromedio', 'dolarturista','dolarbolsa']
for i in symbol:
api_url = f'https://api-dolar-argentina.herokuapp.com/api/{i}'
data = requests.get(api_url).json()
print(f' {i}: precio de venta', {data['venta']})
print(f' {i}: precio de compra', {data['compra']})
I tried to do something like this to see if I can loop through all endpoints, but it won't render anything:
def argentina():
symbol = ['dolaroficial', 'dolarblue', 'contadoliqui', 'dolarpromedio', 'dolarturista', ' dolarbolsa']
for i in symbol:
api_url = f'https://api-dolar-argentina.herokuapp.com/api/{i}'
datasa = requests.get(api_url)
data = json.loads(datasa.content)
return render_template('currency.html', data=data )
{% extends 'layout.html' %}
{% block content %}
<div>
{% for dat in data %}
{{ dat['compra'] }}
{% endfor %}
</div>
{% endblock content %}
If I do it manually, it will look very bad.
Can someone show me the path to display it?
You have an extra space in the last item of symbol, it's causing the API to respond with 404 status. ' dolarbolsa' should be replace with 'dolarbolsa'. That should fix the JSONDecodeError error (you need to find a way to handle errors in the API).
Then you will display only one price. That's because you are saving the dollar price in a variable instead of an array, and returning the template in the first run of the loop.
You should create a new array after symbol, fill it inside the loop, and then render it after the loop.
def argentina():
symbol = ['dolaroficial', 'dolarblue', 'contadoliqui', 'dolarpromedio', 'dolarturista', 'dolarbolsa']
data = []
for i in symbol:
api_url = f'https://api-dolar-argentina.herokuapp.com/api/{i}'
datasa = requests.get(api_url)
content = json.loads(datasa.content)
data.append(content)
return render_template('currency.html', data=data)