Search code examples
pythonjqueryflaskrequest.form

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


I've been trying to figure out the best way to pass data from frontend to backend in Flask. The problem is that when receiving data on the back end, the data retrieval came from the request.form['msg'], which doesn't make sense since I didn't really use a form, just an input field. Why did it do this? Is there a better way to retrieve data?

Here's my code. There's also an index.html with <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"

Solution

  • I'll just reenumerate what I know to pass from front-end to backend.

    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/)

    Example code

    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 (Flask request.args.get get all params (Python))

    5. Same functionality as above but

    Python

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

    So when 127.0.0.1:5000/hello/anything_else

    data = "anything _else"