python - Flask/HTML 问题:来自 html 中输入文本框的请求在哪里到达 Flask 中的 app.route?
问题描述
一般来说,我是烧瓶和网络编程的新手。我正在尝试一个简单的例子。我有一个显示文本框和动物图片的 HTML 基本模板。模板由烧瓶渲染。这个想法是,用户可以在文本框中键入新动物的名称,然后图片会更改为新动物。
我测试了代码。有一个问题 - html 文本框中给出的输入文本似乎没有转到正确的 app.route。或者至少我无法弄清楚(因为我在 pythonanywhere 上运行并且服务器中的打印语句没有显示在控制台上)。
这是代码和模板。请让我知道我做错了什么。谢谢!
这是flask_app.py:
from flask import render_template
from flask import request, redirect
from flask import Flask
app = Flask(__name__)
@app.route('/')
def index():
imgname = "tiger2.png"
return render_template('untitled1.html', title='TIGER', fname=imgname)
@app.route('/', methods=['POST', 'GET'])
def imgshow(animal):
#assert request.method == 'POST'
#print("New request!")
animal = request.form['animal']
if animal.lower() == 'tiger':
imgname = 'tiger2.png'
elif animal.lower() == 'lion':
imgname = 'lion1.png'
elif animal.lower() == 'panther':
imgname = 'panther.png'
else:
imgname = 'lion1.png'
return render_template('untitled1.html', title=animal.upper(), fname=imgname)
这是模板 untitled1.html
<!DOCTYPE html>
<html>
<head>
<title>{{ title }}</title>
</head>
<body>
<!-- Serving an Image -->
<h1>Hello, World!</h1>
<form action="">
<label for="animal">Animal: </label>
<input type="text" id="animal" name="animal"><br><br>
</form>
<img src="{{ url_for('static', filename=fname ) }}" alt="Tiger">
</body>
</html>
解决方案
对我来说,最好的方法是只使用 GET 方法:
from flask import Flask, render_template, request, redirect
app = Flask(__name__)
animals = {'tiger': 'tiger2.png', \
'lion': 'lion1.png', \
'panther': 'panther.png'}
@app.route('/')
def index():
animal = request.args.get('animal', 'tiger')
image = animals.get(animal, 'lion')
return render_template('untitled1.html', title=animal.upper(), fname=image)
当您需要进行一些处理(从数据库写入数据)然后重定向到另一个 GET 路由时,POST 方法是最好的。
推荐阅读
- python - Python:递归生成器跳过值
- sql - Postgresql 错误:列必须出现在 GROUP BY 子句中或在聚合函数中使用
- haskell - 如何在数据列表上使用 GHC Generics 或 Data.Data 以合并特定条件的字段?
- python - 如何在 Pandas 数据框中的“日期”列中的每个元素中减去 n 个季度以创建新列?
- python - 熊猫根据下面列的值移动列
- node.js - 如何使用 node-fetch 发送原始请求?
- r - 无法在 CentOS 7.8.2003 上的 R 3.6.0 上安装 psych 软件包
- async-await - 如何在计划库中使用等待?
- wordpress - 在 wp_mail 标头中设置回复地址
- python - 将多维数组的每个子数组的最后一项放入列表