(Python)烧瓶-request.args.get返回NoneType [英] (Python) Flask - request.args.get returning NoneType

查看:83
本文介绍了(Python)烧瓶-request.args.get返回NoneType的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要完成的网站是为了从输入中获取 n s 值.但是当执行 request.get.args 时,每次都返回None这是代码:

All I need to complete this website is for it to grab the n and s values from the input. But when executing request.get.args is returning None everytime Here's the code:

my_website.py :

import sqlite3
from flask import Flask,render_template, url_for, redirect, request


app = Flask(__name__)
conn = sqlite3.connect('shoes.db', check_same_thread=False)
c = conn.cursor()

@app.route("/", methods=["GET", "POST"])
def main():

    if request.method == 'GET':
        return render_template('main.html')

    elif request.method == 'POST':
        return redirect(url_for('search'))


@app.route("/search/", methods=["GET", "POST"])
def search():

    if not request.args.get("n"):           
        raise RuntimeError("missing n")

    if not request.args.get("s"):
        raise RuntimeError("missing s")

    name = request.args.get('n')
    size = request.args.get('s')
    c.execute("SELECT * FROM shoes WHERE name LIKE ? AND sizes LIKE ? ORDER BY price",
                    ('%'+name+'%','%'+size+'%'))

    p = c.fetchall()

    url = [p[i][0] for i in range(len(p))]
    names = [p[i][1] for i in range(len(p))]
    prices = [p[i][2] for i in range(len(p))]
    sizes = [p[i][3] for i in range(len(p))]
    shoe_type = [p[i][4] for i in range(len(p))]

    return render_template('search.html' , url=url, names=names, prices=prices,
                           sizes=sizes, shoe_type=shoe_type)


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

main.html :

{% extends "layout.html" %}
{% block content %}

<form action = "{{ url_for('main') }}" class="form" method = "POST" >
    <div>
        <h1>Soccer Shoes Finder</h1>
        <div class="line-separator"></div>
        <div>
            <div class="container-fluid">
                <input name = "n" type="text" placeholder="Name"/>
                <input name = "s" type="text" placeholder="Size"/>
                <button class="glyphicon glyphicon-search" aria-hidden="true"></button>
            </div>
        </div>
</form>

{% endblock %}

这是我得到的错误:

RuntimeError: missing n

任何建议将不胜感激.谢谢.

Any advice would be appreciated. Thanks.

推荐答案

request.args 将值保存在查询字符串中.另一方面,您的表单正在POST正文中发送值.

request.args holds the values in the query string. Your form on the other hand is sending values in the POST body.

使用 request.form 映射,或使用 request.values ,它结合了 request.form request.args .

或者,将表格 method 更改为 GET ,以使浏览器将参数放在查询字符串中.

Alternatively, change your form method to GET to have the browser put the arguments in the query string instead.

这篇关于(Python)烧瓶-request.args.get返回NoneType的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