首页 > 编程问答 >Flask 应用程序在路线中搜索的结果返回上一个

Flask 应用程序在路线中搜索的结果返回上一个

时间:2024-07-21 12:25:11浏览次数:6  
标签:python flask search

我很长一段时间都无法处理它。
当我在地址 - http://127.0.0.1:5000/search?key=mySearch 中尝试第二个搜索 (mySecondSearch) 时,它会返回上一个搜索 (mySearch)

(但查询有效 - 我获取带有键 mySecondSearch 的列表的模板)

如何获取带有与我的请求相关的键的地址

header.html

<form method="POST" action="{{ url_for('views.search', key=slugy) }}" role="search" class="hiddenSearch">

{{ search_form.hidden_tag() }}
<input class="form-control" type="search" 
                            placeholder="" 
                            aria-label="Search"   
                            name="searched" 
                            minlength="3" 
                            maxlength="44" 
                            oninvalid="this.setCustomValidity('')" 
                            oninput="this.setCustomValidity('')" 
                            title=""/>
</form>

view.py

@views.route('/search/', methods=["POST"])
def search():
    page_title = ""
    clean = re.compile('<.*?>')
    search_form = SearchForm()
    posts = Poems.query

    if request.method == "POST" and search_form.validate_on_submit():
        # Get Data from submitted form
        searched = search_form.searched.data
        poem_list.searched = searched
        slugy = slugify(searched)

        # Query 
        page = request.args.get('page', 1, type=int)
        posts = posts.filter(Poems.con_keyword.ilike('%' + searched + '%'))
        posts = posts.order_by(Poems.title).paginate(per_page=7, page=page, error_out=True)

        return render_template("content/search.html", 
                       search_form=search_form, 
                       searched=searched, 
                       page_title=page_title,
                       posts=posts, 
                       clean=clean, re=re, slugy=slugy)

    else:
    flash("!")
    return render_template("content/search.html", 
                           search_form=search_form, 
                           page_title=page_title, 
                           posts=posts, clean=clean, re=re)

search.html| ||我尝试删除缓存,或不保存任何数据,-什么都没有

<section id="search">

    <div class="content">
        {% if searched %}
         <h1> you ask -
            <span class="src-ed">{{ searched[0:12] }}...</span><br/>we found:
        </h1>

...etc

测试-一切都完美地返回一些东西
人工智能-没有什么可以帮助我(我尝试了它的代码-与我的一样工作)
AI - nothing that can help me (I tried its code - works as mine)


问题在于的表单操作 URL。在其中硬编码了 key=slugy slugy 是在 上一次搜索 期间设置的。这就是为什么始终会看到上一次搜索结果的原因。

为了解决这个问题,需要从表单操作 URL 中删除 key=slugy 部分。Flask 会自动将搜索词作为查询参数传递给的视图函数。

以下是更新后的代码:

header.html:

<form method="POST" action="{{ url_for('views.search') }}" role="search" class="hiddenSearch">
    {{ search_form.hidden_tag() }}
    <input class="form-control" type="search" 
        placeholder="" 
        aria-label="Search"   
        name="searched" 
        minlength="3" 
        maxlength="44" 
        oninvalid="this.setCustomValidity('')" 
        oninput="this.setCustomValidity('')" 
        title=""/>
</form>

不需要在 url_for() 函数中传递 key 参数。Flask 会自动将表单数据作为请求的一部分发送。

views.py:

@views.route('/search/', methods=["POST"])
def search():
    # ... 其他代码 ...

    if request.method == "POST" and search_form.validate_on_submit():
        # ... 其他代码 ...

        # 不再需要手动设置 slugy,因为它将作为查询参数传递
        # slugy = slugify(searched)

        # ... 其他代码 ...

    else:
        # ... 其他代码 ...

通过这些更改,的搜索功能应该可以正常工作,并且每次搜索都会返回正确的结果。

标签:python,flask,search
From: 78759501

相关文章

  • 【Dison夏令营 Day 25】用Python写个2048
    在本文中,我们将用python代码和逻辑来设计一款你经常在智能手机上玩的2048游戏。如果您对该游戏不熟悉,强烈建议您先玩一下该游戏,以便了解其基本功能。如何玩2048.NET?1.有一个4*4的网格,可以填入任何数字。一开始,随机填入两个2的单元格。其余单元格为空。我们......
  • python入门基础——新手必看
    前言随着人工智能,大数据的发展。python是当前时代最流行,可以在数据处理、web开发、人工智能等多个领域。它的语法简洁、开发效率高、可移植性强,并且可以和其他变成语言(比如C++)轻松衔接,本文主要讲述一些python的变量,基本数据类型,输入、输出,数据类型的转换,运算符等一些必需的......
  • python中逗号运算符的含义
    我理解了python中逗号运算符的简单概念。例如,x0,sigma=0,0.1表示x0=0,sigma=0.1。但我获得了一个代码,其中有一行如下所示。y,xe=np.histogram(np.random.normal(x0,sigma,1000))其中y和xe的输出如下。yOut[10]:array([3,17,58,136,216,25......
  • 【科大讯飞笔试题汇总】2024-07-20-科大讯飞秋招提前批(研发岗)-三语言题解(Cpp/Java/
    ......
  • Python - Pandas - loc vs iloc (DataFrame.loc[:,['column_name':]])
    原文链接:https://blog.csdn.net/weixin_48964486/article/details/123150832————————————————————————————————————————————————关于python数据分析常用库pandas中的DataFrame的loc和iloc取数据基本方法总结归纳及示例如下:1.......
  • 在 Python 中将 2 列的数据框转换为一系列 2 列
    我正在尝试处理一些时间序列数据,并且对pandas数据框相当陌生。我有一个包含两列的数据框,如下所示:+---+-----------------------+-------+--+||0|1||+---+-----------------------+-------+--+|1|2018-08-0223:00:00|456.8||......
  • 基于python的非平稳时间序列模型
    前言平稳时间序列指的是宽平稳时间序列,就是指时间序列的均值、方差和协方差等一二阶矩存在但不随时间改变,表现为时间的常数。若三个条件有一个不成立,那么就称该序列为非平稳时间序列。包括确定性趋势时间序列和随机性趋势时间序列。要想把非平稳的时间序列转化为平稳的时......
  • 猫头虎 Python知识点分享:pandas--read_csv()用法详解
    ......
  • 使用 Python 绘图
    我有一个.txt文件,从中找到有序对,然后使用numpy和matplotlib绘制图形。例如,这些是我的有序对:[[(4.0,0),(0,6.0)],[(6.0,0),(0,3.0)]](每个子列表代表最终图形中的一条线)图形如下所示:但我想找到两条线之间的交点。如果有更多的线,我怎样才能找到它们......
  • 用python计算形状的距离
    我想计算该图像的最小垂直距离和最大水平距离。就像线条一样。我正在尝试:_,binary_image=cv2.threshold(image,0,255,cv2.THRESH_BINARY)horizontal_distances=np.sum(binary_image==255,axis=1)max_horizontal_distance=np.max(horizontal_distance......