Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Get and validate all Flask input parameters with ease.

NotificationsYou must be signed in to change notification settings

Ge0rg3/flask-parameter-validation

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Get and validate all Flask input parameters with ease.

Install

  • Pip: Install withpip install flask_parameter_validation.
  • Manually:
    • git clone https://github.com/Ge0rg3/flask-parameter-validation.git
    • python setup.py install

Usage Example

fromflaskimportFlaskfromtypingimportOptionalfromflask_parameter_validationimportValidateParameters,Route,Json,QueryfromdatetimeimportdatetimefromenumimportEnumclassAccountStatus(int,Enum):# In Python 3.11 or later, subclass IntEnum from enum package instead of int, EnumACTIVE=1DISABLED=0classUserType(str,Enum):# In Python 3.11 or later, subclass StrEnum from enum package instead of str, EnumUSER="user"SERVICE="service"app=Flask(__name__)@app.route("/update/<int:id>",methods=["POST"])@ValidateParameters()defhello(id:int=Route(),username:str=Json(min_str_length=5,blacklist="<>"),age:int=Json(min_int=18,max_int=99),nicknames:list[str]=Json(),date_of_birth:datetime=Json(),password_expiry:Optional[int]=Json(5),is_admin:bool=Query(False),user_type:UserType=Json(alias="type"),status:AccountStatus=Json()     ):return"Hello World!"if__name__=="__main__":app.run()

Usage

To validate parameters with flask-parameter-validation, two conditions must be met.

  1. The@ValidateParameters() decorator must be applied to the function
  2. Type hints (supported types) and a default of a subclass ofParameter must be supplied per parameter

Enable and customize Validation for a Route with the @ValidateParameters decorator

The@ValidateParameters() decorator takes parameters that alter route validation behavior or provide documentation information:

ParameterTypeDefaultDescription
error_handlerOptional[Response]NoneOverwrite the output format of generated errors, seeOverwriting Default Errors for more

Overwriting Default Errors

By default, the error messages are returned as a JSON response, with the detailed error in the "error" field, eg:

{"error":"Parameter 'age' must be type 'int'"}

However, this can be edited by passing a custom error function into theValidateParameters() decorator. For example:

deferror_handler(err):error_name=type(err)error_parameters=err.argserror_message=str(err)return {"error_name":type(err).__name__,"error_parameters":err.args,"error_message":str(err)    },400@app.route(...)@ValidateParameters(error_handler)defapi(...)

Specify Parameter types and constraints with type hints and subclasses of Parameter

Parameter Class

TheParameter class provides a base for validation common among all input types, all location-specific classes extendParameter. These subclasses are:

Subclass NameInput SourceAvailable For
RouteParameter passed in the pathname of the URL, such as/users/<int:id>All HTTP Methods
FormParameter in an HTML form or aFormData object in the request body, often withContent-Type: x-www-form-urlencodedPOST Methods
JsonParameter in the JSON object in the request body, must have headerContent-Type: application/jsonPOST Methods
QueryParameter in the query of the URL, such as /news_article?id=55All HTTP Methods
FileParameter is a file uploaded in the request bodyPOST Method
MultiSourceParameter is in one of the locations provided to the constructorDependent on selected locations

Note: "POST Methods" refers to the HTTP methods that send data in the request body, such as POST, PUT, PATCH and DELETE. Although sending data via some methods such as DELETE is not standard, it is supported by Flask and this library.

MultiSource Parameters

Using theMultiSource parameter type, parameters can be accepted from any combination ofParameter subclasses. Example usage is as follows:

@app.route("/")@app.route("/<v>")# If accepting parameters by Route and another type, a path with and without that Route parameter must be specified@ValidateParameters()defmulti_source_example(value:int=MultiSource(Route,Query,Json,min_int=0))

The above example will accept parameters passed to the route through Route, Query, and JSON Body.

Note: "POST Methods" refers to the HTTP methods that send data in the request body, such as POST, PUT, PATCH and DELETE. Although sending data via some methods such as DELETE is not standard, it is supported by Flask and this library.

Type Hints and Accepted Input Types

Type Hints allow for inline specification of the input type of a parameter. Some types are only available to certainParameter subclasses.

