首页 > 解决方案 > 如何从 api 调用获取有关我的 html 页面的信息

问题描述

我正在尝试通过对 coinmarketcap.com 的 api 调用在我的 html 页面上显示信息。我让用户在上一页中放置一个加密货币的名称,发送一个包含该信息的表单,然后在我的视图中使用它来打印到控制台。我将如何在我的 html 页面上使用这些信息来显示它。

主文件

from requests import Request, Session
from requests.exceptions import ConnectionError, Timeout, TooManyRedirects
import json



    def cryptoLookup(coin):
        url = 'https://pro-api.coinmarketcap.com/v1/cryptocurrency/info'
        parameters = {
            'slug': coin
        }
        headers = {
            'Accepts': 'application/json',
            'X-CMC_PRO_API_KEY': '',
        }
    
        session = Session()
        session.headers.update(headers)
    
        try:
            response = session.get(url, params=parameters)
            data = json.loads(response.text)
            print(data)
        except (ConnectionError, Timeout, TooManyRedirects) as e:
            print(e)

主页.html

<h1>home</h1>
<form action="{% url 'coin' %}" method="POST">
    {% csrf_token %}
    <h1>Which coin would you like to lookup?</h1>
    <input id='coin-lookup' name='coin-lookup' type="text">
    <input type="submit">
</form>
enter code here

视图.py

def coin(request):
    if request.method == 'POST':
        coin = request.POST.get('coin-lookup')
        cryptoLookup(coin)
    return render(request, 'app/coin.html')

标签: pythonhtml

解决方案


推荐阅读