Fields¶
Config
¶
Bases: Field
A field for Flask configuration values.
Examples:
from apiflask import APIFlask, Schema
from apiflask.fields import String, Config
app = APIFlask(__name__)
app.config['API_TITLE'] = 'Pet API'
class FooSchema(Schema):
user = String()
title = Config('API_TITLE')
@app.get('/foo')
@app.output(FooSchema)
def foo():
return {'user': 'test'}
This field should only be used in an output schema. The ValueError
will
be raised if the config key is not found in the app config.
Version Added: 2.0.1
Source code in apiflask/fields.py
125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 |
|
File
¶
Bases: Field
A binary file field, it should only be used in an input schema.
Examples:
import os
from werkzeug.utils import secure_filename
from apiflask.fields import File
class Image(Schema):
image = File()
@app.post('/images')
@app.input(Image, location='files')
def upload_image(files_data):
f = files_data['image']
# use `secure_filename` to clean the filename, notice it will only keep ascii characters
filename = secure_filename(f.filename)
f.save(os.path.join(the_path_to_uploads, filename))
return {'message': f'file {filename} saved.'}
werkzeug.datastructures.FileStorage
, see more details in the
docs. # noqa: B950, E501
Use form_and_files
location if you want to put both files
and other normal fields in one schema.
import os
from werkzeug.utils import secure_filename
from apiflask.fields import String, File
class ProfileIn(Schema):
name = String()
avatar = File()
@app.post('/profiles')
@app.input(ProfileIn, location='form_and_files')
def create_profile(form_and_files_data):
avatar_file = form_and_files_data['avatar']
name = form_and_files_data['name']
# use `secure_filename` to clean the filename, notice it will only keep ascii characters
avatar_filename = secure_filename(avatar_file.filename)
avatar_file.save(os.path.join(the_path_to_uploads, avatar_filename))
profile = Profile(name=name, avatar_filename=avatar_filename)
# ...
return {'message': 'profile created.'}
In the current implementation, files
location data will also include
the form data (equals to form_and_files
).
Version Added: 1.0
This field accepts the same keyword arguments that Field
receives.
Source code in apiflask/fields.py
43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 |
|
External documentation¶
Check out the following docs for the fields provided by marshallow, Flask-Marshmallow, and wegbargs: