Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Chore: Format code using Ruff, and fix linter errors #531

Merged
merged 5 commits into from
Oct 24, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
71 changes: 69 additions & 2 deletions pyproject.toml
Original file line number Diff line number Diff line change
@@ -1,3 +1,70 @@
[build-system]
requires = ["setuptools", "wheel"]
build-backend = "setuptools.build_meta:__legacy__"
build-backend = "setuptools.build_meta"
requires = [
"setuptools>=42", # At least v42 of setuptools required.
]

[tool.ruff]
line-length = 90

extend-exclude = [
"docs/source/conf.py",
"setup.py",
]

lint.select = [
# Builtins
"A",
# Bugbear
"B",
# comprehensions
"C4",
# Pycodestyle
"E",
# eradicate
"ERA",
# Pyflakes
"F",
# isort
"I",
# pandas-vet
"PD",
# return
"RET",
# Bandit
"S",
# print
"T20",
"W",
# flake8-2020
"YTT",
]

lint.extend-ignore = [
"S101", # Allow use of `assert`.
]

lint.per-file-ignores."tests/*" = [
"ERA001", # Found commented-out code.
"S101", # Allow use of `assert`, and `print`.
]

[tool.pytest.ini_options]
addopts = """
-rfEXs -p pytester --strict-markers --verbosity=3
--cov --cov-report=term-missing --cov-report=xml
"""
filterwarnings = [
"error::UserWarning",
]
log_level = "DEBUG"
log_cli_level = "DEBUG"
log_format = "%(asctime)-15s [%(name)-36s] %(levelname)-8s: %(message)s"
minversion = "2.0"
testpaths = [
"responder",
"tests",
]
markers = [
]
xfail_strict = true
4 changes: 0 additions & 4 deletions pytest.ini

This file was deleted.

9 changes: 8 additions & 1 deletion responder/__init__.py
Original file line number Diff line number Diff line change
@@ -1,2 +1,9 @@
from .core import *
from . import ext
from .core import API, Request, Response

__all__ = [
"API",
"Request",
"Response",
"ext",
]
49 changes: 25 additions & 24 deletions responder/api.py
Original file line number Diff line number Diff line change
@@ -1,29 +1,23 @@
import json
import os

from pathlib import Path

import jinja2
import uvicorn
from starlette.exceptions import ExceptionMiddleware
from starlette.middleware.wsgi import WSGIMiddleware
from starlette.middleware.errors import ServerErrorMiddleware
from starlette.middleware.cors import CORSMiddleware
from starlette.middleware.errors import ServerErrorMiddleware
from starlette.middleware.gzip import GZipMiddleware
from starlette.middleware.httpsredirect import HTTPSRedirectMiddleware
from starlette.middleware.trustedhost import TrustedHostMiddleware
from starlette.middleware.sessions import SessionMiddleware
from starlette.staticfiles import StaticFiles
from starlette.middleware.trustedhost import TrustedHostMiddleware
from starlette.testclient import TestClient
from starlette.websockets import WebSocket

from . import models, status_codes
from . import status_codes
from .background import BackgroundQueue
from .ext.schema import OpenAPISchema as OpenAPISchema
from .formats import get_formats
from .routes import Router
from .statics import DEFAULT_API_THEME, DEFAULT_CORS_PARAMS, DEFAULT_SECRET_KEY
from .ext.schema import OpenAPISchema as OpenAPISchema
from .staticfiles import StaticFiles
from .statics import DEFAULT_CORS_PARAMS, DEFAULT_SECRET_KEY
from .templates import Templates


Expand All @@ -34,7 +28,7 @@ class API:
:param templates_dir: The directory to use for templates. Will be created for you if it doesn't already exist.
:param auto_escape: If ``True``, HTML and XML templates will automatically be escaped.
:param enable_hsts: If ``True``, send all responses to HTTPS URLs.
"""
""" # noqa: E501

status_codes = status_codes

