Issue
greetings from argentina, I'm new in programming and I started a flask project, but i encounter a problem, I'm managed to display information from an api with one endpoint and render using flask, and for my next part I have to display information with several endpoints
This is the code I managed to render, 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 try to do something like this to see if I can loop through all endpoints ,but it wont 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? To anyone reading this thanks in advance and have a nice day
Solution
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)
Answered By - Ulian
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.