Comments (3)
Ah, nevermind, read through the docs again and found a convenient way to create a dummy body using a middleware.
from dataclasses import dataclass, field
from typing import Optional
from sanic import Sanic
from sanic.response import json
from sanic_ext import openapi, validate
app = Sanic("Test")
@dataclass
class Test:
bar: Optional[str] = field(default_factory=str)
@app.middleware("request")
async def dummy_body_if_empty(request):
if not request.body:
request.body = b'{}'
@app.post("/")
@openapi.body({"application/json": Test})
@validate(Test)
async def test(request, body: Test):
return json({"message": "Hello world!"})
from sanic-ext.
I think it ultimately is a bug in need of fixing to properly read more information from the dataclass if it is available.
from sanic-ext.
🥳 It works, thank you!
I do have another corner case where a request does have only one optional parameter.
Example:
from dataclasses import dataclass, field
from typing import Optional
from sanic import Sanic
from sanic.log import logger
from sanic.response import json
from sanic_ext import openapi, validate
app = Sanic("Test")
@dataclass
class Test:
bar: Optional[str] = field(default_factory=str)
@app.post("/")
@openapi.body({"application/json": Test})
@validate(Test)
async def test(request, body: Test):
return json({"message": "Hello world!"})
If i omit the body completely, the validation fails again due to the request does not have a body (None):
$ curl -X POST http://127.0.0.1:8000/
{"description":"Bad Request","status":400,"message":"Invalid request body: Test. Error: Value 'None' is not a dict"}
Stacktrace:
[2022-01-21 13:33:53 +0100] [30740] [ERROR] Exception occurred while handling uri: 'http://127.0.0.1:8000/'
Traceback (most recent call last):
File "/home/morph/python3/lib/python3.10/site-packages/sanic_ext/extras/validation/validators.py", line 24, in validate_body
return validator(model, body)
File "/home/morph/python3/lib/python3.10/site-packages/sanic_ext/extras/validation/validators.py", line 36, in _validate_annotations
return check_data(model, body, schema, allow_multiple, allow_coerce)
File "/home/morph/python3/lib/python3.10/site-packages/sanic_ext/extras/validation/check.py", line 83, in check_data
raise TypeError(f"Value '{data}' is not a dict")
TypeError: Value 'None' is not a dict
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "handle_request", line 83, in handle_request
)
File "/home/morph/python3/lib/python3.10/site-packages/sanic_ext/extensions/openapi/openapi.py", line 213, in handler
retval = await retval
File "/home/morph/python3/lib/python3.10/site-packages/sanic_ext/extras/validation/decorator.py", line 37, in decorated_function
await do_validation(
File "/home/morph/python3/lib/python3.10/site-packages/sanic_ext/extras/validation/setup.py", line 41, in do_validation
validation = validate_body(validator, model, data)
File "/home/morph/python3/lib/python3.10/site-packages/sanic_ext/extras/validation/validators.py", line 26, in validate_body
raise ValidationError(
sanic_ext.exceptions.ValidationError: Invalid request body: Test. Error: Value 'None' is not a dict
Passing an empty body works:
$ curl -X POST -d '{}' http://127.0.0.1:8000/
{"message":"Hello world!"}
Any way to specify a fallback for a None
body?
from sanic-ext.
Related Issues (20)
- [Question] OpenAPI spec available on all subdomains, and route exclusion without decorators does not seem to work.
- [Bug] Dependeny Injection throw exceptions by default if @classmethod constructors don't return value/objects
- [Feature Request]
- [Bug] OpenAPI definition does not include placeholder for "headers"
- [Bug] Json validator throws 500 instead of 400
- [Feature Request] Response Compression
- [Bug] Can't use `pydantic>=2.0` model in OpenAPI definition HOT 1
- [Bug] Can't document/exclude websocket routes with OpenAPI decorator
- [Bug] Subheader "parameter" missing in sanic extensions document
- [Bug] Can't apply openapi decorators to blueprintss' routes
- [Bug]TypeError: listener() got an unexpected keyword argument 'priority' HOT 1
- [Bug] Documentation: dead link to the setting
- Query params validation is completely broken HOT 2
- Question regarding licensing info
- [Bug] Doubly defined objects in the output specification #260 HOT 2
- [Bug] The tags in OpenAPI yaml are not effective
- [Bug] Pydantic query validation with extra data not defined in model raise's KeyError
- add project to nix packages
- Add support for scalar.com OpenAPI documentation
- [Bug] Sanic validation extension failed to validate aliased pydantic model field
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
D3
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
-
Recommend Topics
-
javascript
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
-
web
Some thing interesting about web. New door for the world.
-
server
A server is a program made to process requests and deliver data to clients.
-
Machine learning
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.
from sanic-ext.