简体   繁体   English

对 Flask 的字符串 POST 请求

[英]String POST Request to Flask

I'm trying to implement a simple dashboard with Flask that will:我正在尝试使用Flask实现一个简单的仪表板,它将:

  1. Accept a user text input, with a "submit" button.接受用户文本输入,带有“提交”按钮。 POST this user input to flask.将此用户输入发布到烧瓶。
  2. Flask accepts this input, does some stuff to it, then makes a GET request to another API. Flask 接受这个输入,对它做一些事情,然后向另一个 API 发出 GET 请求。
  3. This GET request returns data and shows it somehow (can just be console.log for now)这个 GET 请求返回数据并以某种方式显示它(现在可以只是console.log

As an example, with the star wars API:例如,使用星球大战 API:

  1. User inputs name of a Star Wars character (assume no spelling errors)用户输入星球大战角色的名字(假设没有拼写错误)
  2. Flask reads this input name, and maps it to an ID number, because the Star Wars API accepts id numbers. Flask 读取此输入名称,并将其映射到 ID 号,因为Star Wars API接受 ID 号。 Form a GET request to the Star Wars API, to get full character information.向 Star Wars API 发送 GET 请求,以获取完整的角色信息。
  3. For now, we can just console.log character information (eg "height", "mass", etc.)现在,我们可以只使用console.log字符信息(例如“高度”、“质量”等)

What I have now:我现在所拥有的:

app.py应用程序

from flask import Flask, jsonify, request, render_template
import random
import json

app = Flask(__name__)


@app.route("/")
def index():
    return render_template('index.html')


@app.route("/form_example", methods=["GET", "POST"])
def form_example():
    if request.method == "POST":
        language = request.form("character_name")
        starwars_dictionary = {"Luke Skywalker":"1", "C-3PO":"2", "R2-D2": "3"}
        # starwars_dictionary is a dictionary with character_name:character_number key-value pairs.
        # GET URL is of the form https://swapi.co/api/people/<character_number>

    return render_template("index.html")


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

index.html索引.html

<!DOCTYPE html>
<html>
<head>
    <title>py-to-JS</title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
</head>
<body>
    <h3>Sample Inputs</h3>
    <ul>
        <li>Luke Skywalker</li>
        <li>C-3PO</li>
        <li>R2-D2</li>
    </ul>

    <form method="POST">
        Enter Name: <input type="text" name="character_name"><br>
        <input type="submit" value="Submit"><br>
    </form>
</body>
</html>

In this current form, when I run the app, it returns "Method not allowed; this method is not allowed for the requested URL".在当前的表单中,当我运行应用程序时,它返回“不允许的方法;请求的 URL 不允许使用此方法”。

I'm not sure what I'm missing;我不确定我错过了什么; it's probably just not wired together properly but I'm not sure what the proper syntax is.它可能只是没有正确连接在一起,但我不确定正确的语法是什么。


Working version after implementing the accepted answer:实施接受的答案后的工作版本:

app.py应用程序

from flask import Flask, jsonify, request, render_template
import requests
import random
import json

app = Flask(__name__)


@app.route("/index", methods=["GET", "POST"])
def index():
    #character_height = "" # init a default value of empty string...seems unwieldy
    if request.method == "POST":
        character_name = request.form.get("character_name")

        # Map user input to a numbers
        starwars_dictionary = {"Luke Skywalker":"1", "C-3PO":"2", "R2-D2": "3"}
        char_id = starwars_dictionary[character_name]

        url = "https://swapi.co/api/people/"+char_id
        response = requests.get(url)
        response_dict = json.loads(response.text)
        character_height = response_dict["height"]

        return render_template("index.html", character_height=character_height)

    return render_template("index.html")

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


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

index.html索引.html

<!DOCTYPE html>
<html>
<head>
    <title>py-to-JS</title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
</head>
<body>
    <h3>Sample Inputs</h3>
    <ul>
        <li>Luke Skywalker</li>
        <li>C-3PO</li>
        <li>R2-D2</li>
    </ul>

    <form method="POST" action="/index">
        Enter Name: <input type="text" name="character_name"><br>
        <input type="submit" value="Submit"><br>
    </form>

    {{ character_height }}
</body>
</html>

Probably the form is posting to the / endpoint, because you didn't declare a form action .可能表单正在发布到/端点,因为您没有声明表单action

Needs to be more like:需要更像:

<form method="POST" action="/form_example">

Or if you want to get snazzy and use Jinja's url_for function:或者,如果你想变得时髦并使用 Jinja 的url_for函数:

<form method="POST" action="{{ url_for('form_example') }}">

EDIT: That said, you could handle this with a single route function:编辑:也就是说,您可以使用单个路由功能处理此问题:

@app.route("/", methods=["GET", "POST"])
def index():
    if request.method == "POST":
        language = request.form("character_name")
        starwars_dictionary = {"Luke Skywalker":"1", "C-3PO":"2", "R2-D2": "3"}

        # Logic to query remote API ges here.

    else: # Assume method is GET
        return render_template("index.html")

Then make the form action {{ url_for('index') }}然后使表单动作{{ url_for('index') }}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM