gpt4 book ai didi

python - (Python) Flask - request.args.get 返回 NoneType

转载 作者:太空宇宙 更新时间:2023-11-03 15:34:00 24 4
gpt4 key购买 nike

完成该网站所需的只是从输入中获取 ns 值。但是当执行 request.get.args 每次都返回 None代码如下:

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

如有任何建议,我们将不胜感激。谢谢。

最佳答案

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

使用request.form mapping相反,或使用 request.values ,它结合了 request.formrequest.args

或者,将表单 method 更改为 GET,让浏览器将参数放入查询字符串中。

关于python - (Python) Flask - request.args.get 返回 NoneType,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42687067/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com