Add a check for request body functions and a test for NotImplementedError.

This commit is contained in:
L. Kärkkäinen 2020-03-25 14:35:09 +02:00
parent f1c85eb1f8
commit 42af6e1af6
2 changed files with 25 additions and 1 deletions

View File

@ -22,6 +22,7 @@ from sanic.constants import HTTP_METHODS
from sanic.exceptions import SanicException, ServerError, URLBuildError
from sanic.handlers import ErrorHandler
from sanic.log import LOGGING_CONFIG_DEFAULTS, error_logger, logger
from sanic.request import Request
from sanic.response import BaseHTTPResponse, HTTPResponse
from sanic.router import Router
from sanic.server import (
@ -61,7 +62,15 @@ class Sanic:
)
frame_records = stack()[1]
name = getmodulename(frame_records[1])
# Check for unsupported function on custom request objects
if request_class and any(hasattr(request_class, m) for m in (
"body_init", "body_push", "body_finish"
)) and request_class.receive_body is Request.receive_body:
raise NotImplementedError(
"Request methods body_init, body_push and body_finish "
f"are no longer supported. {request_class!r} should "
"implement receive_body. It is okay to implement both APIs.",
)
# logging
if configure_logging:
logging.config.dictConfig(log_config or LOGGING_CONFIG_DEFAULTS)

View File

@ -1,10 +1,17 @@
from io import BytesIO
import pytest
from sanic import Sanic
from sanic.request import Request
from sanic.response import json_dumps, text
class DeprecCustomRequest(Request):
"""Using old API should fail when receive_body is not implemented"""
def body_push(self, data):
pass
class CustomRequest(Request):
"""Alternative implementation for loading body (non-streaming handlers)"""
async def receive_body(self):
@ -13,6 +20,14 @@ class CustomRequest(Request):
buffer.write(data)
self.body = buffer.getvalue().upper()
buffer.close()
# Old API may be implemented but won't be used here
def body_push(self, data):
assert False
def test_deprecated_custom_request():
with pytest.raises(NotImplementedError):
Sanic(request_class=DeprecCustomRequest)
def test_custom_request():
app = Sanic(request_class=CustomRequest)