URL 参数管理(Python Flask)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12871153/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 12:03:48  来源:igfitidea点击:

Managing parameters of URL (Python Flask)

pythonflask

提问by namit

I want some search feature in my website. In the output page, I am getting all the results in single page. However, I want to distribute it to many pages (i.e. 100 searches/page). For that, I am passing a number of default searches in "urlfor" but it isn't working. I know I am making a small error but I am not catching it.

我想在我的网站上使用一些搜索功能。在输出页面中,我在单个页面中获得所有结果。但是,我想将它分发到许多页面(即 100 个搜索/页面)。为此,我在“urlfor”中传递了一些默认搜索,但它不起作用。我知道我犯了一个小错误,但我没有抓住它。

Here is my code below:

这是我的代码如下:

@app.route('/', methods=['GET', 'POST'])
def doSearch():
    entries=None
    error=None
    if request.method=='POST':
        if request.form['labelname']:
            return redirect(url_for('show_results',results1='0-100', labelname=request.form['labelname'] ))
        else:
            error='Please enter any label to do search'
    return render_template('index.html',entries=entries, error=error)




@app.route('/my_search/<labelname>')
def show_results(labelname=None, resultcount=None, results1=None):
    if not session.get('user_id'):
        flash('You need to log-in to do any search!')
        return redirect(url_for('login'))

    else:
        time1=time()
        if resultcount is None:
            total_count=g.db.execute(query_builder_count(tablename='my_data',nametomatch=labelname, isextension=True)).fetchall()[0][0]

        limit_factor=" limit %s ,%s"%(results1.split('-')[0],results1.split('-')[1])

        nk1=g.db.execute(query_builder(tablename='my_data',nametomatch=labelname, isextension=True) + limit_factor)
        time2=time()
        entries=[]
        maxx_count=None
        for rows in nk1:
            if maxx_count is None:
                maxx_count=int(rows[0])
            entries.append({"xmlname":rows[1],'xmlid':rows[2],"labeltext":rows[12]})
        return render_template('output.html', labelname=labelname,entries=entries, resultcount=total_count, time1=time2-time1, current_output=len(entries))

Here I want output on the URL like "http://127.0.0.1:5000/my_search/assets?results1=0-100" Also, if I edit the url address in browser like I want the next 100 result I can get it on "http://127.0.0.1:5000/my_search/assets?results1=100-100"

在这里,我想对喜欢的URL输出“ http://127.0.0.1:5000/my_search/assets?results1=0-100”另外,如果我在编辑浏览器的URL地址就像我想接下来的100结果,我可以得到它“ http://127.0.0.1:5000/my_search/assets?results1=100-100

Note: here I am using sqlite as backend; so I will use "limit_factor" in my queries to limit my results. And "query_builder" and "query_builder_count" are just simple functions that are generating complex sql queries.

注意:这里我使用 sqlite 作为后端;所以我将limit_factor在我的查询中使用“ ”来限制我的结果。而“ query_builder”和“ query_builder_count”只是生成复杂sql查询的简单函数。

but the error I am getting is "NoneType" can't have split. It stopped at "limit_factor".

但我得到的错误是“NoneType”不能拆分。它停在"limit_factor"

Here limit factor is just one filter that I have applied; but I want to apply more filters, for example i want to search by its location "http://127.0.0.1:5000/my_search/assets?results1=0-100&location=asia"

这里的限制因子只是我应用的一个过滤器;但我想应用更多过滤器,例如我想按其位置搜索“ http://127.0.0.1:5000/my_search/assets?results1=0-100&location=asia

采纳答案by Luká? Lalinsky

Function parameters are mapped only to the route variables. That means in your case, the show_resultsfunction should have only one parameter and that's labelname. You don't even have to default it to None, because it always has to be set (otherwise the route won't match).

函数参数仅映射到路由变量。这意味着在您的情况下,该show_results函数应该只有一个参数,即labelname. 您甚至不必将其默认为None,因为它始终必须设置(否则路由将不匹配)。

In order to get the query parameters, use flask.request.args:

为了获取查询参数,请使用flask.request.args

from flask import request

@app.route('/my_search/<labelname>')
def show_results(labelname=None):
    results1 = request.args.get('results1', '0-100')
    ...

Btw, you better not construct your SQL the way you do, use placeholders and variables. Your code is vulnerable to SQL injection. You can't trust any input that comes from the user.

顺便说一句,你最好不要像你那样构造你的 SQL,使用占位符和变量。您的代码容易受到SQL 注入的影响。您不能相信来自用户的任何输入。

The correct way to do this depends on the actual database, but for example if you use MySQL, you would do this (not that I'm not using the %operator):

执行此操作的正确方法取决于实际数据库,但例如,如果您使用 MySQL,您将执行此操作(不是我没有使用%运算符):

sql = ".... LIMIT %s, %s"
g.db.execute(sql, (limit_offset, limit_count))