Type Hint / Expected Python TypeNotesRouteFormJsonQueryFile
strYYYYN
intYYYYN
boolYYYYN
floatYYYYN
list/typing.List (typing.List isdeprecated)ForJson, received as a JSON List

ForQuery, can be received asvalue=1,2,3 iflist_disable_query_csv isFalse.

ForForm orQuery, received asvalue=1&value=2&value=3.

A singlevalue= with no value will always be transformed to an empty list, butvalue=, (Query only) andvalue=&value= will be transformed to a list of emptystr.

Lists withNone as an accepted type are only supported inJson parameters.
NYYYN
typing.UnionYYYYN
typing.OptionalNot supported forRoute inputsYYYYY
datetime.datetimeReceived as astr in ISO-8601 date-time formatYYYYN
datetime.dateReceived as astr in ISO-8601 full-date formatYYYYN
datetime.timeReceived as astr in ISO-8601 partial-time formatYYYYN
dictForQuery andForm inputs, users should pass the stringified JSONNYYYN
FileStorageNNNNY
A subclass ofStrEnum orIntEnum, or a subclass ofEnum withstr orint mixins prior to Python 3.11YYYYN
uuid.UUIDReceived as astr with or without hyphens, case-insensitiveYYYYN

These can be used in tandem to describe a parameter to validate:parameter_name: type_hint = ParameterSubclass()

  • parameter_name: The field name itself, such as username
  • type_hint: The expected Python data type
  • ParameterSubclass: An instance of a subclass ofParameter

Validation with arguments to Parameter

Validation beyond type-checking can be done by passing arguments into the constructor of theParameter subclass. The arguments available for use on each type hint are:

Parameter NameType of ArgumentEffective On TypesDescription
defaultany, exceptNoneTypeAll, except inRouteSpecifies the default value for the field, makes non-Optional fields not required
min_str_lengthintstrSpecifies the minimum character length for a string input
max_str_lengthintstrSpecifies the maximum character length for a string input
min_list_lengthintlistSpecifies the minimum number of elements in a list
max_list_lengthintlistSpecifies the maximum number of elements in a list
min_intintintSpecifies the minimum number for an integer input
max_intintintSpecifies the maximum number for an integer input
whiteliststrstrA string containing allowed characters for the value
blackliststrstrA string containing forbidden characters for the value
patternstrstrA regex pattern to test for string matches
funcCallable[Any] -> Union[bool, tuple[bool, str]]AllA function containing a fully customized logic to validate the value. See thecustom validation function below for usage
datetime_formatstrdatetime.datetimePython datetime format string datetime format string (datetime format codes)
commentstrAllA string to display as the argument description in any generated documentation
aliasstrAll butFileStorageAn expected parameter name to receive instead of the function name.
json_schemadictdictAn expectedJSON Schema which the dict input must conform to
content_typeslist[str]FileStorageAllowedContent-Types
min_lengthintFileStorageMinimumContent-Length for a file
max_lengthintFileStorageMaximumContent-Length for a file
blank_noneboolOptional[str]IfTrue, an empty string will be converted toNone, defaults to configuredFPV_BLANK_NONE, seeValidation Behavior Configuration for more
list_disable_query_csvboollist inQueryIfFalse, list-type Query parameters will be split by,, defaults to configuredFPV_LIST_DISABLE_QUERY_CSV, seeValidation Behavior Configuration for more

These validators are passed into theParameter subclass in the route function, such as:

  • username: str = Json(default="defaultusername", min_length=5)
  • profile_picture: werkzeug.datastructures.FileStorage = File(content_types=["image/png", "image/jpeg"])
  • filter: str = Query()

Custom Validation Function

Custom validation functions passed into thefunc property can be used to validate an input against custom logic and return customized error responses for that validation

Example custom validation functions are below:

defis_even(val:int):"""Return a single bool, True if valid, False if invalid"""returnval%2==0defis_odd(val:int):"""Return a tuple with a bool, as above, and the error message if the bool is False"""returnval%2!=0,"val must be odd"

Configuration Options

API Documentation Configuration

  • FPV_DOCS_SITE_NAME: str: Your site's name, to be displayed in the page title, default:Site
  • FPV_DOCS_CUSTOM_BLOCKS: array: An array of dicts to display as cards at the top of your documentation, with the (optional) keys:
    • title: Optional[str]: The title of the card
    • body: Optional[str] (HTML allowed): The body of the card
    • order: int: The order in which to display this card (out of the other custom cards)
  • FPV_DOCS_DEFAULT_THEME: str: The default theme to display in the generated webpage