Expand All @@ -47,7 +41,7 @@ def __init__(
description=None,
terms_of_service=None,
contact=None,
license=None,
license=None, # noqa: A002
openapi=None,
openapi_route="/schema.yml",
static_dir="static",
Expand Down Expand Up @@ -84,7 +78,7 @@ def __init__(
# if not debug:
# raise RuntimeError(
# "You need to specify `allowed_hosts` when debug is set to False"
# )
# ) # noqa: ERA001
allowed_hosts = ["*"]
self.allowed_hosts = allowed_hosts

Expand Down Expand Up @@ -170,11 +164,12 @@ def path_matches_route(self, path):
"""Given a path portion of a URL, tests that it matches against any registered route.

:param path: The path portion of a URL, to test all known routes against.
"""
""" # noqa: E501 (Line too long)
for route in self.router.routes:
match, _ = route.matches(path)
if match:
return route
return None

def add_route(
self,
Expand All @@ -192,8 +187,9 @@ def add_route(
:param route: A string representation of the route.
:param endpoint: The endpoint for the route -- can be a callable, or a class.
:param default: If ``True``, all unknown requests will route to this view.
:param static: If ``True``, and no endpoint was passed, render "static/index.html", and it will become a default route.
"""
:param static: If ``True``, and no endpoint was passed, render "static/index.html".
Also, it will become a default route.
""" # noqa: E501

# Path
if static:
Expand Down Expand Up @@ -229,7 +225,8 @@ def redirect(
:param resp: The Response to mutate.
:param location: The location of the redirect.
:param set_text: If ``True``, sets the Redirect body content automatically.
:param status_code: an `API.status_codes` attribute, or an integer, representing the HTTP status code of the redirect.
:param status_code: an `API.status_codes` attribute, or an integer,
representing the HTTP status code of the redirect.
"""
resp.redirect(location, set_text=set_text, status_code=status_code)

Expand Down Expand Up @@ -284,13 +281,15 @@ def decorator(f):
def mount(self, route, app):
"""Mounts an WSGI / ASGI application at a given route.

:param route: String representation of the route to be used (shouldn't be parameterized).
:param route: String representation of the route to be used
(shouldn't be parameterized).
:param app: The other WSGI / ASGI app.
"""
self.router.apps.update({route: app})

def session(self, base_url="http://;"):
"""Testing HTTP client. Returns a Requests session object, able to send HTTP requests to the Responder application.
"""Testing HTTP client. Returns a Requests session object,
able to send HTTP requests to the Responder application.

:param base_url: The URL to mount the connection adaptor to.
"""
Expand All @@ -310,11 +309,13 @@ def url_for(self, endpoint, **params):

def template(self, filename, *args, **kwargs):
"""Renders the given `jinja2 <http://jinja.pocoo.org/docs/>`_ template, with provided values supplied.

Note: The current ``api`` instance is by default passed into the view. This is set in the dict ``api.jinja_values_base``.

:param filename: The filename of the jinja2 template, in ``templates_dir``.
:param *args: Data to pass into the template.
:param *kwargs: Date to pass into the template.
"""
""" # noqa: E501
return self.templates.render(filename, *args, **kwargs)

def template_string(self, source, *args, **kwargs):
Expand All @@ -323,7 +324,7 @@ def template_string(self, source, *args, **kwargs):
:param source: The template to use.
:param *args: Data to pass into the template.
:param **kwargs: Data to pass into the template.
"""
""" # noqa: E501
return self.templates.render_string(source, *args, **kwargs)

def serve(self, *, address=None, port=None, **options):
Expand All @@ -334,11 +335,11 @@ def serve(self, *, address=None, port=None, **options):
:param address: The address to bind to.
:param port: The port to bind to. If none is provided, one will be selected at random.
:param options: Additional keyword arguments to send to ``uvicorn.run()``.
"""
""" # noqa: E501

if "PORT" in os.environ:
if address is None:
address = "0.0.0.0"
address = "0.0.0.0" # noqa: S104
port = int(os.environ["PORT"])

if address is None:
Expand Down
7 changes: 3 additions & 4 deletions responder/background.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
import asyncio
import functools
import concurrent.futures
import multiprocessing
import traceback

from starlette.concurrency import run_in_threadpool


Expand All @@ -27,7 +27,7 @@ def task(self, f):
def on_future_done(fs):
try:
fs.result()
except:
except Exception:
traceback.print_exc()

def do_task(*args, **kwargs):
Expand All @@ -40,5 +40,4 @@ def do_task(*args, **kwargs):
async def __call__(self, func, *args, **kwargs) -> None:
if asyncio.iscoroutinefunction(func):
return await asyncio.ensure_future(func(*args, **kwargs))
else:
return await run_in_threadpool(func, *args, **kwargs)
return await run_in_threadpool(func, *args, **kwargs)
6 changes: 6 additions & 0 deletions responder/core.py
Original file line number Diff line number Diff line change
@@ -1,2 +1,8 @@
from .api import API
from .models import Request, Response

__all__ = [
"API",
"Request",
"Response",
]
10 changes: 3 additions & 7 deletions responder/ext/schema/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,8 @@
from apispec import APISpec, yaml_utils
from apispec.ext.marshmallow import MarshmallowPlugin

from responder.statics import DEFAULT_API_THEME
from responder import status_codes
from responder.statics import DEFAULT_API_THEME


class OpenAPISchema:
Expand All @@ -21,7 +21,7 @@ def __init__(
description=None,
terms_of_service=None,
contact=None,
license=None,
license=None, # noqa: A002
openapi=None,
openapi_route="/schema.yml",
docs_route="/docs/",
Expand Down Expand Up @@ -60,7 +60,6 @@ def __init__(

@property
def _apispec(self):

info = {}
if self.description is not None:
info["description"] = self.description
Expand All @@ -81,9 +80,7 @@ def _apispec(self):

for route in self.app.router.routes:
if route.description:
operations = yaml_utils.load_operations_from_docstring(
route.description
)
operations = yaml_utils.load_operations_from_docstring(route.description)
spec.path(path=route.route, operations=operations)

for name, schema in self.schemas.items():
Expand Down Expand Up @@ -123,7 +120,6 @@ def decorator(f):

@property
def docs(self):

loader = jinja2.PrefixLoader(
{
self.docs_theme: jinja2.PackageLoader(
Expand Down
Loading
Loading