Home > Software design >  Problem with POST Method on my Flask APP on Python
Problem with POST Method on my Flask APP on Python

Time:10-19

i have a problem with my flask app thaht i'm trying to create, i wrote a POST Method to take arguments from HTTP and write them to a table. here's my code:

from flask import Flask
from flask_restful import Resource, Api, reqparse
import pandas as pd
import ast
import sqlalchemy


# SQLAlchemy connectable
engine = sqlalchemy.create_engine("mssql pymssql://my_connection_string")
conn = engine.connect()

app = Flask(__name__)
api = Api(app)


class Samples(Resource):
    def get(self):
        data = pd.read_sql_table('DBLIST_DATA', engine)
        data = data.to_dict()  # convert dataframe to dict
        return {'data': data}, 200  # return data and 200 OK

    def post(self):
        parser = reqparse.RequestParser()  # initialize
        parser.add_argument('NODE_NO_data', required=True)  # add args
        parser.add_argument('BLOCK_NAME_data', required=True)
        parser.add_argument('BLOCK_TYPE_data', required=True)
        args = parser.parse_args()  # parse arguments to dictionary

        # read our SQL Table
        data = pd.read_sql_table('DBLIST_DATA', engine)

        #Check if Value Exists
        if args['NODE_NO_data'] in list(data['NODE_NO_data']):
            return {
                       'message': f"'{args['NODE_NO_data']}' already exists."
                   }, 409
        else:
            # create new dataframe containing new values
            new_data = pd.DataFrame({
                'NODE_NO_data': [args['NODE_NO_data']],
                'BLOCK_NAME_data': [args['BLOCK_NAME_data']],
                'BLOCK_TYPE_data': [args['BLOCK_TYPE_data']],
                'locations': [[]]
            })
            # add the newly provided values
            data = data.append(new_data, ignore_index=True)
            data.to_sql('DBLIST_DATA', index=False)  # save back to SQL Table
            return {'data': data.to_dict()}, 200  # return data with 200 OK

api.add_resource(Samples, '/samples')  # add endpoints

if __name__ == '__main__':
    app.run()  # run app

when i try to POST via Postman the following values:

127.0.0.1:5000/samples/?NODE_NO_data=1&BLOCK_NAME_data=Machine&BLOCK_TYPE_data=Vertical

i'm getting a 404 not found error.

can someone please tell me what i'm doing wrong?

Thanks!

CodePudding user response:

You could just remove the last / of your request URL http://127.0.0.1:5000/samples.

  • Related