pythonhtmlajaxflaskjsonify

Method Not Allowed The method is not allowed for the requested URL


I am trying to return a list of the random numbers after click but having an error saying " Method Not Allowed The method is not allowed for the requested URL." I am really new to the flask. following is the code:

main.py

        import flask
        from flask import Flask, render_template, request, jsonify
        import numpy as np
        
        app = Flask(__name__)
        
        p=[]
        @app.route('/')
        def index():
            return render_template('index.html')
        @app.route('/rannum/', methods=['POST'])
        def rannum():
            print("clicked")
            p = []
            p = np.random.randint(100, size=10)
            for i in p:
                print(i)
            return jsonify(p)
        
        
        if __name__ == '__main__':
            app.run(debug=True)
        

index.html here is the HTML doc.

    <!DOCTYPE html>
    <html lang='en'>
       <head>
          <title>Flask App</title>
          <style type="text/css">
             * {
                font-family: sans-serif;
             }
          </style>
       </head>
       <body>
          <h1>random number generation</h1>
          <form method="post" id="form">
             <label >click button</label>
    
             <button>click</button>
          </form>
          <p id="rannum"></p>
          <script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
          <script>
             $.ajax({
    
                url: "{{ url_for( 'rannum' ) }}",
    
                type: "POST",
    
                data: nameArray,
    
                success: function( resp ){
    
                    console.log( resp )
    
                }
    
            })
          </script>
       </body>
    </html>

Solution

  • Simply change your code to this:

            @app.route('/rannum/', methods=['POST'])
            def rannum():
                print("clicked")
                p = []
                p = np.random.randint(100, size=10)
                for i in p:
                    print(i)
                return jsonify({"data": p})
    
    

    Note: a list cannot be given to users as a response, and note that you cannot use jsonify function for a list. use jsonify when you have dictionary.