Skip to content

Commit

Permalink
Remove deprecated items (#2555)
Browse files Browse the repository at this point in the history
  • Loading branch information
ahopkins committed Sep 28, 2022
1 parent 23ce4ea commit 5052321
Show file tree
Hide file tree
Showing 10 changed files with 47 additions and 155 deletions.
109 changes: 22 additions & 87 deletions sanic/app.py
Expand Up @@ -47,7 +47,7 @@
from sanic_routing.route import Route

from sanic.application.ext import setup_ext
from sanic.application.state import ApplicationState, Mode, ServerStage
from sanic.application.state import ApplicationState, ServerStage
from sanic.asgi import ASGIApp
from sanic.base.root import BaseSanic
from sanic.blueprint_group import BlueprintGroup
Expand Down Expand Up @@ -158,7 +158,6 @@ class Sanic(BaseSanic, StartupMixin, metaclass=TouchUpMeta):
)

_app_registry: Dict[str, "Sanic"] = {}
_uvloop_setting = None # TODO: Remove in v22.6
test_mode = False

def __init__(
Expand Down Expand Up @@ -394,8 +393,8 @@ def _apply_route(self, route: FutureRoute) -> List[Route]:
routes = [routes]

for r in routes:
r.ctx.websocket = websocket
r.ctx.static = params.get("static", False)
r.extra.websocket = websocket
r.extra.static = params.get("static", False)
r.ctx.__dict__.update(ctx)

return routes
Expand Down Expand Up @@ -589,7 +588,7 @@ def url_for(self, view_name: str, **kwargs):

uri = route.path

if getattr(route.ctx, "static", None):
if getattr(route.extra, "static", None):
filename = kwargs.pop("filename", "")
# it's static folder
if "__file_uri__" in uri:
Expand Down Expand Up @@ -622,18 +621,18 @@ def url_for(self, view_name: str, **kwargs):
host = kwargs.pop("_host", None)
external = kwargs.pop("_external", False) or bool(host)
scheme = kwargs.pop("_scheme", "")
if route.ctx.hosts and external:
if not host and len(route.ctx.hosts) > 1:
if route.extra.hosts and external:
if not host and len(route.extra.hosts) > 1:
raise ValueError(
f"Host is ambiguous: {', '.join(route.ctx.hosts)}"
f"Host is ambiguous: {', '.join(route.extra.hosts)}"
)
elif host and host not in route.ctx.hosts:
elif host and host not in route.extra.hosts:
raise ValueError(
f"Requested host ({host}) is not available for this "
f"route: {route.ctx.hosts}"
f"route: {route.extra.hosts}"
)
elif not host:
host = list(route.ctx.hosts)[0]
host = list(route.extra.hosts)[0]

if scheme and not external:
raise ValueError("When specifying _scheme, _external must be True")
Expand Down Expand Up @@ -884,7 +883,7 @@ async def handle_request(self, request: Request): # no cov
if (
request.stream
and request.stream.request_body
and not route.ctx.ignore_body
and not route.extra.ignore_body
):

if hasattr(handler, "is_stream"):
Expand Down Expand Up @@ -1346,18 +1345,6 @@ def asgi(self, value: bool):
def debug(self):
return self.state.is_debug

@debug.setter
def debug(self, value: bool):
deprecation(
"Setting the value of a Sanic application's debug value directly "
"is deprecated and will be removed in v22.9. Please set it using "
"the CLI, app.run, app.prepare, or directly set "
"app.state.mode to Mode.DEBUG.",
22.9,
)
mode = Mode.DEBUG if value else Mode.PRODUCTION
self.state.mode = mode

@property
def auto_reload(self):
return self.config.AUTO_RELOAD
Expand All @@ -1374,58 +1361,6 @@ def state(self) -> ApplicationState: # type: ignore
"""
return self._state

@property
def is_running(self):
deprecation(
"Use of the is_running property is no longer used by Sanic "
"internally. The property is now deprecated and will be removed "
"in version 22.9. You may continue to set the property for your "
"own needs until that time. If you would like to check whether "
"the application is operational, please use app.state.stage. More "
"information is available at ___.",
22.9,
)
return self.state.is_running

@is_running.setter
def is_running(self, value: bool):
deprecation(
"Use of the is_running property is no longer used by Sanic "
"internally. The property is now deprecated and will be removed "
"in version 22.9. You may continue to set the property for your "
"own needs until that time. If you would like to check whether "
"the application is operational, please use app.state.stage. More "
"information is available at ___.",
22.9,
)
self.state.is_running = value

@property
def is_stopping(self):
deprecation(
"Use of the is_stopping property is no longer used by Sanic "
"internally. The property is now deprecated and will be removed "
"in version 22.9. You may continue to set the property for your "
"own needs until that time. If you would like to check whether "
"the application is operational, please use app.state.stage. More "
"information is available at ___.",
22.9,
)
return self.state.is_stopping

@is_stopping.setter
def is_stopping(self, value: bool):
deprecation(
"Use of the is_stopping property is no longer used by Sanic "
"internally. The property is now deprecated and will be removed "
"in version 22.9. You may continue to set the property for your "
"own needs until that time. If you would like to check whether "
"the application is operational, please use app.state.stage. More "
"information is available at ___.",
22.9,
)
self.state.is_stopping = value

@property
def reload_dirs(self):
return self.state.reload_dirs
Expand Down Expand Up @@ -1520,6 +1455,16 @@ def get_app(
return cls(name)
raise SanicException(f'Sanic app name "{name}" not found.')

@classmethod
def _check_uvloop_conflict(cls) -> None:
values = {app.config.USE_UVLOOP for app in cls._app_registry.values()}
if len(values) > 1:
error_logger.warning(
"It looks like you're running several apps with different "
"uvloop settings. This is not supported and may lead to "
"unintended behaviour."
)

# -------------------------------------------------------------------- #
# Lifecycle
# -------------------------------------------------------------------- #
Expand Down Expand Up @@ -1569,17 +1514,7 @@ async def _startup(self):
23.3,
)

# TODO: Replace in v22.6 to check against apps in app registry
if (
self.__class__._uvloop_setting is not None
and self.__class__._uvloop_setting != self.config.USE_UVLOOP
):
error_logger.warning(
"It looks like you're running several apps with different "
"uvloop settings. This is not supported and may lead to "
"unintended behaviour."
)
self.__class__._uvloop_setting = self.config.USE_UVLOOP
Sanic._check_uvloop_conflict()

# Startup time optimizations
if self.state.primary:
Expand Down
2 changes: 1 addition & 1 deletion sanic/blueprints.py
Expand Up @@ -406,7 +406,7 @@ def register(self, app, options):

self.routes += [route for route in routes if isinstance(route, Route)]
self.websocket_routes += [
route for route in self.routes if route.ctx.websocket
route for route in self.routes if route.extra.websocket
]
self.middlewares += middleware
self.exceptions += exception_handlers
Expand Down
23 changes: 6 additions & 17 deletions sanic/config.py
Expand Up @@ -12,7 +12,7 @@
from sanic.errorpages import DEFAULT_FORMAT, check_error_format
from sanic.helpers import Default, _default
from sanic.http import Http
from sanic.log import deprecation, error_logger
from sanic.log import error_logger
from sanic.utils import load_module_from_file_location, str_to_bool


Expand Down Expand Up @@ -71,10 +71,6 @@
"WEBSOCKET_PING_TIMEOUT": 20,
}

# These values will be removed from the Config object in v22.6 and moved
# to the application state
DEPRECATED_CONFIG = ("SERVER_RUNNING", "RELOADER_PROCESS", "RELOADED_FILES")


class DescriptorMeta(type):
def __init__(cls, *_):
Expand Down Expand Up @@ -132,6 +128,7 @@ def __init__(
):
defaults = defaults or {}
super().__init__({**DEFAULT_CONFIG, **defaults})
self._configure_warnings()

self._converters = [str, str_to_bool, float, int]

Expand All @@ -149,7 +146,6 @@ def __init__(
self.load_environment_vars(SANIC_PREFIX)

self._configure_header_size()
self._configure_warnings()
self._check_error_format()
self._init = True

Expand Down Expand Up @@ -241,7 +237,9 @@ def load_environment_vars(self, prefix=SANIC_PREFIX):
"""
Looks for prefixed environment variables and applies them to the
configuration if present. This is called automatically when Sanic
starts up to load environment variables into config.
starts up to load environment variables into config. Environment
variables should start with the defined prefix and should only
contain uppercase letters.
It will automatically hydrate the following types:
Expand All @@ -267,12 +265,9 @@ def __init__(self, name) -> None:
`See user guide re: config
<https://sanicframework.org/guide/deployment/configuration.html>`__
"""
lower_case_var_found = False
for key, value in environ.items():
if not key.startswith(prefix):
if not key.startswith(prefix) or not key.isupper():
continue
if not key.isupper():
lower_case_var_found = True

_, config_key = key.split(prefix, 1)

Expand All @@ -282,12 +277,6 @@ def __init__(self, name) -> None:
break
except ValueError:
pass
if lower_case_var_found:
deprecation(
"Lowercase environment variables will not be "
"loaded into Sanic config beginning in v22.9.",
22.9,
)

def update_config(self, config: Union[bytes, str, dict, Any]):
"""
Expand Down
4 changes: 2 additions & 2 deletions sanic/errorpages.py
Expand Up @@ -448,8 +448,8 @@ def exception_response(
# from the route
if request.route:
try:
if request.route.ctx.error_format:
render_format = request.route.ctx.error_format
if request.route.extra.error_format:
render_format = request.route.extra.error_format
except AttributeError:
...

Expand Down
23 changes: 2 additions & 21 deletions sanic/mixins/routes.py
Expand Up @@ -10,6 +10,7 @@
from typing import (
Any,
Callable,
Dict,
Iterable,
List,
Optional,
Expand Down Expand Up @@ -38,14 +39,6 @@
RouteWrapper = Callable[
[RouteHandler], Union[RouteHandler, Tuple[Route, RouteHandler]]
]
RESTRICTED_ROUTE_CONTEXT = (
"ignore_body",
"stream",
"hosts",
"static",
"error_format",
"websocket",
)


class RouteMixin(metaclass=SanicMeta):
Expand Down Expand Up @@ -1046,24 +1039,12 @@ def visit_Return(self, node: Return) -> Any:

return types

def _build_route_context(self, raw):
def _build_route_context(self, raw: Dict[str, Any]) -> HashableDict:
ctx_kwargs = {
key.replace("ctx_", ""): raw.pop(key)
for key in {**raw}.keys()
if key.startswith("ctx_")
}
restricted = [
key for key in ctx_kwargs.keys() if key in RESTRICTED_ROUTE_CONTEXT
]
if restricted:
restricted_arguments = ", ".join(restricted)
raise AttributeError(
"Cannot use restricted route context: "
f"{restricted_arguments}. This limitation is only in place "
"until v22.9 when the restricted names will no longer be in"
"conflict. See https://github.com/sanic-org/sanic/issues/2303 "
"for more information."
)
if raw:
unexpected_arguments = ", ".join(raw.keys())
raise TypeError(
Expand Down
10 changes: 1 addition & 9 deletions sanic/mixins/startup.py
Expand Up @@ -559,7 +559,6 @@ def _helper(

def motd(
self,
serve_location: str = "",
server_settings: Optional[Dict[str, Any]] = None,
):
if (
Expand All @@ -569,14 +568,7 @@ def motd(
or os.environ.get("SANIC_SERVER_RUNNING")
):
return
if serve_location:
deprecation(
"Specifying a serve_location in the MOTD is deprecated and "
"will be removed.",
22.9,
)
else:
serve_location = self.get_server_location(server_settings)
serve_location = self.get_server_location(server_settings)
if self.config.MOTD:
logo = get_logo(coffee=self.state.coffee)
display, extra = self.get_motd_data(server_settings)
Expand Down
12 changes: 6 additions & 6 deletions sanic/router.py
Expand Up @@ -133,14 +133,14 @@ def add( # type: ignore
params.update({"requirements": {"host": host}})

route = super().add(**params) # type: ignore
route.ctx.ignore_body = ignore_body
route.ctx.stream = stream
route.ctx.hosts = hosts
route.ctx.static = static
route.ctx.error_format = error_format
route.extra.ignore_body = ignore_body
route.extra.stream = stream
route.extra.hosts = hosts
route.extra.static = static
route.extra.error_format = error_format

if error_format:
check_error_format(route.ctx.error_format)
check_error_format(route.extra.error_format)

routes.append(route)

Expand Down
2 changes: 1 addition & 1 deletion tests/test_app.py
Expand Up @@ -525,7 +525,7 @@ def test_multiple_uvloop_configs_display_warning(caplog):

counter = Counter([(r[1], r[2]) for r in caplog.record_tuples])

assert counter[(logging.WARNING, message)] == 2
assert counter[(logging.WARNING, message)] == 3


def test_cannot_run_fast_and_workers(app: Sanic):
Expand Down
11 changes: 3 additions & 8 deletions tests/test_config.py
Expand Up @@ -125,14 +125,9 @@ def test_env_w_custom_converter():


def test_env_lowercase():
with pytest.warns(None) as record:
environ["SANIC_test_answer"] = "42"
app = Sanic(name="Test")
assert app.config.test_answer == 42
assert str(record[0].message) == (
"[DEPRECATION v22.9] Lowercase environment variables will not be "
"loaded into Sanic config beginning in v22.9."
)
environ["SANIC_test_answer"] = "42"
app = Sanic(name="Test")
assert "test_answer" not in app.config
del environ["SANIC_test_answer"]


Expand Down

0 comments on commit 5052321

Please sign in to comment.