Skip to content

Commit

Permalink
fix linter issues
Browse files Browse the repository at this point in the history
  • Loading branch information
Goldziher committed Jul 21, 2022
1 parent 136d9f1 commit 26afa44
Show file tree
Hide file tree
Showing 32 changed files with 86 additions and 63 deletions.
2 changes: 1 addition & 1 deletion CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -231,7 +231,7 @@
[1.4.2]

- fix `status_code` missing from exception OpenAPI documentation @timwedde
- fix exceptioin `extra` being mistyped in OpenAPI documentation
- fix exception `extra` being mistyped in OpenAPI documentation

[1.5.0]

Expand Down
2 changes: 1 addition & 1 deletion CODE_OF_CONDUCT.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
We as members, contributors, and leaders pledge to make participation in our
community a harassment-free experience for everyone, regardless of age, body
size, visible or invisible disability, ethnicity, sex characteristics, gender
identity and expression, level of experience, education, socio-economic status,
identity and expression, level of experience, education, socioeconomic status,
nationality, personal appearance, race, religion, or sexual identity
and orientation.

Expand Down
2 changes: 1 addition & 1 deletion docs/governance-and-contribution.md
Original file line number Diff line number Diff line change
Expand Up @@ -17,5 +17,5 @@ you contribute substantially.
As stated above, not only code is considered a contribution - any and all assistance and involvement is welcome. Still,
this being a coding project fundamentally, coding contributions are integral. The easiest way to begin contributing is
to checkout the open issues - and reach out on our discord server or Matrix space. Please make sure to consult the `CONTRIBUTING.md`
file at the project's repository root for concerte instructions on how to setup a development environment and how to
file at the project's repository root for concrete instructions on how to setup a development environment and how to
submit a pull request.
2 changes: 1 addition & 1 deletion docs/usage/1-routers-and-controllers.md
Original file line number Diff line number Diff line change
Expand Up @@ -98,7 +98,7 @@ Aside from `path` and `route_handlers` which are required kwargs, you can also p
`Response` object and it must return a `Response` object.
- `after_response`: a sync or async callable executed after the `Response` is returned. The callable receives the
original `Request` object, and should return `None`.
`Respose` object and it must return a `Response` object.
`Response` object and it must return a `Response` object.
- `tags`: a list of `str`, which correlate to the [tag specification](https://spec.openapis.org/oas/latest.html#tag-object).
- `exception_handlers`: A dictionary mapping exceptions or exception codes to handler functions.
See [exception-handlers](17-exceptions#exception-handling).
Expand Down
24 changes: 18 additions & 6 deletions docs/usage/10-plugins.md
Original file line number Diff line number Diff line change
Expand Up @@ -141,7 +141,7 @@ class Address(Model):
created_at = fields.DatetimeField(auto_now_add=True)

event: fields.OneToOneRelation[Event] = fields.OneToOneField(
"models.Event", on_delete=fields.CASCADE, related_name="address", pk=True
"models.Event", related_name="address", pk=True
)

class Meta:
Expand Down Expand Up @@ -191,7 +191,7 @@ app = Starlite(
)
```

With the plugin in place, you can use any Tortoise model as type in route handelrs.
With the plugin in place, you can use any Tortoise model as type in route handlers.

## Creating Plugins

Expand All @@ -201,8 +201,20 @@ representing the model type to be used.
To create a plugin you must implement the following methods:

```python
from typing import Type, Any, Dict
from pydantic import BaseModel


class MyClass:
"""
The class for which we create a plugin. For example, could be a base ORM class such as "Model" or "Document" etc.
"""

...


def to_pydantic_model_class(
self, model_class: Type[T], **kwargs: Any
self, model_class: Type[MyClass], **kwargs: Any
) -> Type[BaseModel]:
"""
Given a model_class T, convert it to a subclass of the pydantic BaseModel
Expand All @@ -219,7 +231,7 @@ def is_plugin_supported_type(value: Any) -> bool:


def from_pydantic_model_instance(
self, model_class: Type[T], pydantic_model_instance: BaseModel
self, model_class: Type[MyClass], pydantic_model_instance: BaseModel
) -> T:
"""
Given an instance of a pydantic model created using a plugin's 'to_pydantic_model_class',
Expand All @@ -230,14 +242,14 @@ def from_pydantic_model_instance(
...


def to_dict(self, model_instance: T) -> Dict[str, Any]:
def to_dict(self, model_instance: MyClass) -> Dict[str, Any]:
"""
Given an instance of a model supported by the plugin, return a dictionary of serializable values.
"""
...


def from_dict(self, model_class: Type[T], **kwargs: Any) -> T:
def from_dict(self, model_class: Type[MyClass], **kwargs: Any) -> MyClass:
"""
Given a class supported by this plugin and a dict of values, create an instance of the class
"""
Expand Down
4 changes: 2 additions & 2 deletions docs/usage/11-data-transfer-objects.md
Original file line number Diff line number Diff line change
Expand Up @@ -153,7 +153,7 @@ class MyClassDTO(BaseModel):

## Add New Fields

You add fields that do not exist in the original model by passing in a `field_defintions` dictionary. This dictionary
You add fields that do not exist in the original model by passing in a `field_definitions` dictionary. This dictionary
should have field names as keys, and a tuple following the format supported by the [pydantic create_model helper](https://pydantic-docs.helpmanual.io/usage/models/#dynamic-model-creation):

1. For required fields use a tuple of type + ellipsis, for example `(str, ...)`.
Expand Down Expand Up @@ -200,7 +200,6 @@ from sqlalchemy.orm import declarative_base
from starlite import DTOFactory
from starlite.plugins.sql_alchemy import SQLAlchemyPlugin


dto_factory = DTOFactory(plugins=[SQLAlchemyPlugin()])

Base = declarative_base()
Expand Down Expand Up @@ -229,6 +228,7 @@ When you have an instance of a DTO model, you can convert it into a model instan
from starlite import get


@get()
def create_company(data: CompanyDTO) -> Company:
company_instance = data.to_model_instance()
...
Expand Down
4 changes: 2 additions & 2 deletions docs/usage/12-openapi.md
Original file line number Diff line number Diff line change
Expand Up @@ -122,9 +122,9 @@ Starlite includes a pre-configured controller called `OpenAPIController` which e
<!-- prettier-ignore -->
!!! important
prior to version 0.3.0 there was only a single download endpoint by default and its path was `/schema`
prior to version 0.8.0, the redoc UI was found at `/schema/redoc` and has since been moved to `/schema` for ease of use.
prior to version 0.8.0, the Redoc UI was found at `/schema/redoc` and has since been moved to `/schema` for ease of use.

If you would like to modify the endpoints, add new endpoints, change the styling of redoc etc., you can subclass the
If you would like to modify the endpoints, add new endpoints, change the styling of Redoc etc., you can subclass the
`OpenAPIController` and then pass your subclass to the `OpenAPIConfig`.

For example, lets say we wanted to change the base path from "/schema" to "/api-docs":
Expand Down
13 changes: 10 additions & 3 deletions docs/usage/15-templating.md
Original file line number Diff line number Diff line change
Expand Up @@ -53,16 +53,23 @@ dictionary specifying context data that is passed to the engine.
## Defining a Custom Template Engine

If you wish to use another templating engine, you can easily do so by
implemnting `starlite.template.TemplateEngineProtocol`. This class accepts a generic argument `T` which should be the
implementing `starlite.template.TemplateEngineProtocol`. This class accepts a generic argument `T` which should be the
template class, and it specifies two methods:

```python
class TemplateEngineProtocol(Protocol[T]):
from typing import Protocol, Union, List
from pydantic import DirectoryPath

# the template class of the respective library
from my_lib import MyTemplate


class TemplateEngineProtocol(Protocol[MyTemplate]):
def __init__(self, directory: Union[DirectoryPath, List[DirectoryPath]]) -> None:
"""Builds a template engine."""
...

def get_template(self, name: str) -> T:
def get_template(self, name: str) -> MyTemplate:
"""Loads the template with name and returns it."""
...
```
Expand Down
2 changes: 1 addition & 1 deletion docs/usage/17-exceptions.md
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ Starlite also offers several pre-configured **exception subclasses** with pre-se
- `InternalServerException`: status code 500.
- `ServiceUnavailableException`: status code 503.

When a value fails `pydantic` validaton, the result will be a `ValidationException` with the `extra` key set to the
When a value fails `pydantic` validation, the result will be a `ValidationException` with the `extra` key set to the
pydantic validation errors. Thus this data will be made available for the API consumers by default.

## Exception Handling
Expand Down
4 changes: 2 additions & 2 deletions docs/usage/2-route-handlers/0_route_handlers_concept.md
Original file line number Diff line number Diff line change
Expand Up @@ -123,9 +123,9 @@ def my_request_handler(

Starlite enforces strict type annotations. Functions decorated by a route handler **must** have all their kwargs and
return value type annotated. If a type annotation is missing, an `ImproperlyConfiguredException` will be raised during
the application bootup process.
the application boot-up process.

There are several reasons for why this limitation is enforeced:
There are several reasons for why this limitation is enforced:

1. to ensure best practices
2. to ensure consistent OpenAPI schema generation
Expand Down
2 changes: 1 addition & 1 deletion docs/usage/2-route-handlers/3_asgi_route_handlers.md
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ async def my_asgi_app(scope: Scope, receive: Receive, send: Send) -> None:

In difference to the other route handlers, the `asgi` route handler accepts only 3 kwargs that **must** be defined:

- `scope`, a mapping of values describing the asgi connection. It always includes a `type` key, with the values being
- `scope`, a mapping of values describing the ASGI connection. It always includes a `type` key, with the values being
either `http` or `websocket`, and a `path` key. If the type is `http`, the scope dictionary will also include
a `method` key with the value being one of `DELETE, GET, POST, PATCH, PUT, HEAD`.
- `receive`, an injected function by which the ASGI application receives messages.
Expand Down
4 changes: 2 additions & 2 deletions docs/usage/3-parameters.md
Original file line number Diff line number Diff line change
Expand Up @@ -263,7 +263,7 @@ Starlite has a "layered" architecture, which is also evident in that one can dec
route handlers - as in the above example, but on different layers of the application:

```python
from starlite import Starlite, Controller, Router, Parameter
from starlite import Starlite, Controller, Router, Parameter, get


class MyController(Controller):
Expand Down Expand Up @@ -316,7 +316,7 @@ required for the router handler function that declares it as an `str` and not an
provided, it will be tested against the provided regex.

`controller_param` is a query param with the key `controller_param`. It has an `lt=100` defined on the controller, which
means the provided value must be less than 100. Yet the route handler redeclares it with an `lt=50`, which means for the
means the provided value must be less than 100. Yet the route handler re-declares it with an `lt=50`, which means for the
route handler this value must be less than 50.

Finally `local_param` is a route handler local query parameter, and `path_param` is a path parameter.
Expand Down
2 changes: 1 addition & 1 deletion docs/usage/5-responses.md
Original file line number Diff line number Diff line change
Expand Up @@ -354,7 +354,7 @@ from starlite import get, Response

@get(path="/")
def my_route_handler() -> Response:
return Response(...)
return Response(..., media_type=..., status_code=...)
```

<!-- prettier-ignore -->
Expand Down
13 changes: 9 additions & 4 deletions starlite/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -120,10 +120,15 @@ def dict(self, *args, **kwargs) -> Dict[str, Any]: # type: ignore[no-untyped-de
Returns:
Dict[str, Any]: dictionary representation of the selected CompressionConfig. Only columns for the selected backend are included
"""
brotli_keys = set(
{"minimum_size", "brotli_quality", "brotli_mode", "brotli_lgwin", "brotli_lgblock", "brotli_gzip_fallback"}
)
gzip_keys = set({"minimum_size", "gzip_compress_level"})
brotli_keys = {
"minimum_size",
"brotli_quality",
"brotli_mode",
"brotli_lgwin",
"brotli_lgblock",
"brotli_gzip_fallback",
}
gzip_keys = {"minimum_size", "gzip_compress_level"}
if self.backend == CompressionBackend.GZIP:
kwargs["include"] = gzip_keys
elif self.backend == CompressionBackend.BROTLI:
Expand Down
2 changes: 1 addition & 1 deletion starlite/dto.py
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,7 @@ def from_model_instance(cls, model_instance: T) -> "DTO[T]":
@classmethod
async def from_model_instance_async(cls, model_instance: T) -> "DTO[T]":
"""
Given an instance of the source model, create an instance of the given DTO subclass asyncrounesouly
Given an instance of the source model, create an instance of the given DTO subclass asynchronously
"""
if (
cls.dto_source_plugin is not None
Expand Down
1 change: 1 addition & 0 deletions starlite/handlers/http.py
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@
Middleware,
ResponseHeader,
)
from starlite.utils import is_async_callable

if TYPE_CHECKING:
from starlite.app import Starlite
Expand Down
2 changes: 1 addition & 1 deletion starlite/kwargs.py
Original file line number Diff line number Diff line change
Expand Up @@ -139,7 +139,7 @@ def create_parameter_definition(
allow_none: bool, field_info: FieldInfo, field_name: str, path_parameters: Set[str], is_sequence: bool
) -> ParameterDefinition:
"""
Creates a ParameterDefition for the given pydantic FieldInfo instance and inserts it into the correct parameter set
Creates a ParameterDefinition for the given pydantic FieldInfo instance and inserts it into the correct parameter set
"""
extra = field_info.extra
is_required = extra.get(EXTRA_KEY_REQUIRED, True)
Expand Down
2 changes: 1 addition & 1 deletion starlite/plugins/sql_alchemy.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@

class SQLAlchemyPlugin(PluginProtocol[DeclarativeMeta]):
def __init__(self) -> None:
# a map object that maps SQLAlchemy entity qualnames to pydantic BaseModel subclasses
# a map object that maps SQLAlchemy entity qualified names to pydantic BaseModel subclasses
self.model_namespace_map: Dict[str, "Type[BaseModel]"] = {}

@staticmethod
Expand Down
9 changes: 5 additions & 4 deletions starlite/plugins/tortoise_orm.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,9 +21,10 @@ class TortoiseORMPlugin(PluginProtocol[Model]):
_models_map: Dict[Type[Model], Type[PydanticModel]] = {}
_data_models_map: Dict[Type[Model], Type[PydanticModel]] = {}

def _create_pydantic_model(self, model_class: Type[Model], **kwargs: Dict[str, Any]) -> Type[PydanticModel]:
@staticmethod
def _create_pydantic_model(model_class: Type[Model], **kwargs: Dict[str, Any]) -> Type[PydanticModel]:
"""
Takes a tortoitse model_class instance and convert it to a subclass of the tortoise PydanticModel.
Takes a tortoise model_class instance and convert it to a subclass of the tortoise PydanticModel.
It fixes some issues with the result of the tortoise model creator.
"""
pydantic_model = cast(Type[PydanticModel], pydantic_model_creator(model_class, **kwargs))
Expand All @@ -48,11 +49,11 @@ def _create_pydantic_model(self, model_class: Type[Model], **kwargs: Dict[str, A

def to_pydantic_model_class(self, model_class: Type[Model], **kwargs: Any) -> Type[PydanticModel]:
"""
Given a tortoitse model_class instance, convert it to a subclass of the tortoise PydanticModel
Given a tortoise model_class instance, convert it to a subclass of the tortoise PydanticModel
Since incoming request body's cannot and should not include values for
related fields, pk fields and read only fields in tortoise-orm, we generate two different kinds of pydantic models here:
- the first is a regular pydantic model, and the othre is for the "data" kwarg only, which is further sanitized.
- the first is a regular pydantic model, and the other is for the "data" kwarg only, which is further sanitized.
This function uses memoization to ensure we don't recompute unnecessarily.
"""
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ class Store(GenericModel, Generic[T]):

model: Type[T]

def get(self, id: str) -> Optional[T]:
def get(self, value_id: str) -> Optional[T]:
raise NotImplementedError


Expand All @@ -26,7 +26,7 @@ class Item(BaseModel):
class DictStore(Store[Item]):
"""In-memory store implementation"""

def get(self, id: str) -> Optional[T]:
def get(self, value_id: str) -> Optional[T]:
return None


Expand Down
2 changes: 1 addition & 1 deletion tests/handlers/http/test_sync.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ def sync_handler() -> str:
"handler",
[
get("/", media_type=MediaType.TEXT, sync_to_thread=True)(sync_handler),
get("/", media_type=MediaType.TEXT, sync_to_thread=False)(sync_handler),
get("/", media_type=MediaType.TEXT)(sync_handler),
],
)
def test_sync_to_thread(handler: HTTPRouteHandler) -> None:
Expand Down
4 changes: 2 additions & 2 deletions tests/handlers/http/test_to_response.py
Original file line number Diff line number Diff line change
Expand Up @@ -53,10 +53,10 @@ async def test_function(data: Person) -> Person:


async def slow_numbers(minimum: int, maximum: int) -> Any:
yield ("<html><body><ul>")
yield "<html><body><ul>"
for number in range(minimum, maximum + 1):
yield "<li>%d</li>" % number
yield ("</ul></body></html>")
yield "</ul></body></html>"


generator = slow_numbers(1, 10)
Expand Down
4 changes: 2 additions & 2 deletions tests/kwargs/test_json_data.py
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
from starlette.status import HTTP_201_CREATED

from starlite import Body, RequestEncodingType, post
from starlite import Body, post
from starlite.testing import create_test_client
from tests.kwargs import Form


def test_request_body_json() -> None:
body = Body(media_type=RequestEncodingType.JSON)
body = Body()

test_path = "/test"
data = Form(name="Moishe Zuchmir", age=30, programmer=True).dict()
Expand Down
6 changes: 3 additions & 3 deletions tests/kwargs/test_validations.py
Original file line number Diff line number Diff line change
Expand Up @@ -107,7 +107,7 @@ def multi_part_dependency(data: Dict[str, Any] = Body(media_type=RequestEncoding
return data


def json_dependency(data: Dict[str, Any] = Body(media_type=RequestEncodingType.JSON)) -> Dict[str, Any]:
def json_dependency(data: Dict[str, Any] = Body()) -> Dict[str, Any]:
assert data
return data

Expand Down Expand Up @@ -144,8 +144,8 @@ def test_dependency_data_kwarg_validation_success_scenarios(handler: HTTPRouteHa
@pytest.mark.parametrize(
"body, dependency",
[
[Body(media_type=RequestEncodingType.JSON), url_encoded_dependency],
[Body(media_type=RequestEncodingType.JSON), multi_part_dependency],
[Body(), url_encoded_dependency],
[Body(), multi_part_dependency],
[Body(media_type=RequestEncodingType.URL_ENCODED), json_dependency],
[Body(media_type=RequestEncodingType.URL_ENCODED), multi_part_dependency],
[Body(media_type=RequestEncodingType.MULTI_PART), json_dependency],
Expand Down
Loading

0 comments on commit 26afa44

Please sign in to comment.