---
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)
```

### Choices
```python
parser.add_argument(
'gender',
choices=('male', 'female'),
)
```

### Required Arguments
```python
parser.add_argument('id', required=True)
```

### Multiple Values & Lists
```python
parser.add_argument('hobby', action='append')
```

```python
parser.add_argument('favourite_food', action='split')
```

### 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')
```

回傳格式為 [`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)