首页 > 解决方案 > 问题:使用 Flask 时,从函数创建的全局变量不会在 HTML 模板中呈现

问题描述

我编写了一个函数,调用该函数时使用漂亮的汤从网站收集信息并将项目保存在两个列表变量中。我已将这些变量设为全局变量,但是我无法使用 render_template() 将它们传递给烧瓶。

首先我创建了我的函数。我在下面包含了所有漂亮的汤代码,它会抓取数据并将其放入列表中,但重要的部分是我的函数在底部两行“全局数据”和 data = list(zipped) 中创建的全局变量:

def beautiful():

    image=[]
    price=[]

    my_url = str('https://www.websitewithproducts.com/for-sale/')+str(location)
    uClient= uReq(my_url)
    page_html=uClient.read()
    uClient.close()
    
    #parse page
    page_soup = soup(page_html, "html.parser")
    
    #grabs each product 
    containers = page_soup.findAll("div", {"class":"results-wrapper"})
    container= containers[0]

    for container in containers:
    #images
        try:
            image_container=container.find("a",{"class":"photo-hover"})
            image_place=image_container.img["data-src"]
            image.append(image_place)
        except TypeError:
            continue
        #prices
        try:
            price_container=container.find("a",{"class":"results-price"})
            price_place=price_container.text.strip()
            price.append(price_place)
        except TypeError:
            continue
        
    
    zipped = zip(image, price)
    global data
    data = list(zipped)

接下来,我创建了我的 Flask 应用程序,它在客户端向网站发布帖子时调用该函数:

app=Flask(__name__)
@app.route('/test', methods=['GET', 'POST'])
def search_products():

    if request.method == "POST":
        area = request.form['search']
        beautiful()
    return render_template('test.html', data= data)

if __name__ == '__main__':
    app.run(debug=True)

当我运行我的代码并在浏览器中打开时,它给了我 NameError: name 'data' is not defined。我的html代码是:

<body>
    <div class = "form">
        <form method='post'>
            <input type = "text" name = "search" placeholder="Search">
            <input type = "submit">
        </form>
    </div>
    
    <div class="results">
        {% for image in data %}
        <div class = "image">
            <img src = {{image}}>
        </div>
    </div>
</body>

我认为问题是我试图在 Flask 中传递的数据变量未被识别为我在 beautiful() 函数中创建的全局变量。但是,我不知道为什么。帮助将不胜感激!

标签: pythonflaskglobal-variableslocal-variables

解决方案


您忘记将结果分配给beautiful()变量。

代替

app=Flask(__name__)
@app.route('/test', methods=['GET', 'POST'])
def search_products():

    if request.method == "POST":
        area = request.form['search']
        beautiful()
    return render_template('test.html', data= data)

尝试

app=Flask(__name__)
@app.route('/test', methods=['GET', 'POST'])
def search_products():

    if request.method == "POST":
        area = request.form['search']
        data = beautiful()
        return render_template('test.html', data=data, area=area)
    return # whatever you want to show when there is no search, e.g. the search form

因此,您需要确保通过在搜索表单中使用 post 来触发搜索。

PS:不需要使用全局变量


推荐阅读