简体   繁体   中英

How to properly map user defined methods to GET/POST HTTP calls in Python Flask?

I am new to Python-Flask and trying to implement APIs in it. To do that, I have created two APIs which will receive the values and then display the values. Code:

from flask import Flask, jsonify, request
from flask_restful import Resource, Api, reqparse

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

vehicles = []

class VehicleData(Resource):

    parser = reqparse.RequestParser()
    parser.add_argument('vehicle', type=str, required=True, help='name cannot be empty')
    parser.add_argument('type', type=str, required=True, help='vehicle type cannot be empty')
    parser.add_argument('wheels', type=int, required=True, help='number of wheels cannot be empty')
    parser.add_argument('suv', type=bool, required=False, help='SUV or not can be empty')

    def get(self, name):
        vehicle = list(filter(lambda x: x['name'] == name, vehicles), None)
        return {'vehicle': vehicle}, 200 if vehicle else 404

    def post(self, name):
        # data = request.get_json()
        # sport.append({'sportname': data['sport_name'], 'team_size':data['team_size'], 'popularity':data['popularity']})
        if next(filter(lambda x: x['name'] == name, vehicles), None) is not None:
            print("in the IF BLOCK")
            return {'message': 'The vehicel {n} already exists in the database'.format(n=name)}, 404

        v_data = VehicleData.parser.parse_args()
        vehicle = {'name': name, 'type':v_data['type'],  'vehicle': v_data['vehicle'], 'suv': v_data['suv'], 'wheels': v_data['wheels']}
        vehicles.append(vehicle)
        return vehicle, 201

    def getallvehicles(self):
        return {'vehicles': vehicles}


api.add_resource(VehicleData, '/addvehicle/<string:name>', '/getvehicle/<string:name>', '/getallvehicles')
app.run(port=5000, debug=True)

Api Calls:

http://127.0.0.1:5000/addvehicle/polo
http://127.0.0.1:5000/getvehicle/polo
http://127.0.0.1:5000/getallvehicles

The calls to the methods POST and GET are working fine which can be seen in the image. 在此处输入图像描述

But when I run the third API which gives me all the entries of the list: vehicles , the code is giving an error saying it needs an argument name .

Traceback (most recent call last):
  File "/Users/bobby/PyCharmProjects/FlaskAPI/venv/lib/python3.7/site-packages/flask/app.py", line 2464, in __call__
    return self.wsgi_app(environ, start_response)
  File "/Users/bobby/PyCharmProjects/FlaskAPI/venv/lib/python3.7/site-packages/flask/app.py", line 2450, in wsgi_app
    response = self.handle_exception(e)
  File "/Users/bobby/PyCharmProjects/FlaskAPI/venv/lib/python3.7/site-packages/flask_restful/__init__.py", line 272, in error_router
    return original_handler(e)
  File "/Users/bobby/PyCharmProjects/FlaskAPI/venv/lib/python3.7/site-packages/flask/app.py", line 1867, in handle_exception
    reraise(exc_type, exc_value, tb)
  File "/Users/bobby/PyCharmProjects/FlaskAPI/venv/lib/python3.7/site-packages/flask/_compat.py", line 38, in reraise
    raise value.with_traceback(tb)
  File "/Users/bobby/PyCharmProjects/FlaskAPI/venv/lib/python3.7/site-packages/flask/app.py", line 2447, in wsgi_app
    response = self.full_dispatch_request()
  File "/Users/bobby/PyCharmProjects/FlaskAPI/venv/lib/python3.7/site-packages/flask/app.py", line 1952, in full_dispatch_request
    rv = self.handle_user_exception(e)
  File "/Users/bobby/PyCharmProjects/FlaskAPI/venv/lib/python3.7/site-packages/flask_restful/__init__.py", line 272, in error_router
    return original_handler(e)
  File "/Users/bobby/PyCharmProjects/FlaskAPI/venv/lib/python3.7/site-packages/flask/app.py", line 1821, in handle_user_exception
    reraise(exc_type, exc_value, tb)
  File "/Users/bobby/PyCharmProjects/FlaskAPI/venv/lib/python3.7/site-packages/flask/_compat.py", line 38, in reraise
    raise value.with_traceback(tb)
  File "/Users/bobby/PyCharmProjects/FlaskAPI/venv/lib/python3.7/site-packages/flask/app.py", line 1950, in full_dispatch_request
    rv = self.dispatch_request()
  File "/Users/bobby/PyCharmProjects/FlaskAPI/venv/lib/python3.7/site-packages/flask/app.py", line 1936, in dispatch_request
    return self.view_functions[rule.endpoint](**req.view_args)
  File "/Users/bobby/PyCharmProjects/FlaskAPI/venv/lib/python3.7/site-packages/flask_restful/__init__.py", line 468, in wrapper
    resp = resource(*args, **kwargs)
  File "/Users/bobby/PyCharmProjects/FlaskAPI/venv/lib/python3.7/site-packages/flask/views.py", line 89, in view
    return self.dispatch_request(*args, **kwargs)
  File "/Users/bobby/PyCharmProjects/FlaskAPI/venv/lib/python3.7/site-packages/flask_restful/__init__.py", line 583, in dispatch_request
    resp = meth(*args, **kwargs)