See theAPI Documentation below for other information on API Documentation generation

Validation Behavior Configuration

  • FPV_BLANK_NONE: bool: Set the defaultblank_none behavior for routes in your application, defaults toFalse if unset
  • FPV_LIST_DISABLE_QUERY_CSV: bool: Set the defaultlist_disable_query_csv behavior for routes in your application, defaults toFalse if unset

API Documentation

Using the data provided through parameters, docstrings, and Flask route registrations, Flask Parameter Validation can generate API Documentation in various formats.To make this easy to use, it comes with aBlueprint and the output shown below and configuration optionsabove:

Included Blueprint

The documentation blueprint can be added using the following code:

fromflask_parameter_validation.docs_blueprintimportdocs_blueprint...app.register_blueprint(docs_blueprint)

The default blueprint adds twoGET routes:

  • /: HTML Page with Bootstrap CSS and toggleable light/dark mode
  • /json: Non-standard Format JSON Representation of the generated documentation

The/json route yields a response with the following format:

{"custom_blocks":"<array entered in the FPV_DOCS_CUSTOM_BLOCKS config option, default: []>","default_theme":"<string entered in the FPV_DOCS_DEFAULT_THEME config option, default: 'light'>","docs":"<see get_route_docs() return value format below>","site_name":"<string entered in the FPV_DOCS_SITE_NAME config option, default: 'Site'"}
Example with included Blueprint

Code:

@config_api.get("/")@ValidateParameters()defget_all_configs():"""    Get the System Configuration    Returns:    <code>{"configs":        [{"id": int,        "module": str,        "name": str,        "description": str,        "value": str}, ...]    }</code>    """system_configs= []forsystem_configinSystemConfig.query.all():system_configs.append(system_config.toDict())returnresp_success({"configs":system_configs})@config_api.post("/<int:config_id>")@ValidateParameters()defedit_config(config_id:int=Route(comment="The ID of the Config Record to Edit"),value:str=Json(max_str_length=2000,comment="The value to set in the Config Record")):"""Edit a specific System Configuration value"""config=SystemConfig.get_by_id(config_id)ifconfigisNone:returnresp_not_found("No link exists with ID "+str(config_id))else:config.update(value)returnresp_success()

Documentation Generated:

Custom Blueprint

If you would like to use your own blueprint, you can get the raw data from the following function:

fromflask_parameter_validation.docs_blueprintimportget_route_docs...get_route_docs()
get_route_docs() return value format

This method returns an object with the following structure:

[  {"rule":"/path/to/route","methods": ["HTTPVerb"],"docstring":"String, unsanitized of HTML Tags","decorators": ["@decorator1","@decorator2(param)"],"args": {"<Subclass of Parameter this route uses>": [        {"name":"Argument Name","type":"Argument Type","loc_args": {"<Name of argument passed to Parameter Subclass>":"Value passed to Argument","<Name of another argument passed to Parameter Subclass>":0          }        }      ],"<Another Subclass of Parameter this route uses>": []    }  },...]

JSON Schema Validation

An example of theJSON Schema validation is provided below:

json_schema= {"type":"object","required": ["user_id","first_name","last_name","tags"],"properties": {"user_id": {"type":"integer"},"first_name": {"type":"string"},"last_name": {"type":"string"},"tags": {"type":"array","items": {"type":"string"}        }    }}@api.get("/json_schema_example")@ValidateParameters()defjson_schema(data:dict=Json(json_schema=json_schema)):returnjsonify({"data":data})

Contributions

Many thanks to all those who have made contributions to the project:

  • d3-steichman/smt5541: API documentation, custom error handling, datetime validation and bug fixes
  • summersz: Parameter aliases, async support, form type conversion and list bug fixes
  • Garcel: Allow passing custom validator function
  • iml1111: Implement regex validation
  • borisowww: Fix file handling bugs
  • Charlie-Mindified: Fix JSON handling bug
  • dkassen: Helped to resolve broken list parsing logic

[8]ページ先頭

©2009-2025 Movatter.jp