Omegastick
Omegastick

Reputation: 1901

Can't set methods in add_url_rule

I'm trying to wrap my Flask server in a class, so as to better fit in the structure of the rest of my application.

I have the below code:

class HTTPServer(object):
    def __init__(self):
        self.app = Flask(__name__)
        self.app.add_url_rule('/', 'index', self.hello_world, methods=['POST'])
        self.app.run(port=5050, use_reloader=False)

    def hello_world(self, data):
        print "Hello, World: {}".format(data)

However, if I send a POST request to localhost:5050/index I get a 404 error.

The Flask log shows the following:

127.0.0.1 - - [30/Aug/2019 11:17:52] "POST /index HTTP/1.1" 404 -

The same happens if I change ['POST'] to ['GET'] in methods and send a GET request.

However, if I remove the methods parameter from add_url_rule() entirely, I can send GET requests and they are handled appropriately.

Upvotes: 1

Views: 1652

Answers (1)

Omegastick
Omegastick

Reputation: 1901

I didn't understand the endpoint parameter of add_url_rule. It isn't the endpoint as seen by the client, but rather an internal name for the endpoint. The correct method call is:

self.app.add_url_rule('/index', 'hello_world', self.hello_world, methods=['POST'])

Upvotes: 2

Related Questions