首页 > 解决方案 > 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>

标签: pythonflask

解决方案


对我来说,最好的方法是只使用 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 方法是最好的。


推荐阅读