简体   繁体   English

Method Not Allowed 请求的 URL 不允许该方法

[英]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."我试图在单击后返回随机数列表,但出现错误消息“不允许使用方法 请求的 URL 不允许使用该方法。” I am really new to the flask.我对 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. index.html这里是 HTML 文档。

    <!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>

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.注意:不能将列表作为响应提供给用户,请注意您不能使用jsonify function 作为列表。 use jsonify when you have dictionary .当你有dictionary时使用 jsonify 。

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

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