分配前引用的变量 'html':UnboundLocalError

Variable 'html' referenced before assigned: UnboundLocalError

这段代码之前可以正常运行并在网站上输出了我想要的内容,但是后来出现了这个错误

from django.shortcuts import render
import json

def get_html_content(fplid):
    import requests
    API_KEY = "eb9f22abb3158b83c5b1b7f03c325c65"
    url = 'https://fantasy.premierleague.com/api/entry/{fplid}/event/30/picks/'

    payload = {'api_key': API_KEY, 'url': url}
    for _ in range(3):
        try:
            response = requests.get('http://api.scraperapi.com/', params= payload)
            if response.status_code in [200, 404]:
                break
        except requests.exceptions.ConnectionError:
            response = ''
    #userdata = json.loads(response.text)
    return response.text

def home(request):
    if 'fplid' in request.GET:
        fplid = request.GET.get('fplid')
        html = get_html_content(fplid)
    return render(request, 'scrape/home.html', {'fpldata': html})

这是我的 views.py 文件。我想我之前分配了 html ,但我不确定它在呈现之前是如何引用的。我为许多 ip 地址添加了 scraperapi,因为我想我可能被 api 禁止了。我不确定发生了什么。

<body>
    <h1>Enter Your FPL id </h1>
    <form method="GET">
        <label for="fplid"> </label>
        <input type="text", name="fplid", id="fplid"> <br>
        <input type="submit" value="Submit" />
    </form>

    <h3> {{fpldata}}</h3>
</body>

如果相关,这是 home.html 文件的一部分

当您最初加载页面时,可能不会初始化 ?fplid=xx。如果不存在,则不会为变量赋值。

您可以使用 html = None 或此初始化变量:

def home(request):
    if 'fplid' in request.GET: # <- when this isnt true
        fplid = request.GET.get('fplid')
        html = get_html_content(fplid)
        return render(request, 'scrape/home.html', {'fpldata': html})
    return render(request, 'scrape/home.html')