Coder Social home page Coder Social logo

Comments (3)

morph027 avatar morph027 commented on June 20, 2024 1

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.

ahopkins avatar ahopkins commented on June 20, 2024

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.

morph027 avatar morph027 commented on June 20, 2024

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

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo 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.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.