Search code examples
pythonpython-server-pages

Python 3.7 TypeError: missing 1 required positional argument: 'input'


I have already finished my function, but when I run the webserver I get the following error:

TypeError : index() missing 1 required positional argument:'input'

This is my code:

from sklearn import tree
from flask import Flask

app = Flask(__name__)

@app.route('/', methods=['GET','POST'])
def index(input):
    input = [[1,1,2,3,3,1,1,2]]

    data = pd.read_csv('datawadek.csv')
    y = data.KELAS
    x = data.drop('KELAS', axis = 1)

    cart = tree.DecisionTreeClassifier()

    cart = cart.fit(x,y)

    return cart.predict(input)

if __name__ == '__main__':
    app.run(debug=True)

I am very new to python programming. Please help me with any suggestions or solutions.

Have a nice day


Solution

  • I assume that you want to pass input as a parameter in flask. You cannot define the input as parameters to your flask's endpoint function. Instead, you should read the parameters inside the said function with request.args.get like this:

    @app.route('/', methods=['GET','POST'])
    def index():
        input = request.args.get('input')
        if input is None:
            input = [[1,1,2,3,3,1,1,2]]
    

    From python docs:

    The request object is automatically reachable from all flask api's and it contains all the data that you are passing through the api. To access incoming request data, you can use the global request object. Flask parses incoming request data for you and gives you access to it through that global object. Internally Flask makes sure that you always get the correct data for the active thread if you are in a multithreaded environment.

    EDIT:

    In the comments we had a similar example with path parameter:

    @app.route('/<input>', methods=['GET','POST'])
    def index(input):
    

    the final result will be identical to my initial answer above, but it less practical from design standpoint. You would be using a post method to pass an array of data and in this case, the data should come inside a request.

    Another reason to not do it is that you should also always avoid passing an array as a path parameter unless