简体   繁体   中英

Flask: Return Exception on wrong call

Below is my simple flask app

hello.py

from flask import Flask
from flask_restful import Api

import api_resources

application = Flask(__name__)
application.config['BUNDLE_ERRORS'] = True
api = Api(application)
api.add_resource(api_resources.helloworld, '/helloworld')

if __name__ == '__main__':
    application.run(debug=True, port=8080)

api_resources.py

import json
import requests

from flask_restful import Resource, reqparse
from flask import Response

def bandwidth_type(x):
    x = int(x)
    if x < 12:
        print('yes')
        raise Exception('Invalid parameter type')
    return x

parser = reqparse.RequestParser()
parser.add_argument("band", type=bandwidth_type, help="target bandwidth >= 12")

class helloworld(Resource):

    def __init__(self):
        pass

    def get(self):
        count_parser = parser.copy()
        args = count_parser.parse_args()
        print(args)
        resp = Response({'Hello World'}, mimetype='application/json', headers={})
        return resp

When I call localhost:8080/helloworld?band=1, I would like to display that I have used wrong value of Band but that doesn't happen. The exception is not changing any thing. What can be done to return "Wrong value of band" to the flask api call if value of band is < 12.

you have to only raise Exception. my problem was that when i call from postman with wring boolean parameter than it should be shown the custom exception message to the postman. i solved my problem with this. mainly you have to remove the help parameter from the parser otherwise that will override the custom message

def checkBoolean(v):
    if isinstance(v, bool):
        return v
    else:
        raise Exception("Put right boolean field")

 parser.add_argument(
        'ajax',
        type = checkBoolean,
        required=True
    )

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