@@ -22,10 +22,13 @@ from marshmallow import Schema, fields, ValidationError, post_load
22
22
from starlette.applications import Starlette
23
23
from starlette.datastructures import UploadFile
24
24
from starlette.responses import JSONResponse
25
+ from apispec.ext.marshmallow import MarshmallowPlugin
26
+ from apispec import APISpec
25
27
26
28
from dataclasses import dataclass
29
+ from datetime import datetime
27
30
28
- from star_resty import Method, Operation, endpoint, json_schema, json_payload, form_payload , query, setup_spec
31
+ from star_resty import Method, Operation, endpoint, json_schema, json_payload, upload , query, setup_spec, form_payload
29
32
from typing import Optional
30
33
31
34
class EchoInput (Schema ):
@@ -37,6 +40,7 @@ class JsonPayloadSchema(Schema):
37
40
a = fields.Int(required = True )
38
41
s = fields.String()
39
42
43
+ ma_plugin = MarshmallowPlugin()
40
44
41
45
# Json Payload (by dataclass)
42
46
@dataclass
@@ -54,15 +58,9 @@ class JsonPayloadDataclass(Schema):
54
58
55
59
56
60
# Form Payload
57
- class FormFile (fields .Field ):
58
- def _validate (self , value ):
59
- if not isinstance (value, UploadFile):
60
- raise ValidationError(' Not a file' )
61
-
62
-
63
61
class FormPayload (Schema ):
64
62
id = fields.Int(required = True )
65
- file = FormFile ()
63
+ file_dt = fields.DateTime ()
66
64
67
65
68
66
app = Starlette(debug = True )
@@ -105,10 +103,15 @@ class PostDataclass(Method):
105
103
class PostForm (Method ):
106
104
meta = Operation(tag = ' default' , description = ' post form' )
107
105
108
- async def execute (self , form_data : form_payload(FormPayload)):
109
- file_name = form_data.get(' file' ).filename
106
+ async def execute (self , form_data : form_payload(FormPayload),
107
+ files_reqired : upload(' selfie' , ' doc' , required = True ),
108
+ files_optional : upload(' file1' , ' file2' , ' file3' )):
109
+ files = {}
110
+ for file in files_reqired + files_optional:
111
+ body = await file .read()
112
+ files[file .filename] = f " { body.hex()[:10 ]} ... "
110
113
id = form_data.get(' id' )
111
- return {' message' : f " file { file_name } with id { id } received " }
114
+ return {' message' : f " files received (id: { id } ) " , " files " : files }
112
115
113
116
114
117
if __name__ == ' __main__' :
@@ -118,4 +121,4 @@ if __name__ == '__main__':
118
121
uvicorn.run(app, port = 8080 )
119
122
```
120
123
121
- Open [ http://localhost:8080/apidocs.json ] ( http://localhost:8080/apidocs.json ) to view generated openapi schema.
124
+ Open [ http://localhost:8080/apidocs.json ] ( http://localhost:8080/apidocs.json ) to view generated openapi schema.
0 commit comments