--- tags: Python --- # Flask RESTPlus ## Arguments ```python from flask import Flask from flask_restplus import Resource, Api, reqparse parser = reqparse.RequestParser() @api.route('/hello') @api.expect(parser) class HelloWorld(Resource): def get(self): args = parser.parse_args() return {'hello': 'world'} ``` ### Basic arguments ```python parser.add_argument('name') ``` > The default argument type is a unicode string. This will be str in python3 and unicode in python2. > - `help` - A brief description of what the argument does. > - `default` - The value produced if the argument is absent from the command line. > - `dest` - The name of the attribute to be added to the object returned by parse_args(). > > [name=[The `add_argument()` method](https://docs.python.org/3/library/argparse.html#the-add-argument-method)] ### 限定 type ```python parser.add_argument('height', type=int) ``` ![](https://i.imgur.com/z92JpSs.png) ### Choices ```python parser.add_argument( 'gender', choices=('male', 'female'), ) ``` ![](https://i.imgur.com/F7KDvkg.png) ### Required Arguments ```python parser.add_argument('id', required=True) ``` ![](https://i.imgur.com/PGsWoKr.png) ### Multiple Values & Lists ```python parser.add_argument('hobby', action='append') ``` ![](https://i.imgur.com/e8HNvNC.png) ```python parser.add_argument('favourite_food', action='split') ``` ![](https://i.imgur.com/e2XN6jE.png) ### Other destination ```python parser.add_argument('full name', dest='full_name') ``` 會以 `dest` 設定的名稱為 key,原先的不會儲存。也就是說只能以 `full_name` 來拿取值。 ### Upload file ```python from werkzeug.datastructures import FileStorage parser.add_argument('picture', type=FileStorage, location='files') ``` ![](https://i.imgur.com/Acd3VDE.png) 回傳格式為 [`werkzeug.datastructures.FileStorage`](https://werkzeug.palletsprojects.com/en/0.15.x/datastructures/#werkzeug.datastructures.FileStorage): ```python {'picture': <FileStorage: 'photo.JPG' ('image/jpeg')>} ``` ### Parser Inheritance ```python parser_copy.replace_argument('foo', required=True, location='json') # 'foo' is now a required str located in json, not an int as defined by original parser parser_copy.remove_argument('foo') # parser_copy no longer has 'foo' argument ``` ## 參考資料 - [Request Parsing / Flask RESTPlus](https://flask-restplus.readthedocs.io/en/stable/parsing.html)