问题:使用Flask

问题描述

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

首先,我创建了我的函数。我已经在下面包含了所有漂亮的汤代码,这些代码对数据进行爬网并将其放入列表中,但是重要的部分是我的函数在最下面两行“全局数据”和data = list(压缩)中创建的全局变量:>

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:未定义名称“数据”。我的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()函数中创建的全局变量。但是,我不知道为什么。帮助将不胜感激!

解决方法

您忘记将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','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

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

P.S .:无需使用全局变量