为什么我的数据在 Flask python 中传递到后端时来自 request.form?

Why does my data come from request.form when passing it to the backend in Flask, python?

我一直在努力找出在 Flask 中将数据从前端传递到后端的最佳方式。问题是当在后端接收数据时,数据检索来自 request.form['msg'],这没有意义,因为我并没有真正使用表单,只是一个输入场地。它为什么这样做?有没有更好的方法来检索数据?

这是我的代码。还有一个 index.html 和 <input id='msg'> </input>

jQuery / Javascript:

const message = document.getElementById('msg');

$(document).load('/run', {'msg': message.value}, function(){return 'run complete'})

main.py:

@app.route("/run", methods=["GET", "POST"])
def run():
    if request.method == 'POST':
        msg = request.form["msg"]
        print('msg:', msg)
    return "OK"

我将重新列举我知道从 front-end 传递到后端的内容。

1. request.form["name_of_the_input"]

HTML

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

<input type = "text" name = "name_of_the_input" />

<button type = "submit"> Send Data </button>

</form>

Python

@app.route("/your_url")
def your_function():
    your_variable = request.form["name_of_the_input"]

2。 Ajax/Fetch

JavaScript

  fetch(`${window.origin}/your_url`, {
    method: "POST",
    credentials: "include",
    body: JSON.stringify(your_data),
    cache: "no-cache",
    headers: new Headers({
      "content-type": "application/json"
    })
  })

Python

@app.route("/your_url", methods = ["post"])
def printer():
  data = request.get_json()
  print(data)
  return "hey"

3。 Flask-SocketIO (https://flask-socketio.readthedocs.io/en/latest/)

示例代码

Python

@socketio.on('receiver')
def message_server(msg):
  /* Do something here */

JavaScript

 
/* You need to load socketio, you can look it up at socket.io, the link above also have instructions */
 ​let​ ​socket​ ​=​ ​io​(​) 
  
  
 ​  ​socket​.​emit​(​"receiver"​,​ ​{ 
 ​    ​msg​: ​form​.​value​ /* your data */, 
 ​  ​}​) 
 ​   

4. request.args ()

5.与上述功能相同,但

Python

@app.route("/hello/<your_variable>")
def your_function(variable):
    data = variable
    .... ....

所以当 127.0.0.1:5000/hello/anything_else

data = "anything _else"

这是最简单的方法,希望不要造成混淆,这里给大家看一下代码:

In your routes file main.py

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

@app.route('/render/run', methods=['GET', 'POST'])
def run():
    if request.method == 'POST':
        message = request.form['msg']
         print('msg:', message)
        flash('You notification message OK!')
        return redirect(url_for('render'))    

in your HTML file, postscript use bootstrap ) index.html

 <div class="container-fluid pt-3">
            <form action="{{url_for('run')}}" method="POST">
            <div class="col justify-content-md-center">
            <div class="row pt-3">
                <div class="col pt-3">
                    <label class="form-label">Message: </label>
                </div>
                <div class="col pt-3">
                    <input class="form-control" type="text" name="msg">
                </div>
            </div>
        </div>

       
       
            <div class="container pt-3">
                <div class="row justify-content-md-center">
                  <div class="col col-lg-2">
                   <button class="btn btn-success btn-block rounded">send message</button>
                   
                  </div>
        </div>
            </div>
        </form>
    </div>