TypeError: get() missing 1 required positional argument: 'name'

I understand that the GET call is invoking get() in the code and not getallvehicles() . Is it because getallvehicles is a user defined method? If so, could anyone let me know how to map a user defined method to GET or POST or any corresponding call. In this case, how can I map getallvehicles to GET http call?

Approach 1: I can add an extra class to the existing code & register in my API to return all the data from the list: vehicles

class GetAllVehicles(Resource):
    
    def get(self):
        return {'vehicles': vehicles}

api.add_resource(GetAllVehicles, '/getallvehicles')

How can I achieve the same functionality without using an extra class in the code and map GET to getallvehicles()

Not exactly what you requested, but I would use a keyword 'all' as a possible input for getting all the vehicle data in the API.

class VehicleData(Resource):

    parser = reqparse.RequestParser()
    parser.add_argument('vehicle', type=str, required=True, help='name cannot be empty')
    parser.add_argument('type', type=str, required=True, help='vehicle type cannot be empty')
    parser.add_argument('wheels', type=int, required=True, help='number of wheels cannot be empty')
    parser.add_argument('suv', type=bool, required=False, help='SUV or not can be empty')

    def get(self, name):
        if name == 'all': # return all vehicles if 'all' keyword is passed
            return {'vehicles': vehicles}
        else:
            vehicle = list(filter(lambda x: x['name'] == name, vehicles), None)
            return {'vehicle': vehicle}, 200 if vehicle else 404

    def post(self, name):
        # data = request.get_json()
        # sport.append({'sportname': data['sport_name'], 'team_size':data['team_size'], 'popularity':data['popularity']})
        if next(filter(lambda x: x['name'] == name, vehicles), None) is not None:
            print("in the IF BLOCK")
            return {'message': 'The vehicle {n} already exists in the database'.format(n=name)}, 404
        elif name == 'all': # prevent adding a vehicle named 'all'
            return {'message': 'Invalid vehicle name'}, 404

        v_data = VehicleData.parser.parse_args()
        vehicle = {'name': name, 'type':v_data['type'],  'vehicle': v_data['vehicle'], 'suv': v_data['suv'], 'wheels': v_data['wheels']}
        vehicles.append(vehicle)
        return vehicle, 201

api.add_resource(VehicleData, '/addvehicle/<string:name>', '/getvehicle/<string:name>')
app.run(port=5000, debug=True)

The modified code above returns all vehicles if the url /getvehicle/all is entered and prevents adding a car named 'all' in the post() function.

Not sure if I've fully understand your requirements but my interpretation is that you have three end-points:

  1. Add vehicle (loads data)
  2. Get vehicle (gets the data of one of the vehicles based on an input)
  3. Get all vehicles (gets data for all of the vehicles)

I would suggest storing the output in a nested dictionary as this makes it easier to manipulate.

from flask import Flask, request

global vehicles
vehicles = {}
 
my_app = Flask(__name__)

@my_app.route('/load_vehicle', methods=['POST'])
def load_vehicle():

    """
    Example JSON:
        
    {'compass':{'type':'car',
                'vehicle':'automobile',
                'suv':True,
                'wheels':4}}
    """

    global vehicles
    
    json_in = request.get_json(silent=True)

    if json_in != None:
        
        vehicles.update(json_in)


@my_app.route('/get_vehicle', methods=['POST'])
def get_vehicle():

    """
    Example JSON:
        
    {'name':'compass'}
    """

    global vehicles
    
    json_in = request.get_json(silent=True)

    if json_in != None:
        
        output = vehicles[json_in['name']]

    return output

@my_app.route('/get_all', methods=['GET'])
def get_all():
    
    global vehicles
    
    return vehicles

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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