从API获取数据并在temp上显示

2024-04-26 11:11:58 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图从stackoverflow API获取数据,并将它们显示在模板的html表中。你知道吗

到目前为止,我已经成功地获得了数据,但无法在模板中显示它们。我最后得到了最后一个。我知道我的循环是错误的,我尝试了很多东西,但似乎无法解决它。你知道吗

到目前为止我的代码是:

def get_questions(request):
    context = {}
    r = requests.get('https://api.stackexchange.com/2.2/questions?fromdate=1525737600&order=desc&sort=activity&tagged=python&site=stackoverflow').json()
    for item in r['items']:
        context['owner'] = item['owner']['display_name']
        context['title'] = item['title']
        #some other attrs here

    template = 'questions/questions_list.html'
    context['greeting'] = 'Hello'

    return render(request,template,context)

我的模板代码: 我还没做什么花哨的事。很简单。你知道吗

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <link href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-WskhaSGFgHYWDcbwN70/dfYBj47jz9qbsMId/iRN3ewGhXQFZCSftd1LZCfmhktB" crossorigin="anonymous">
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/js/bootstrap.min.js" integrity="sha384-smHYKdLADwkXOn1EmN1qk/HfnUcbVRZyYmZ4qpPea6sjB/pTJ0euyQp0Mk8ck+5T" crossorigin="anonymous"></script>

    <title>Questions</title>
</head>
<body>
    {{ owner }} - {{ title }}
</body>
</html>

Tags: 代码httpscom模板gettitlerequesthtml
1条回答
网友
1楼 · 发布于 2024-04-26 11:11:58

您需要将结果附加到列表中,并在模板中呈现该列表。你知道吗

演示:你知道吗视图.py

def get_questions(request):
    context = {}
    r = requests.get('https://api.stackexchange.com/2.2/questions?fromdate=1525737600&order=desc&sort=activity&tagged=python&site=stackoverflow').json()
    dataList = []
    for item in r['items']:
        dataList.append({'owner': item['owner']['display_name'], 'title': item['title']})
        #some other attrs here

    template = 'questions/questions_list.html'
    context['greeting'] = 'Hello'
    context['data'] = dataList

    return render(request,template,context)

模板迭代结果并获取所有数据

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <link href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-WskhaSGFgHYWDcbwN70/dfYBj47jz9qbsMId/iRN3ewGhXQFZCSftd1LZCfmhktB" crossorigin="anonymous">
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/js/bootstrap.min.js" integrity="sha384-smHYKdLADwkXOn1EmN1qk/HfnUcbVRZyYmZ4qpPea6sjB/pTJ0euyQp0Mk8ck+5T" crossorigin="anonymous"></script>

    <title>Questions</title>
</head>
<body>
    {% for i in data %}
        {{ i.owner }} - {{ i.title }}
    {% endfor %}
</body>
</html>

相关问题 更多 >