From 7b44751ec27f534583c370cfed86f39be447ed17 Mon Sep 17 00:00:00 2001 From: Dmitry Chaplinsky Date: Sun, 19 Jul 2026 14:40:23 +0000 Subject: [PATCH 1/5] Revive for modern Python (2.0): native async, pyproject packaging, CI - Rewrite the decorator with native async/await: asyncio.coroutine was removed in Python 3.11, which made the library unusable there. Plain (non-async) handlers remain supported via inspect.iscoroutinefunction - Handlers may return a (data, status) tuple to set the response status code (closes the long-standing request in #180) - Document the handler signature (data, request) in README, answering #246 - Fix __ALL__ typo (a misnamed tuple) to a proper __all__ - Replace setup.py/setup.cfg/Makefile/tox/travis/pyup scaffolding with pyproject.toml: version 2.0 (single-sourced; the repo previously carried three conflicting versions), requires-python >=3.9, aiohttp>=3.8, jsonschema>=3.0, py.typed marker; drop the console_scripts entry point that referenced a module that never existed; remove the stale sphinx skeleton - Modernize tests for current aiohttp/pytest-aiohttp (no loop argument), add coverage for the status tuple and sync handlers - tests.yml: matrix on CPython 3.9-3.13; publish.yml: PyPI trusted publishing on v* tags or manual dispatch - README badges and examples refreshed; HISTORY updated Co-Authored-By: Claude Fable 5 Claude-Session: https://claude.ai/code/session_01Ha16zNy2fDMdrZBMQGgpBt --- .github/workflows/publish.yml | 41 +++++ .github/workflows/tests.yml | 27 ++++ .travis.yml | 29 ---- HISTORY.rst | 12 ++ MANIFEST.in | 13 -- Makefile | 88 ----------- README.rst | 33 ++-- aiohttp_validate/__init__.py | 59 ++++--- aiohttp_validate/py.typed | 0 docs/Makefile | 177 --------------------- docs/authors.rst | 1 - docs/conf.py | 275 --------------------------------- docs/contributing.rst | 1 - docs/history.rst | 1 - docs/index.rst | 25 --- docs/installation.rst | 51 ------ docs/make.bat | 242 ----------------------------- docs/readme.rst | 1 - docs/usage.rst | 7 - pyproject.toml | 55 +++++++ requirements_dev.txt | 14 -- setup.cfg | 18 --- setup.py | 56 ------- tests/test_aiohttp_validate.py | 63 ++++++-- tox.ini | 22 --- travis_pypi_setup.py | 122 --------------- 26 files changed, 239 insertions(+), 1194 deletions(-) create mode 100644 .github/workflows/publish.yml create mode 100644 .github/workflows/tests.yml delete mode 100644 .travis.yml delete mode 100644 MANIFEST.in delete mode 100644 Makefile create mode 100644 aiohttp_validate/py.typed delete mode 100644 docs/Makefile delete mode 100644 docs/authors.rst delete mode 100755 docs/conf.py delete mode 100644 docs/contributing.rst delete mode 100644 docs/history.rst delete mode 100644 docs/index.rst delete mode 100644 docs/installation.rst delete mode 100644 docs/make.bat delete mode 100644 docs/readme.rst delete mode 100644 docs/usage.rst create mode 100644 pyproject.toml delete mode 100644 requirements_dev.txt delete mode 100644 setup.cfg delete mode 100644 setup.py delete mode 100644 tox.ini delete mode 100644 travis_pypi_setup.py diff --git a/.github/workflows/publish.yml b/.github/workflows/publish.yml new file mode 100644 index 0000000..fb6feb0 --- /dev/null +++ b/.github/workflows/publish.yml @@ -0,0 +1,41 @@ +name: Publish to PyPI + +on: + push: + tags: ["v*"] + workflow_dispatch: + +jobs: + build: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + + - uses: actions/setup-python@v5 + with: + python-version: "3.13" + + - name: Build sdist and wheel + run: | + pip install build + python -m build + + - uses: actions/upload-artifact@v4 + with: + name: dist + path: dist/ + + publish: + needs: build + runs-on: ubuntu-latest + environment: pypi + permissions: + id-token: write + + steps: + - uses: actions/download-artifact@v4 + with: + name: dist + path: dist/ + + - uses: pypa/gh-action-pypi-publish@release/v1 diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml new file mode 100644 index 0000000..17370c4 --- /dev/null +++ b/.github/workflows/tests.yml @@ -0,0 +1,27 @@ +name: Tests + +on: + push: + branches: [master] + pull_request: + +jobs: + test: + runs-on: ubuntu-latest + strategy: + fail-fast: false + matrix: + python-version: ["3.9", "3.10", "3.11", "3.12", "3.13"] + + steps: + - uses: actions/checkout@v4 + + - uses: actions/setup-python@v5 + with: + python-version: ${{ matrix.python-version }} + + - name: Install package with test dependencies + run: pip install -e .[test] + + - name: Run tests + run: pytest -v diff --git a/.travis.yml b/.travis.yml deleted file mode 100644 index c5b27b1..0000000 --- a/.travis.yml +++ /dev/null @@ -1,29 +0,0 @@ -# This file was autogenerated and will overwrite each time you run travis_pypi_setup.py -deploy: - true: - condition: $TOXENV == py35 - repo: dchaplinsky/aiohttp_validate - tags: true - password: - secure: !!binary | - S1FTYXdNWmlWMUtyVzlicHlYbTBXNjc1TnpxZjduV3MrNFNlaEcwY3VHcWIwcWpxREZlQjhPRXlZ - Wkd5UkVzYzRnUThzSEhLVEdyL000NEQrYktiOTh4TUI3a2dMc2lhamZXcjFYb1l1NVAzREZjRkpj - WlE2dXZOYzlPSU5ubzZ2ei9ySnc5anVqbVlQbEEyMEw2WUs4QXRuL3lFSCs4ZWRCaDkvNVBCa0xp - MXFMTnVrNFVEekdTTmNrKzBCR3lqN0dzRVhUYzNDN1VpejU2T1N6TGRSQVoyM1dzanVja0pzYVdz - N0I5eHVkaXB0R3l3VTRrSVJyc3drRklDR2JZaWJsSDRaWWt4NUZZaU1sZlB6b3NRR2tIbCtRSnFn - MktBcGxVTzZTTG80ZGR5bjEzMnZxUEFGdGx2NEllZlREVytWcjZERzZyTjVLUWZFMDhxVDVsUi9U - WGVmNjluNGNEMEIzVk54bHptUkRtb3V2MFFnYThsYk9jU01GU2UwVWRRTERaZ3lGV05UMDZqbno1 - TmllSllDSVZVblQ4Z1FPQmFyejRZbGtjU01ycTYvUjM5MzB5SWI0SFVhcnk2RTAwWmQ4SlJIaFgr - WlNhemZEY3cxbXVDT3V4MDI3VjRDcnd0bGQ2RFVWcTVMK0gvb2wwR1cyNnV5ZHA1dG8zV0lkenlw - dHhLRHFDQlpYRXhIdVExSFNMQzJpWmJmM2dKT3YwcWI3cjlwTVFEOVdvOVd0UGhMUCtCM2U2c3gv - TElhZHhFVGFOUXREenVNOVpSQUtzOHdxYytTZ09hQVBtUEo5ZEVkbW9idGRIaE83ZnRVNVZ0aGwy - bDdqWTdSOVpDNHV3emsvNkJ0NjBJN09nMEdqZmdEWng0SGdocWplL0lVZ0cwUURWbVM2WTQ4dUU9 - distributions: sdist bdist_wheel - user: dchaplinsky - provider: pypi -env: -- TOXENV=py35 -install: pip install -U tox -language: python -python: 3.5 -script: tox -e ${TOXENV} diff --git a/HISTORY.rst b/HISTORY.rst index 9e0b247..a135a7d 100644 --- a/HISTORY.rst +++ b/HISTORY.rst @@ -2,6 +2,18 @@ History ======= +2.0 (2026-07-19) +------------------ + +* Revived for modern Python: works on Python 3.9-3.13 (the removal of + ``asyncio.coroutine`` in Python 3.11 had made the library unusable there). +* Handlers may return a ``(data, status)`` tuple to set the response status. +* Plain (non-async) handlers are still supported. +* Type hints and a ``py.typed`` marker. +* Modern packaging (``pyproject.toml``), tests on GitHub Actions, releases + via PyPI trusted publishing. + + 1.0.0 (2016-12-12) ------------------ diff --git a/MANIFEST.in b/MANIFEST.in deleted file mode 100644 index 63895e7..0000000 --- a/MANIFEST.in +++ /dev/null @@ -1,13 +0,0 @@ - -include AUTHORS.rst - -include CONTRIBUTING.rst -include HISTORY.rst -include LICENSE -include README.rst - -recursive-include tests * -recursive-exclude * __pycache__ -recursive-exclude * *.py[co] - -recursive-include docs *.rst conf.py Makefile make.bat *.jpg *.png *.gif diff --git a/Makefile b/Makefile deleted file mode 100644 index d73af27..0000000 --- a/Makefile +++ /dev/null @@ -1,88 +0,0 @@ -.PHONY: clean clean-test clean-pyc clean-build docs help -.DEFAULT_GOAL := help -define BROWSER_PYSCRIPT -import os, webbrowser, sys -try: - from urllib import pathname2url -except: - from urllib.request import pathname2url - -webbrowser.open("file://" + pathname2url(os.path.abspath(sys.argv[1]))) -endef -export BROWSER_PYSCRIPT - -define PRINT_HELP_PYSCRIPT -import re, sys - -for line in sys.stdin: - match = re.match(r'^([a-zA-Z_-]+):.*?## (.*)$$', line) - if match: - target, help = match.groups() - print("%-20s %s" % (target, help)) -endef -export PRINT_HELP_PYSCRIPT -BROWSER := python -c "$$BROWSER_PYSCRIPT" - -help: - @python -c "$$PRINT_HELP_PYSCRIPT" < $(MAKEFILE_LIST) - -clean: clean-build clean-pyc clean-test ## remove all build, test, coverage and Python artifacts - - -clean-build: ## remove build artifacts - rm -fr build/ - rm -fr dist/ - rm -fr .eggs/ - find . -name '*.egg-info' -exec rm -fr {} + - find . -name '*.egg' -exec rm -f {} + - -clean-pyc: ## remove Python file artifacts - find . -name '*.pyc' -exec rm -f {} + - find . -name '*.pyo' -exec rm -f {} + - find . -name '*~' -exec rm -f {} + - find . -name '__pycache__' -exec rm -fr {} + - -clean-test: ## remove test and coverage artifacts - rm -fr .tox/ - rm -f .coverage - rm -fr htmlcov/ - -lint: ## check style with flake8 - flake8 aiohttp_validate tests - -test: ## run tests quickly with the default Python - py.test - - -test-all: ## run tests on every Python version with tox - tox - -coverage: ## check code coverage quickly with the default Python - coverage run --source aiohttp_validate py.test - - coverage report -m - coverage html - $(BROWSER) htmlcov/index.html - -docs: ## generate Sphinx HTML documentation, including API docs - rm -f docs/aiohttp_validate.rst - rm -f docs/modules.rst - sphinx-apidoc -o docs/ aiohttp_validate - $(MAKE) -C docs clean - $(MAKE) -C docs html - $(BROWSER) docs/_build/html/index.html - -servedocs: docs ## compile the docs watching for changes - watchmedo shell-command -p '*.rst' -c '$(MAKE) -C docs html' -R -D . - -release: clean ## package and upload a release - python setup.py sdist upload - python setup.py bdist_wheel upload - -dist: clean ## builds source and wheel package - python setup.py sdist - python setup.py bdist_wheel - ls -l dist - -install: clean ## install the package to the active Python's site-packages - python setup.py install diff --git a/README.rst b/README.rst index 3747fa4..0468882 100644 --- a/README.rst +++ b/README.rst @@ -6,19 +6,11 @@ aiohttp_validate .. image:: https://img.shields.io/pypi/v/aiohttp_validate.svg :target: https://pypi.python.org/pypi/aiohttp_validate -.. image:: https://img.shields.io/travis/dchaplinsky/aiohttp_validate.svg - :target: https://travis-ci.org/dchaplinsky/aiohttp_validate +.. image:: https://github.com/dchaplinsky/aiohttp_validate/actions/workflows/tests.yml/badge.svg + :target: https://github.com/dchaplinsky/aiohttp_validate/actions/workflows/tests.yml -.. image:: https://readthedocs.org/projects/aiohttp-validate/badge/?version=latest - :target: https://aiohttp-validate.readthedocs.io/en/latest/?badge=latest - :alt: Documentation Status -.. image:: https://pyup.io/repos/github/dchaplinsky/aiohttp_validate/shield.svg - :target: https://pyup.io/repos/github/dchaplinsky/aiohttp_validate/ - :alt: Updates - - -Simple library that helps you validate your API endpoints requests/responses with jsonschema_. Documentation is also available here at https://aiohttp-validate.readthedocs.io. +Simple library that helps you validate your API endpoints requests/responses with jsonschema_. Requires Python 3.9+ and aiohttp 3.8+. @@ -57,6 +49,19 @@ Complete example of validation for `text tokenization microservice`_:: async def tokenize_text_handler(request, *args): return tokenize_text(request["text"]) +The wrapped handler receives the parsed and validated JSON body as its +first argument and the original aiohttp request object as the second:: + + async def handler(data, request): + pool = request.app["redis_pool"] # the real request is right here + ... + +To respond with a status code other than 200, return a ``(data, status)`` +tuple:: + + async def create_handler(data, request): + return {"id": new_id}, 201 + Features -------- * The decorator to (optionally) validate the request to your aiohttp endpoint and it's response. @@ -67,10 +72,10 @@ Features Developing ---------- -Install requirement and launch tests:: +Install with test dependencies and launch tests:: - pip install -r requirements-dev.txt - py.test + pip install -e .[test] + pytest Credits diff --git a/aiohttp_validate/__init__.py b/aiohttp_validate/__init__.py index d28c82f..5a72b8b 100644 --- a/aiohttp_validate/__init__.py +++ b/aiohttp_validate/__init__.py @@ -1,22 +1,29 @@ -import json +"""Validate aiohttp request handlers' input and output with JSON schema.""" + +from __future__ import annotations + import functools -import asyncio +import inspect +import json from collections import defaultdict +from typing import Any, Optional from aiohttp import web from aiohttp.abc import AbstractView from jsonschema.validators import validator_for __author__ = """Dmitry Chaplinsky""" -__email__ = 'chaplinsky.dmitry@gmail.com' -__version__ = '0.1.1' +__email__ = "chaplinsky.dmitry@gmail.com" +__version__ = "2.0" + +__all__ = ["validate"] -def _raise_exception(cls, reason, data=None): +def _raise_exception(cls: type, reason: str, data: Any = None) -> None: """ Raise aiohttp exception and pass payload/reason into it. """ - text_dict = { + text_dict: dict = { "error": reason } @@ -29,12 +36,12 @@ def _raise_exception(cls, reason, data=None): ) -def _validate_data(data, schema, validator_cls): +def _validate_data(data: Any, schema: dict, validator_cls: type) -> None: """ Validate the dict against given schema (using given validator class). """ validator = validator_cls(schema) - _errors = defaultdict(list) + _errors: dict = defaultdict(list) def set_nested_item(dataDict, mapList, key, val): for _key in mapList: @@ -85,10 +92,17 @@ def set_nested_item(dataDict, mapList, key, val): _errors) -def validate(request_schema=None, response_schema=None): +def validate(request_schema: Optional[dict] = None, + response_schema: Optional[dict] = None): """ - Decorate request handler to make it automagically validate it's request + Decorate request handler to make it automagically validate its request and response. + + The wrapped handler is called as ``handler(parsed_json, request)`` + (``handler(self, parsed_json, request)`` for class-based views) and may + return either the response data, or a ``(data, status)`` tuple to set + the response status code, or a ready ``StreamResponse`` (which skips + response validation). """ def wrapper(func): @@ -102,14 +116,8 @@ def wrapper(func): _response_schema_validator = validator_for(response_schema) _response_schema_validator.check_schema(response_schema) - @asyncio.coroutine @functools.wraps(func) - def wrapped(*args): - if asyncio.iscoroutinefunction(func): - coro = func - else: - coro = asyncio.coroutine(func) - + async def wrapped(*args): # Supports class based views see web.View if isinstance(args[0], AbstractView): class_based = True @@ -123,7 +131,7 @@ def wrapped(*args): # Strictly expect json object here try: - req_body = yield from request.json() + req_body = await request.json() except (json.decoder.JSONDecodeError, TypeError): _raise_exception( web.HTTPBadRequest, @@ -138,19 +146,27 @@ def wrapped(*args): if class_based: coro_args = (args[0],) + coro_args - context = yield from coro(*coro_args) + if inspect.iscoroutinefunction(func): + context = await func(*coro_args) + else: + context = func(*coro_args) # No validation of response for websockets stream if isinstance(context, web.StreamResponse): return context + status = 200 + if isinstance(context, tuple) and len(context) == 2 and \ + isinstance(context[1], int): + context, status = context + # Validate response data against response schema (if given) if response_schema is not None: _validate_data(context, response_schema, _response_schema_validator) try: - return web.json_response(context) + return web.json_response(context, status=status) except (TypeError,): _raise_exception( web.HTTPInternalServerError, @@ -162,6 +178,3 @@ def wrapped(*args): return wrapped return wrapper - - -__ALL__ = ["validate", "__author__", "__email__", "__version__"], diff --git a/aiohttp_validate/py.typed b/aiohttp_validate/py.typed new file mode 100644 index 0000000..e69de29 diff --git a/docs/Makefile b/docs/Makefile deleted file mode 100644 index b84ce2d..0000000 --- a/docs/Makefile +++ /dev/null @@ -1,177 +0,0 @@ -# Makefile for Sphinx documentation -# - -# You can set these variables from the command line. -SPHINXOPTS = -SPHINXBUILD = sphinx-build -PAPER = -BUILDDIR = _build - -# User-friendly check for sphinx-build -ifeq ($(shell which $(SPHINXBUILD) >/dev/null 2>&1; echo $$?), 1) -$(error The '$(SPHINXBUILD)' command was not found. Make sure you have Sphinx installed, then set the SPHINXBUILD environment variable to point to the full path of the '$(SPHINXBUILD)' executable. Alternatively you can add the directory with the executable to your PATH. If you don't have Sphinx installed, grab it from http://sphinx-doc.org/) -endif - -# Internal variables. -PAPEROPT_a4 = -D latex_paper_size=a4 -PAPEROPT_letter = -D latex_paper_size=letter -ALLSPHINXOPTS = -d $(BUILDDIR)/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) . -# the i18n builder cannot share the environment and doctrees with the others -I18NSPHINXOPTS = $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) . - -.PHONY: help clean html dirhtml singlehtml pickle json htmlhelp qthelp devhelp epub latex latexpdf text man changes linkcheck doctest gettext - -help: - @echo "Please use \`make ' where is one of" - @echo " html to make standalone HTML files" - @echo " dirhtml to make HTML files named index.html in directories" - @echo " singlehtml to make a single large HTML file" - @echo " pickle to make pickle files" - @echo " json to make JSON files" - @echo " htmlhelp to make HTML files and a HTML help project" - @echo " qthelp to make HTML files and a qthelp project" - @echo " devhelp to make HTML files and a Devhelp project" - @echo " epub to make an epub" - @echo " latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter" - @echo " latexpdf to make LaTeX files and run them through pdflatex" - @echo " latexpdfja to make LaTeX files and run them through platex/dvipdfmx" - @echo " text to make text files" - @echo " man to make manual pages" - @echo " texinfo to make Texinfo files" - @echo " info to make Texinfo files and run them through makeinfo" - @echo " gettext to make PO message catalogs" - @echo " changes to make an overview of all changed/added/deprecated items" - @echo " xml to make Docutils-native XML files" - @echo " pseudoxml to make pseudoxml-XML files for display purposes" - @echo " linkcheck to check all external links for integrity" - @echo " doctest to run all doctests embedded in the documentation (if enabled)" - -clean: - rm -rf $(BUILDDIR)/* - -html: - $(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html - @echo - @echo "Build finished. The HTML pages are in $(BUILDDIR)/html." - -dirhtml: - $(SPHINXBUILD) -b dirhtml $(ALLSPHINXOPTS) $(BUILDDIR)/dirhtml - @echo - @echo "Build finished. The HTML pages are in $(BUILDDIR)/dirhtml." - -singlehtml: - $(SPHINXBUILD) -b singlehtml $(ALLSPHINXOPTS) $(BUILDDIR)/singlehtml - @echo - @echo "Build finished. The HTML page is in $(BUILDDIR)/singlehtml." - -pickle: - $(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) $(BUILDDIR)/pickle - @echo - @echo "Build finished; now you can process the pickle files." - -json: - $(SPHINXBUILD) -b json $(ALLSPHINXOPTS) $(BUILDDIR)/json - @echo - @echo "Build finished; now you can process the JSON files." - -htmlhelp: - $(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) $(BUILDDIR)/htmlhelp - @echo - @echo "Build finished; now you can run HTML Help Workshop with the" \ - ".hhp project file in $(BUILDDIR)/htmlhelp." - -qthelp: - $(SPHINXBUILD) -b qthelp $(ALLSPHINXOPTS) $(BUILDDIR)/qthelp - @echo - @echo "Build finished; now you can run "qcollectiongenerator" with the" \ - ".qhcp project file in $(BUILDDIR)/qthelp, like this:" - @echo "# qcollectiongenerator $(BUILDDIR)/qthelp/aiohttp_validate.qhcp" - @echo "To view the help file:" - @echo "# assistant -collectionFile $(BUILDDIR)/qthelp/aiohttp_validate.qhc" - -devhelp: - $(SPHINXBUILD) -b devhelp $(ALLSPHINXOPTS) $(BUILDDIR)/devhelp - @echo - @echo "Build finished." - @echo "To view the help file:" - @echo "# mkdir -p $$HOME/.local/share/devhelp/aiohttp_validate" - @echo "# ln -s $(BUILDDIR)/devhelp $$HOME/.local/share/devhelp/aiohttp_validate" - @echo "# devhelp" - -epub: - $(SPHINXBUILD) -b epub $(ALLSPHINXOPTS) $(BUILDDIR)/epub - @echo - @echo "Build finished. The epub file is in $(BUILDDIR)/epub." - -latex: - $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex - @echo - @echo "Build finished; the LaTeX files are in $(BUILDDIR)/latex." - @echo "Run \`make' in that directory to run these through (pdf)latex" \ - "(use \`make latexpdf' here to do that automatically)." - -latexpdf: - $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex - @echo "Running LaTeX files through pdflatex..." - $(MAKE) -C $(BUILDDIR)/latex all-pdf - @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex." - -latexpdfja: - $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex - @echo "Running LaTeX files through platex and dvipdfmx..." - $(MAKE) -C $(BUILDDIR)/latex all-pdf-ja - @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex." - -text: - $(SPHINXBUILD) -b text $(ALLSPHINXOPTS) $(BUILDDIR)/text - @echo - @echo "Build finished. The text files are in $(BUILDDIR)/text." - -man: - $(SPHINXBUILD) -b man $(ALLSPHINXOPTS) $(BUILDDIR)/man - @echo - @echo "Build finished. The manual pages are in $(BUILDDIR)/man." - -texinfo: - $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo - @echo - @echo "Build finished. The Texinfo files are in $(BUILDDIR)/texinfo." - @echo "Run \`make' in that directory to run these through makeinfo" \ - "(use \`make info' here to do that automatically)." - -info: - $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo - @echo "Running Texinfo files through makeinfo..." - make -C $(BUILDDIR)/texinfo info - @echo "makeinfo finished; the Info files are in $(BUILDDIR)/texinfo." - -gettext: - $(SPHINXBUILD) -b gettext $(I18NSPHINXOPTS) $(BUILDDIR)/locale - @echo - @echo "Build finished. The message catalogs are in $(BUILDDIR)/locale." - -changes: - $(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) $(BUILDDIR)/changes - @echo - @echo "The overview file is in $(BUILDDIR)/changes." - -linkcheck: - $(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) $(BUILDDIR)/linkcheck - @echo - @echo "Link check complete; look for any errors in the above output " \ - "or in $(BUILDDIR)/linkcheck/output.txt." - -doctest: - $(SPHINXBUILD) -b doctest $(ALLSPHINXOPTS) $(BUILDDIR)/doctest - @echo "Testing of doctests in the sources finished, look at the " \ - "results in $(BUILDDIR)/doctest/output.txt." - -xml: - $(SPHINXBUILD) -b xml $(ALLSPHINXOPTS) $(BUILDDIR)/xml - @echo - @echo "Build finished. The XML files are in $(BUILDDIR)/xml." - -pseudoxml: - $(SPHINXBUILD) -b pseudoxml $(ALLSPHINXOPTS) $(BUILDDIR)/pseudoxml - @echo - @echo "Build finished. The pseudo-XML files are in $(BUILDDIR)/pseudoxml." diff --git a/docs/authors.rst b/docs/authors.rst deleted file mode 100644 index e122f91..0000000 --- a/docs/authors.rst +++ /dev/null @@ -1 +0,0 @@ -.. include:: ../AUTHORS.rst diff --git a/docs/conf.py b/docs/conf.py deleted file mode 100755 index 26abffe..0000000 --- a/docs/conf.py +++ /dev/null @@ -1,275 +0,0 @@ -#!/usr/bin/env python -# -*- coding: utf-8 -*- -# -# aiohttp_validate documentation build configuration file, created by -# sphinx-quickstart on Tue Jul 9 22:26:36 2013. -# -# This file is execfile()d with the current directory set to its -# containing dir. -# -# Note that not all possible configuration values are present in this -# autogenerated file. -# -# All configuration values have a default; values that are commented out -# serve to show the default. - -import sys -import os - -# If extensions (or modules to document with autodoc) are in another -# directory, add these directories to sys.path here. If the directory is -# relative to the documentation root, use os.path.abspath to make it -# absolute, like shown here. -#sys.path.insert(0, os.path.abspath('.')) - -# Get the project root dir, which is the parent dir of this -cwd = os.getcwd() -project_root = os.path.dirname(cwd) - -# Insert the project root dir as the first element in the PYTHONPATH. -# This lets us ensure that the source package is imported, and that its -# version is used. -sys.path.insert(0, project_root) - -# import aiohttp_validate - -# -- General configuration --------------------------------------------- - -# If your documentation needs a minimal Sphinx version, state it here. -#needs_sphinx = '1.0' - -# Add any Sphinx extension module names here, as strings. They can be -# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom ones. -extensions = ['sphinx.ext.autodoc', 'sphinx.ext.viewcode'] - -# Add any paths that contain templates here, relative to this directory. -templates_path = ['_templates'] - -# The suffix of source filenames. -source_suffix = '.rst' - -# The encoding of source files. -#source_encoding = 'utf-8-sig' - -# The master toctree document. -master_doc = 'index' - -# General information about the project. -project = u'aiohttp_validate' -copyright = u"2016, Dmitry Chaplinsky" - -# The version info for the project you're documenting, acts as replacement -# for |version| and |release|, also used in various other places throughout -# the built documents. -# -# The short X.Y version. -version = '1.0.0' -# The full version, including alpha/beta/rc tags. -release = '1.0.0' - -# The language for content autogenerated by Sphinx. Refer to documentation -# for a list of supported languages. -#language = None - -# There are two options for replacing |today|: either, you set today to -# some non-false value, then it is used: -#today = '' -# Else, today_fmt is used as the format for a strftime call. -#today_fmt = '%B %d, %Y' - -# List of patterns, relative to source directory, that match files and -# directories to ignore when looking for source files. -exclude_patterns = ['_build'] - -# The reST default role (used for this markup: `text`) to use for all -# documents. -#default_role = None - -# If true, '()' will be appended to :func: etc. cross-reference text. -#add_function_parentheses = True - -# If true, the current module name will be prepended to all description -# unit titles (such as .. function::). -#add_module_names = True - -# If true, sectionauthor and moduleauthor directives will be shown in the -# output. They are ignored by default. -#show_authors = False - -# The name of the Pygments (syntax highlighting) style to use. -pygments_style = 'sphinx' - -# A list of ignored prefixes for module index sorting. -#modindex_common_prefix = [] - -# If true, keep warnings as "system message" paragraphs in the built -# documents. -#keep_warnings = False - - -# -- Options for HTML output ------------------------------------------- - -# The theme to use for HTML and HTML Help pages. See the documentation for -# a list of builtin themes. -html_theme = 'default' - -# Theme options are theme-specific and customize the look and feel of a -# theme further. For a list of options available for each theme, see the -# documentation. -#html_theme_options = {} - -# Add any paths that contain custom themes here, relative to this directory. -#html_theme_path = [] - -# The name for this set of Sphinx documents. If None, it defaults to -# " v documentation". -#html_title = None - -# A shorter title for the navigation bar. Default is the same as -# html_title. -#html_short_title = None - -# The name of an image file (relative to this directory) to place at the -# top of the sidebar. -#html_logo = None - -# The name of an image file (within the static path) to use as favicon -# of the docs. This file should be a Windows icon file (.ico) being -# 16x16 or 32x32 pixels large. -#html_favicon = None - -# Add any paths that contain custom static files (such as style sheets) -# here, relative to this directory. They are copied after the builtin -# static files, so a file named "default.css" will overwrite the builtin -# "default.css". -html_static_path = ['_static'] - -# If not '', a 'Last updated on:' timestamp is inserted at every page -# bottom, using the given strftime format. -#html_last_updated_fmt = '%b %d, %Y' - -# If true, SmartyPants will be used to convert quotes and dashes to -# typographically correct entities. -#html_use_smartypants = True - -# Custom sidebar templates, maps document names to template names. -#html_sidebars = {} - -# Additional templates that should be rendered to pages, maps page names -# to template names. -#html_additional_pages = {} - -# If false, no module index is generated. -#html_domain_indices = True - -# If false, no index is generated. -#html_use_index = True - -# If true, the index is split into individual pages for each letter. -#html_split_index = False - -# If true, links to the reST sources are added to the pages. -#html_show_sourcelink = True - -# If true, "Created using Sphinx" is shown in the HTML footer. -# Default is True. -#html_show_sphinx = True - -# If true, "(C) Copyright ..." is shown in the HTML footer. -# Default is True. -#html_show_copyright = True - -# If true, an OpenSearch description file will be output, and all pages -# will contain a tag referring to it. The value of this option -# must be the base URL from which the finished HTML is served. -#html_use_opensearch = '' - -# This is the file name suffix for HTML files (e.g. ".xhtml"). -#html_file_suffix = None - -# Output file base name for HTML help builder. -htmlhelp_basename = 'aiohttp_validatedoc' - - -# -- Options for LaTeX output ------------------------------------------ - -latex_elements = { - # The paper size ('letterpaper' or 'a4paper'). - #'papersize': 'letterpaper', - - # The font size ('10pt', '11pt' or '12pt'). - #'pointsize': '10pt', - - # Additional stuff for the LaTeX preamble. - #'preamble': '', -} - -# Grouping the document tree into LaTeX files. List of tuples -# (source start file, target name, title, author, documentclass -# [howto/manual]). -latex_documents = [ - ('index', 'aiohttp_validate.tex', - u'aiohttp_validate Documentation', - u'Dmitry Chaplinsky', 'manual'), -] - -# The name of an image file (relative to this directory) to place at -# the top of the title page. -#latex_logo = None - -# For "manual" documents, if this is true, then toplevel headings -# are parts, not chapters. -#latex_use_parts = False - -# If true, show page references after internal links. -#latex_show_pagerefs = False - -# If true, show URL addresses after external links. -#latex_show_urls = False - -# Documents to append as an appendix to all manuals. -#latex_appendices = [] - -# If false, no module index is generated. -#latex_domain_indices = True - - -# -- Options for manual page output ------------------------------------ - -# One entry per manual page. List of tuples -# (source start file, name, description, authors, manual section). -man_pages = [ - ('index', 'aiohttp_validate', - u'aiohttp_validate Documentation', - [u'Dmitry Chaplinsky'], 1) -] - -# If true, show URL addresses after external links. -#man_show_urls = False - - -# -- Options for Texinfo output ---------------------------------------- - -# Grouping the document tree into Texinfo files. List of tuples -# (source start file, target name, title, author, -# dir menu entry, description, category) -texinfo_documents = [ - ('index', 'aiohttp_validate', - u'aiohttp_validate Documentation', - u'Dmitry Chaplinsky', - 'aiohttp_validate', - 'One line description of project.', - 'Miscellaneous'), -] - -# Documents to append as an appendix to all manuals. -#texinfo_appendices = [] - -# If false, no module index is generated. -#texinfo_domain_indices = True - -# How to display URL addresses: 'footnote', 'no', or 'inline'. -#texinfo_show_urls = 'footnote' - -# If true, do not generate a @detailmenu in the "Top" node's menu. -#texinfo_no_detailmenu = False diff --git a/docs/contributing.rst b/docs/contributing.rst deleted file mode 100644 index e582053..0000000 --- a/docs/contributing.rst +++ /dev/null @@ -1 +0,0 @@ -.. include:: ../CONTRIBUTING.rst diff --git a/docs/history.rst b/docs/history.rst deleted file mode 100644 index 2506499..0000000 --- a/docs/history.rst +++ /dev/null @@ -1 +0,0 @@ -.. include:: ../HISTORY.rst diff --git a/docs/index.rst b/docs/index.rst deleted file mode 100644 index 8dfb0fc..0000000 --- a/docs/index.rst +++ /dev/null @@ -1,25 +0,0 @@ -.. aiohttp_validate documentation master file, created by - sphinx-quickstart on Tue Jul 9 22:26:36 2013. - You can adapt this file completely to your liking, but it should at least - contain the root `toctree` directive. - -Welcome to aiohttp_validate's documentation! -====================================== - -Contents: - -.. toctree:: - :maxdepth: 2 - - readme - installation - usage - contributing - authorshistory - -Indices and tables -================== - -* :ref:`genindex` -* :ref:`modindex` -* :ref:`search` diff --git a/docs/installation.rst b/docs/installation.rst deleted file mode 100644 index 5de9374..0000000 --- a/docs/installation.rst +++ /dev/null @@ -1,51 +0,0 @@ -.. highlight:: shell - -============ -Installation -============ - - -Stable release --------------- - -To install aiohttp_validate, run this command in your terminal: - -.. code-block:: console - - $ pip install aiohttp_validate - -This is the preferred method to install aiohttp_validate, as it will always install the most recent stable release. - -If you don't have `pip`_ installed, this `Python installation guide`_ can guide -you through the process. - -.. _pip: https://pip.pypa.io -.. _Python installation guide: http://docs.python-guide.org/en/latest/starting/installation/ - - -From sources ------------- - -The sources for aiohttp_validate can be downloaded from the `Github repo`_. - -You can either clone the public repository: - -.. code-block:: console - - $ git clone git://github.com/dchaplinsky/aiohttp_validate - -Or download the `tarball`_: - -.. code-block:: console - - $ curl -OL https://github.com/dchaplinsky/aiohttp_validate/tarball/master - -Once you have a copy of the source, you can install it with: - -.. code-block:: console - - $ python setup.py install - - -.. _Github repo: https://github.com/dchaplinsky/aiohttp_validate -.. _tarball: https://github.com/dchaplinsky/aiohttp_validate/tarball/master diff --git a/docs/make.bat b/docs/make.bat deleted file mode 100644 index 263b249..0000000 --- a/docs/make.bat +++ /dev/null @@ -1,242 +0,0 @@ -@ECHO OFF - -REM Command file for Sphinx documentation - -if "%SPHINXBUILD%" == "" ( - set SPHINXBUILD=sphinx-build -) -set BUILDDIR=_build -set ALLSPHINXOPTS=-d %BUILDDIR%/doctrees %SPHINXOPTS% . -set I18NSPHINXOPTS=%SPHINXOPTS% . -if NOT "%PAPER%" == "" ( - set ALLSPHINXOPTS=-D latex_paper_size=%PAPER% %ALLSPHINXOPTS% - set I18NSPHINXOPTS=-D latex_paper_size=%PAPER% %I18NSPHINXOPTS% -) - -if "%1" == "" goto help - -if "%1" == "help" ( - :help - echo.Please use `make ^` where ^ is one of - echo. html to make standalone HTML files - echo. dirhtml to make HTML files named index.html in directories - echo. singlehtml to make a single large HTML file - echo. pickle to make pickle files - echo. json to make JSON files - echo. htmlhelp to make HTML files and a HTML help project - echo. qthelp to make HTML files and a qthelp project - echo. devhelp to make HTML files and a Devhelp project - echo. epub to make an epub - echo. latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter - echo. text to make text files - echo. man to make manual pages - echo. texinfo to make Texinfo files - echo. gettext to make PO message catalogs - echo. changes to make an overview over all changed/added/deprecated items - echo. xml to make Docutils-native XML files - echo. pseudoxml to make pseudoxml-XML files for display purposes - echo. linkcheck to check all external links for integrity - echo. doctest to run all doctests embedded in the documentation if enabled - goto end -) - -if "%1" == "clean" ( - for /d %%i in (%BUILDDIR%\*) do rmdir /q /s %%i - del /q /s %BUILDDIR%\* - goto end -) - - -%SPHINXBUILD% 2> nul -if errorlevel 9009 ( - echo. - echo.The 'sphinx-build' command was not found. Make sure you have Sphinx - echo.installed, then set the SPHINXBUILD environment variable to point - echo.to the full path of the 'sphinx-build' executable. Alternatively you - echo.may add the Sphinx directory to PATH. - echo. - echo.If you don't have Sphinx installed, grab it from - echo.http://sphinx-doc.org/ - exit /b 1 -) - -if "%1" == "html" ( - %SPHINXBUILD% -b html %ALLSPHINXOPTS% %BUILDDIR%/html - if errorlevel 1 exit /b 1 - echo. - echo.Build finished. The HTML pages are in %BUILDDIR%/html. - goto end -) - -if "%1" == "dirhtml" ( - %SPHINXBUILD% -b dirhtml %ALLSPHINXOPTS% %BUILDDIR%/dirhtml - if errorlevel 1 exit /b 1 - echo. - echo.Build finished. The HTML pages are in %BUILDDIR%/dirhtml. - goto end -) - -if "%1" == "singlehtml" ( - %SPHINXBUILD% -b singlehtml %ALLSPHINXOPTS% %BUILDDIR%/singlehtml - if errorlevel 1 exit /b 1 - echo. - echo.Build finished. The HTML pages are in %BUILDDIR%/singlehtml. - goto end -) - -if "%1" == "pickle" ( - %SPHINXBUILD% -b pickle %ALLSPHINXOPTS% %BUILDDIR%/pickle - if errorlevel 1 exit /b 1 - echo. - echo.Build finished; now you can process the pickle files. - goto end -) - -if "%1" == "json" ( - %SPHINXBUILD% -b json %ALLSPHINXOPTS% %BUILDDIR%/json - if errorlevel 1 exit /b 1 - echo. - echo.Build finished; now you can process the JSON files. - goto end -) - -if "%1" == "htmlhelp" ( - %SPHINXBUILD% -b htmlhelp %ALLSPHINXOPTS% %BUILDDIR%/htmlhelp - if errorlevel 1 exit /b 1 - echo. - echo.Build finished; now you can run HTML Help Workshop with the ^ -.hhp project file in %BUILDDIR%/htmlhelp. - goto end -) - -if "%1" == "qthelp" ( - %SPHINXBUILD% -b qthelp %ALLSPHINXOPTS% %BUILDDIR%/qthelp - if errorlevel 1 exit /b 1 - echo. - echo.Build finished; now you can run "qcollectiongenerator" with the ^ -.qhcp project file in %BUILDDIR%/qthelp, like this: - echo.^> qcollectiongenerator %BUILDDIR%\qthelp\aiohttp_validate.qhcp - echo.To view the help file: - echo.^> assistant -collectionFile %BUILDDIR%\qthelp\aiohttp_validate.ghc - goto end -) - -if "%1" == "devhelp" ( - %SPHINXBUILD% -b devhelp %ALLSPHINXOPTS% %BUILDDIR%/devhelp - if errorlevel 1 exit /b 1 - echo. - echo.Build finished. - goto end -) - -if "%1" == "epub" ( - %SPHINXBUILD% -b epub %ALLSPHINXOPTS% %BUILDDIR%/epub - if errorlevel 1 exit /b 1 - echo. - echo.Build finished. The epub file is in %BUILDDIR%/epub. - goto end -) - -if "%1" == "latex" ( - %SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex - if errorlevel 1 exit /b 1 - echo. - echo.Build finished; the LaTeX files are in %BUILDDIR%/latex. - goto end -) - -if "%1" == "latexpdf" ( - %SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex - cd %BUILDDIR%/latex - make all-pdf - cd %BUILDDIR%/.. - echo. - echo.Build finished; the PDF files are in %BUILDDIR%/latex. - goto end -) - -if "%1" == "latexpdfja" ( - %SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex - cd %BUILDDIR%/latex - make all-pdf-ja - cd %BUILDDIR%/.. - echo. - echo.Build finished; the PDF files are in %BUILDDIR%/latex. - goto end -) - -if "%1" == "text" ( - %SPHINXBUILD% -b text %ALLSPHINXOPTS% %BUILDDIR%/text - if errorlevel 1 exit /b 1 - echo. - echo.Build finished. The text files are in %BUILDDIR%/text. - goto end -) - -if "%1" == "man" ( - %SPHINXBUILD% -b man %ALLSPHINXOPTS% %BUILDDIR%/man - if errorlevel 1 exit /b 1 - echo. - echo.Build finished. The manual pages are in %BUILDDIR%/man. - goto end -) - -if "%1" == "texinfo" ( - %SPHINXBUILD% -b texinfo %ALLSPHINXOPTS% %BUILDDIR%/texinfo - if errorlevel 1 exit /b 1 - echo. - echo.Build finished. The Texinfo files are in %BUILDDIR%/texinfo. - goto end -) - -if "%1" == "gettext" ( - %SPHINXBUILD% -b gettext %I18NSPHINXOPTS% %BUILDDIR%/locale - if errorlevel 1 exit /b 1 - echo. - echo.Build finished. The message catalogs are in %BUILDDIR%/locale. - goto end -) - -if "%1" == "changes" ( - %SPHINXBUILD% -b changes %ALLSPHINXOPTS% %BUILDDIR%/changes - if errorlevel 1 exit /b 1 - echo. - echo.The overview file is in %BUILDDIR%/changes. - goto end -) - -if "%1" == "linkcheck" ( - %SPHINXBUILD% -b linkcheck %ALLSPHINXOPTS% %BUILDDIR%/linkcheck - if errorlevel 1 exit /b 1 - echo. - echo.Link check complete; look for any errors in the above output ^ -or in %BUILDDIR%/linkcheck/output.txt. - goto end -) - -if "%1" == "doctest" ( - %SPHINXBUILD% -b doctest %ALLSPHINXOPTS% %BUILDDIR%/doctest - if errorlevel 1 exit /b 1 - echo. - echo.Testing of doctests in the sources finished, look at the ^ -results in %BUILDDIR%/doctest/output.txt. - goto end -) - -if "%1" == "xml" ( - %SPHINXBUILD% -b xml %ALLSPHINXOPTS% %BUILDDIR%/xml - if errorlevel 1 exit /b 1 - echo. - echo.Build finished. The XML files are in %BUILDDIR%/xml. - goto end -) - -if "%1" == "pseudoxml" ( - %SPHINXBUILD% -b pseudoxml %ALLSPHINXOPTS% %BUILDDIR%/pseudoxml - if errorlevel 1 exit /b 1 - echo. - echo.Build finished. The pseudo-XML files are in %BUILDDIR%/pseudoxml. - goto end -) - -:end diff --git a/docs/readme.rst b/docs/readme.rst deleted file mode 100644 index 72a3355..0000000 --- a/docs/readme.rst +++ /dev/null @@ -1 +0,0 @@ -.. include:: ../README.rst diff --git a/docs/usage.rst b/docs/usage.rst deleted file mode 100644 index adfb89a..0000000 --- a/docs/usage.rst +++ /dev/null @@ -1,7 +0,0 @@ -===== -Usage -===== - -To use aiohttp_validate in a project:: - - import aiohttp_validate diff --git a/pyproject.toml b/pyproject.toml new file mode 100644 index 0000000..db01e14 --- /dev/null +++ b/pyproject.toml @@ -0,0 +1,55 @@ +[build-system] +requires = ["setuptools>=77"] +build-backend = "setuptools.build_meta" + +[project] +name = "aiohttp_validate" +dynamic = ["version"] +description = "Simple library that helps you validate your API endpoints requests/responses with json schema" +readme = "README.rst" +license = "MIT" +authors = [ + {name = "Dmitry Chaplinsky", email = "chaplinsky.dmitry@gmail.com"}, +] +requires-python = ">=3.9" +keywords = ["aiohttp", "jsonschema", "validation", "api"] +dependencies = [ + "aiohttp>=3.8", + "jsonschema>=3.0", +] +classifiers = [ + "Development Status :: 5 - Production/Stable", + "Intended Audience :: Developers", + "Natural Language :: English", + "Programming Language :: Python :: 3", + "Programming Language :: Python :: 3.9", + "Programming Language :: Python :: 3.10", + "Programming Language :: Python :: 3.11", + "Programming Language :: Python :: 3.12", + "Programming Language :: Python :: 3.13", + "Framework :: aiohttp", + "Topic :: Internet :: WWW/HTTP :: HTTP Servers", +] + +[project.urls] +Homepage = "https://github.com/dchaplinsky/aiohttp_validate" +Issues = "https://github.com/dchaplinsky/aiohttp_validate/issues" + +[project.optional-dependencies] +test = [ + "pytest", + "pytest-aiohttp", +] + +[tool.pytest.ini_options] +asyncio_mode = "auto" +testpaths = ["tests"] + +[tool.setuptools] +packages = ["aiohttp_validate"] + +[tool.setuptools.package-data] +aiohttp_validate = ["py.typed"] + +[tool.setuptools.dynamic] +version = {attr = "aiohttp_validate.__version__"} diff --git a/requirements_dev.txt b/requirements_dev.txt deleted file mode 100644 index 30dbdc2..0000000 --- a/requirements_dev.txt +++ /dev/null @@ -1,14 +0,0 @@ -pip==19.2.1 -bumpversion==0.5.3 -wheel==0.33.4 -watchdog==0.9.0 -flake8==3.6.0 -tox==3.13.2 -coverage==4.5.4 -pytest-aiohttp==0.3.0 -Sphinx==2.1.2 -cryptography==2.7 -PyYAML==5.1.2 -pytest==5.0.1 -docutils==0.15.2 -pluggy==0.12.0 \ No newline at end of file diff --git a/setup.cfg b/setup.cfg deleted file mode 100644 index 4fbfb3b..0000000 --- a/setup.cfg +++ /dev/null @@ -1,18 +0,0 @@ -[bumpversion] -current_version = 0.1.0 -commit = True -tag = True - -[bumpversion:file:setup.py] -search = version='{current_version}' -replace = version='{new_version}' - -[bumpversion:file:aiohttp_validate/__init__.py] -search = __version__ = '{current_version}' -replace = __version__ = '{new_version}' - -[bdist_wheel] -universal = 1 - -[flake8] -exclude = docs diff --git a/setup.py b/setup.py deleted file mode 100644 index b34a30c..0000000 --- a/setup.py +++ /dev/null @@ -1,56 +0,0 @@ -#!/usr/bin/env python -# -*- coding: utf-8 -*- - -from setuptools import setup - -with open('README.rst') as readme_file: - readme = readme_file.read() - -with open('HISTORY.rst') as history_file: - history = history_file.read() - -requirements = [ - 'aiohttp>=3.0.0', - 'jsonschema>=2.5.1', -] - -test_requirements = [ - 'pytest==5.0.1', - 'pytest-aiohttp==0.3.0', -] - -setup( - name='aiohttp_validate', - version='1.2.0', - description="Simple library that helps you validate your API endpoints requests/responses with json schema", - long_description=readme + '\n\n' + history, - author="Dmitry Chaplinsky", - author_email='chaplinsky.dmitry@gmail.com', - url='https://github.com/dchaplinsky/aiohttp_validate', - packages=[ - 'aiohttp_validate', - ], - package_dir={'aiohttp_validate': - 'aiohttp_validate'}, - entry_points={ - 'console_scripts': [ - 'aiohttp_validate=aiohttp_validate.cli:main' - ] - }, - include_package_data=True, - install_requires=requirements, - license="MIT license", - zip_safe=False, - keywords='aiohttp_validate', - classifiers=[ - 'Development Status :: 5 - Production/Stable', - 'Intended Audience :: Developers', - 'License :: OSI Approved :: MIT License', - 'Natural Language :: English', - 'Programming Language :: Python :: 3', - 'Programming Language :: Python :: 3.5', - 'Programming Language :: Python :: 3.6', - ], - test_suite='tests', - tests_require=test_requirements -) diff --git a/tests/test_aiohttp_validate.py b/tests/test_aiohttp_validate.py index 92bb143..0e73aa1 100644 --- a/tests/test_aiohttp_validate.py +++ b/tests/test_aiohttp_validate.py @@ -103,8 +103,8 @@ async def validate_nested_errors(request, *args): return request -async def test_invalid_request(aiohttp_client, loop): - app = web.Application(loop=loop) +async def test_invalid_request(aiohttp_client): + app = web.Application() app.router.add_post('/', hello) app.router.add_get('/', hello) client = await aiohttp_client(app) @@ -125,8 +125,8 @@ async def test_invalid_request(aiohttp_client, loop): assert 'Request is malformed' in text["error"] -async def test_wrong_request_format(aiohttp_client, loop): - app = web.Application(loop=loop) +async def test_wrong_request_format(aiohttp_client): + app = web.Application() app.router.add_post('/', hello) client = await aiohttp_client(app) @@ -137,8 +137,8 @@ async def test_wrong_request_format(aiohttp_client, loop): assert text["errors"] -async def test_correct_request(aiohttp_client, loop): - app = web.Application(loop=loop) +async def test_correct_request(aiohttp_client): + app = web.Application() app.router.add_post('/', hello) app.router.add_get('/', hello) client = await aiohttp_client(app) @@ -154,8 +154,8 @@ async def test_correct_request(aiohttp_client, loop): assert 'Hello world' in text -async def test_invalid_response(aiohttp_client, loop): - app = web.Application(loop=loop) +async def test_invalid_response(aiohttp_client): + app = web.Application() app.router.add_post('/', invalid_enc) app.router.add_get('/', invalid_enc) client = await aiohttp_client(app) @@ -171,8 +171,8 @@ async def test_invalid_response(aiohttp_client, loop): assert 'Response is malformed' in text["error"] -async def test_wrong_response_format(aiohttp_client, loop): - app = web.Application(loop=loop) +async def test_wrong_response_format(aiohttp_client): + app = web.Application() app.router.add_post('/', validate_output) client = await aiohttp_client(app) @@ -188,8 +188,8 @@ async def test_wrong_response_format(aiohttp_client, loop): assert text["errors"] -async def test_class_based_valid_request(aiohttp_client, loop): - app = web.Application(loop=loop) +async def test_class_based_valid_request(aiohttp_client): + app = web.Application() app.router.add_view('/', HelloView) client = await aiohttp_client(app) @@ -204,8 +204,8 @@ async def test_class_based_valid_request(aiohttp_client, loop): assert 'Hello world' in text -async def test_nested_errors(aiohttp_client, loop): - app = web.Application(loop=loop) +async def test_nested_errors(aiohttp_client): + app = web.Application() app.router.add_view('/', validate_nested_errors) client = await aiohttp_client(app) @@ -223,3 +223,38 @@ async def test_nested_errors(aiohttp_client, loop): errors = text["errors"] assert errors["firstName"] assert errors["nested"]["test_for_nested"] + + +@validate( + request_schema={"type": "object"}, + response_schema=None, +) +async def created(request, *args): + return {"id": 42}, 201 + + +@validate(request_schema={"type": "object"}) +def sync_handler(request, *args): + return {"sync": True} + + +async def test_custom_status(aiohttp_client): + app = web.Application() + app.router.add_post('/', created) + client = await aiohttp_client(app) + + resp = await client.post('/', data='{}') + assert resp.status == 201 + data = await resp.json() + assert data["id"] == 42 + + +async def test_sync_handler(aiohttp_client): + app = web.Application() + app.router.add_post('/', sync_handler) + client = await aiohttp_client(app) + + resp = await client.post('/', data='{}') + assert resp.status == 200 + data = await resp.json() + assert data["sync"] is True diff --git a/tox.ini b/tox.ini deleted file mode 100644 index b2d4d65..0000000 --- a/tox.ini +++ /dev/null @@ -1,22 +0,0 @@ -[tox] -envlist = flake8 - -[testenv:flake8] -basepython=python -deps=flake8 -commands=flake8 aiohttp_validate - -[testenv] -setenv = - PYTHONPATH = {toxinidir}:{toxinidir}/aiohttp_validate -deps = - -r{toxinidir}/requirements_dev.txt -commands = - pip install -U pip - py.test --basetemp={envtmpdir} - - -; If you want to make tox run the tests with the same versions, create a -; requirements.txt with the pinned versions and uncomment the following lines: -; deps = -; -r{toxinidir}/requirements.txt diff --git a/travis_pypi_setup.py b/travis_pypi_setup.py deleted file mode 100644 index ae870f5..0000000 --- a/travis_pypi_setup.py +++ /dev/null @@ -1,122 +0,0 @@ -#!/usr/bin/env python -# -*- coding: utf-8 -*- -"""Update encrypted deploy password in Travis config file -""" - - -from __future__ import print_function -import base64 -import json -import os -from getpass import getpass -import yaml -from cryptography.hazmat.primitives.serialization import load_pem_public_key -from cryptography.hazmat.backends import default_backend -from cryptography.hazmat.primitives.asymmetric.padding import PKCS1v15 - - -try: - from urllib import urlopen -except: - from urllib.request import urlopen - - -GITHUB_REPO = 'dchaplinsky/aiohttp_validate' -TRAVIS_CONFIG_FILE = os.path.join( - os.path.dirname(os.path.abspath(__file__)), '.travis.yml') - - -def load_key(pubkey): - """Load public RSA key, with work-around for keys using - incorrect header/footer format. - - Read more about RSA encryption with cryptography: - https://cryptography.io/latest/hazmat/primitives/asymmetric/rsa/ - """ - try: - return load_pem_public_key(pubkey.encode(), default_backend()) - except ValueError: - # workaround for https://github.com/travis-ci/travis-api/issues/196 - pubkey = pubkey.replace('BEGIN RSA', 'BEGIN').replace('END RSA', 'END') - return load_pem_public_key(pubkey.encode(), default_backend()) - - -def encrypt(pubkey, password): - """Encrypt password using given RSA public key and encode it with base64. - - The encrypted password can only be decrypted by someone with the - private key (in this case, only Travis). - """ - key = load_key(pubkey) - encrypted_password = key.encrypt(password, PKCS1v15()) - return base64.b64encode(encrypted_password) - - -def fetch_public_key(repo): - """Download RSA public key Travis will use for this repo. - - Travis API docs: http://docs.travis-ci.com/api/#repository-keys - """ - keyurl = 'https://api.travis-ci.org/repos/{0}/key'.format(repo) - data = json.loads(urlopen(keyurl).read().decode()) - if 'key' not in data: - errmsg = "Could not find public key for repo: {}.\n".format(repo) - errmsg += "Have you already added your GitHub repo to Travis?" - raise ValueError(errmsg) - return data['key'] - - -def prepend_line(filepath, line): - """Rewrite a file adding a line to its beginning. - """ - with open(filepath) as f: - lines = f.readlines() - - lines.insert(0, line) - - with open(filepath, 'w') as f: - f.writelines(lines) - - -def load_yaml_config(filepath): - with open(filepath) as f: - return yaml.load(f) - - -def save_yaml_config(filepath, config): - with open(filepath, 'w') as f: - yaml.dump(config, f, default_flow_style=False) - - -def update_travis_deploy_password(encrypted_password): - """Update the deploy section of the .travis.yml file - to use the given encrypted password. - """ - config = load_yaml_config(TRAVIS_CONFIG_FILE) - - config['deploy']['password'] = dict(secure=encrypted_password) - - save_yaml_config(TRAVIS_CONFIG_FILE, config) - - line = ('# This file was autogenerated and will overwrite' - ' each time you run travis_pypi_setup.py\n') - prepend_line(TRAVIS_CONFIG_FILE, line) - - -def main(args): - public_key = fetch_public_key(args.repo) - password = args.password or getpass('PyPI password: ') - update_travis_deploy_password(encrypt(public_key, password.encode())) - print("Wrote encrypted password to .travis.yml -- you're ready to deploy") - - -if '__main__' == __name__: - import argparse - parser = argparse.ArgumentParser(description=__doc__) - parser.add_argument('--repo', default=GITHUB_REPO, - help='GitHub repo (default: %s)' % GITHUB_REPO) - parser.add_argument('--password', - help='PyPI password (will prompt if not provided)') - - args = parser.parse_args() - main(args) From 047e645dfd33469aab30202f1b7b9b1e2f13eeb7 Mon Sep 17 00:00:00 2001 From: Dmitry Chaplinsky Date: Sun, 19 Jul 2026 14:44:50 +0000 Subject: [PATCH 2/5] Hoist the coroutine check, harden the status tuple signal, NoReturn hint - inspect.iscoroutinefunction is evaluated once at decoration time instead of on every request - The (data, status) shape check excludes bools and its collision case (response data that is itself a 2-tuple ending in an int) is documented in the docstring and README - _raise_exception is annotated NoReturn so type checkers see the truth Co-Authored-By: Claude Fable 5 Claude-Session: https://claude.ai/code/session_01Ha16zNy2fDMdrZBMQGgpBt --- README.rst | 5 +++++ aiohttp_validate/__init__.py | 23 +++++++++++++++++------ 2 files changed, 22 insertions(+), 6 deletions(-) diff --git a/README.rst b/README.rst index 0468882..5b1e82b 100644 --- a/README.rst +++ b/README.rst @@ -62,6 +62,11 @@ tuple:: async def create_handler(data, request): return {"id": new_id}, 201 +The tuple form is detected by shape (a 2-tuple ending in an int), so if +your response data is itself such a tuple, return it as a list instead — +JSON has no tuples, the wire format is identical — or return a ready +``web.json_response``. + Features -------- * The decorator to (optionally) validate the request to your aiohttp endpoint and it's response. diff --git a/aiohttp_validate/__init__.py b/aiohttp_validate/__init__.py index 5a72b8b..a27b222 100644 --- a/aiohttp_validate/__init__.py +++ b/aiohttp_validate/__init__.py @@ -6,7 +6,7 @@ import inspect import json from collections import defaultdict -from typing import Any, Optional +from typing import Any, NoReturn, Optional from aiohttp import web from aiohttp.abc import AbstractView @@ -19,11 +19,11 @@ __all__ = ["validate"] -def _raise_exception(cls: type, reason: str, data: Any = None) -> None: +def _raise_exception(cls: type, reason: str, data: Any = None) -> NoReturn: """ Raise aiohttp exception and pass payload/reason into it. """ - text_dict: dict = { + text_dict = { "error": reason } @@ -41,7 +41,7 @@ def _validate_data(data: Any, schema: dict, validator_cls: type) -> None: Validate the dict against given schema (using given validator class). """ validator = validator_cls(schema) - _errors: dict = defaultdict(list) + _errors = defaultdict(list) def set_nested_item(dataDict, mapList, key, val): for _key in mapList: @@ -103,6 +103,10 @@ def validate(request_schema: Optional[dict] = None, return either the response data, or a ``(data, status)`` tuple to set the response status code, or a ready ``StreamResponse`` (which skips response validation). + + Because the ``(data, status)`` form is detected by shape, response data + that is itself a 2-tuple ending in an int must be returned as a list + (JSON has no tuples anyway) or as a ready ``web.json_response``. """ def wrapper(func): @@ -116,6 +120,8 @@ def wrapper(func): _response_schema_validator = validator_for(response_schema) _response_schema_validator.check_schema(response_schema) + func_is_coro = inspect.iscoroutinefunction(func) + @functools.wraps(func) async def wrapped(*args): # Supports class based views see web.View @@ -146,7 +152,7 @@ async def wrapped(*args): if class_based: coro_args = (args[0],) + coro_args - if inspect.iscoroutinefunction(func): + if func_is_coro: context = await func(*coro_args) else: context = func(*coro_args) @@ -155,9 +161,14 @@ async def wrapped(*args): if isinstance(context, web.StreamResponse): return context + # Flask-style status sugar: a 2-tuple ending in an int (but + # not a bool) means (data, status). Tuple-shaped response DATA + # must be returned as a list instead (JSON arrays are lists + # anyway), or as a ready json_response status = 200 if isinstance(context, tuple) and len(context) == 2 and \ - isinstance(context[1], int): + isinstance(context[1], int) and \ + not isinstance(context[1], bool): context, status = context # Validate response data against response schema (if given) From afcf6e9cd95336e9484ada6371e614e4336d8ce3 Mon Sep 17 00:00:00 2001 From: Dmitry Chaplinsky Date: Sun, 19 Jul 2026 15:02:17 +0000 Subject: [PATCH 3/5] Complete test coverage: 100% of the module, 14 tests New tests for the previously uncovered branches: the type-mismatch error formatting path, plain-class (non-web.View) method handlers, ready StreamResponse passthrough, the bool-tuple non-hijack guarantee, and tuple response data serializing as a JSON array. Co-Authored-By: Claude Fable 5 Claude-Session: https://claude.ai/code/session_01Ha16zNy2fDMdrZBMQGgpBt --- tests/test_aiohttp_validate.py | 77 ++++++++++++++++++++++++++++++++++ 1 file changed, 77 insertions(+) diff --git a/tests/test_aiohttp_validate.py b/tests/test_aiohttp_validate.py index 0e73aa1..e5cf7bf 100644 --- a/tests/test_aiohttp_validate.py +++ b/tests/test_aiohttp_validate.py @@ -258,3 +258,80 @@ async def test_sync_handler(aiohttp_client): assert resp.status == 200 data = await resp.json() assert data["sync"] is True + + +class PlainAPI: + """Not a web.View - exercises the qualname-based detection.""" + @validate(request_schema={"type": "object"}) + async def post(self, data, request): + return {"plain_class": True} + + +@validate(request_schema=None) +async def passthrough(request, *args): + return web.json_response({"raw": True}, status=418) + + +@validate(request_schema=None) +async def bool_tuple(request, *args): + return {"flag": "x"}, True + + +@validate(request_schema=None) +async def tuple_data(request, *args): + return ("a", "b") + + +async def test_type_mismatch_error_path(aiohttp_client): + app = web.Application() + app.router.add_post('/', hello) + client = await aiohttp_client(app) + + resp = await client.post('/', data='{"text": 123}') + assert resp.status == 400 + text = await resp.json() + assert text["errors"]["text"] + + +async def test_plain_class_method(aiohttp_client): + app = web.Application() + app.router.add_post('/', PlainAPI().post) + client = await aiohttp_client(app) + + resp = await client.post('/', data='{}') + assert resp.status == 200 + data = await resp.json() + assert data["plain_class"] is True + + +async def test_stream_response_passthrough(aiohttp_client): + app = web.Application() + app.router.add_post('/', passthrough) + client = await aiohttp_client(app) + + resp = await client.post('/', data='{}') + assert resp.status == 418 + data = await resp.json() + assert data["raw"] is True + + +async def test_bool_tuple_is_data_not_status(aiohttp_client): + app = web.Application() + app.router.add_post('/', bool_tuple) + client = await aiohttp_client(app) + + resp = await client.post('/', data='{}') + assert resp.status == 200 + data = await resp.json() + assert data == [{"flag": "x"}, True] + + +async def test_tuple_data_serialized_as_array(aiohttp_client): + app = web.Application() + app.router.add_post('/', tuple_data) + client = await aiohttp_client(app) + + resp = await client.post('/', data='{}') + assert resp.status == 200 + data = await resp.json() + assert data == ["a", "b"] From 960321a595c7f3af4a3cf9d7afc3b07735546159 Mon Sep 17 00:00:00 2001 From: Dmitry Chaplinsky Date: Sun, 19 Jul 2026 15:05:54 +0000 Subject: [PATCH 4/5] Restore 1.x awaitable-return support, hoist validators, add format_checker - A plain (non-async) handler returning an awaitable is awaited again, matching the old asyncio.coroutine behavior the async rewrite dropped - jsonschema validator instances are built once at decoration time instead of per request - New optional format_checker argument, passed through to the validator, for opt-in string format validation - HISTORY now explicitly flags the (data, status) breaking edge case - 16 tests, 100% line coverage Co-Authored-By: Claude Fable 5 Claude-Session: https://claude.ai/code/session_01Ha16zNy2fDMdrZBMQGgpBt --- HISTORY.rst | 5 ++++ README.rst | 7 +++++ aiohttp_validate/__init__.py | 43 ++++++++++++++++++------------ tests/test_aiohttp_validate.py | 48 ++++++++++++++++++++++++++++++++++ 4 files changed, 87 insertions(+), 16 deletions(-) diff --git a/HISTORY.rst b/HISTORY.rst index a135a7d..699db8a 100644 --- a/HISTORY.rst +++ b/HISTORY.rst @@ -8,6 +8,11 @@ History * Revived for modern Python: works on Python 3.9-3.13 (the removal of ``asyncio.coroutine`` in Python 3.11 had made the library unusable there). * Handlers may return a ``(data, status)`` tuple to set the response status. + (Breaking edge case: a handler that previously returned exactly such a + tuple *as response data* must now return a list instead.) +* Optional ``format_checker`` argument to also validate string formats. +* Schema validators are built once at decoration time instead of on + every request. * Plain (non-async) handlers are still supported. * Type hints and a ``py.typed`` marker. * Modern packaging (``pyproject.toml``), tests on GitHub Actions, releases diff --git a/README.rst b/README.rst index 5b1e82b..f419a46 100644 --- a/README.rst +++ b/README.rst @@ -67,6 +67,13 @@ your response data is itself such a tuple, return it as a list instead — JSON has no tuples, the wire format is identical — or return a ready ``web.json_response``. +To also validate string formats (``date``, ``email``, ...), pass a format +checker (extra format support follows `jsonschema's rules`_):: + + @validate(request_schema=..., format_checker=jsonschema.FormatChecker()) + +.. _jsonschema's rules: https://python-jsonschema.readthedocs.io/en/stable/validate/#validating-formats + Features -------- * The decorator to (optionally) validate the request to your aiohttp endpoint and it's response. diff --git a/aiohttp_validate/__init__.py b/aiohttp_validate/__init__.py index a27b222..d6a61d0 100644 --- a/aiohttp_validate/__init__.py +++ b/aiohttp_validate/__init__.py @@ -36,11 +36,10 @@ def _raise_exception(cls: type, reason: str, data: Any = None) -> NoReturn: ) -def _validate_data(data: Any, schema: dict, validator_cls: type) -> None: +def _validate_data(data: Any, validator: Any) -> None: """ - Validate the dict against given schema (using given validator class). + Validate the data against the given (prebuilt) schema validator. """ - validator = validator_cls(schema) _errors = defaultdict(list) def set_nested_item(dataDict, mapList, key, val): @@ -93,7 +92,8 @@ def set_nested_item(dataDict, mapList, key, val): def validate(request_schema: Optional[dict] = None, - response_schema: Optional[dict] = None): + response_schema: Optional[dict] = None, + format_checker: Optional[Any] = None): """ Decorate request handler to make it automagically validate its request and response. @@ -107,18 +107,27 @@ def validate(request_schema: Optional[dict] = None, Because the ``(data, status)`` form is detected by shape, response data that is itself a 2-tuple ending in an int must be returned as a list (JSON has no tuples anyway) or as a ready ``web.json_response``. + + Pass ``format_checker=jsonschema.FormatChecker()`` to also validate + string formats such as ``date-time`` or ``email`` (off by default, + matching jsonschema's own behavior). """ def wrapper(func): - # Validating the schemas itself. - # Die with exception if they aren't valid + # Validate the schemas themselves and build their validators once, + # at decoration time. Die with exception if they aren't valid + def build_validator(schema): + validator_cls = validator_for(schema) + validator_cls.check_schema(schema) + return validator_cls(schema, format_checker=format_checker) + + _request_validator = None if request_schema is not None: - _request_schema_validator = validator_for(request_schema) - _request_schema_validator.check_schema(request_schema) + _request_validator = build_validator(request_schema) + _response_validator = None if response_schema is not None: - _response_schema_validator = validator_for(response_schema) - _response_schema_validator.check_schema(response_schema) + _response_validator = build_validator(response_schema) func_is_coro = inspect.iscoroutinefunction(func) @@ -144,9 +153,8 @@ async def wrapped(*args): "Request is malformed; could not decode JSON object.") # Validate request data against request schema (if given) - if request_schema is not None: - _validate_data(req_body, request_schema, - _request_schema_validator) + if _request_validator is not None: + _validate_data(req_body, _request_validator) coro_args = req_body, request if class_based: @@ -156,6 +164,10 @@ async def wrapped(*args): context = await func(*coro_args) else: context = func(*coro_args) + # 1.x compat: a plain function may hand back an awaitable + # (e.g. a lambda delegating to a coroutine function) + if inspect.isawaitable(context): + context = await context # No validation of response for websockets stream if isinstance(context, web.StreamResponse): @@ -172,9 +184,8 @@ async def wrapped(*args): context, status = context # Validate response data against response schema (if given) - if response_schema is not None: - _validate_data(context, response_schema, - _response_schema_validator) + if _response_validator is not None: + _validate_data(context, _response_validator) try: return web.json_response(context, status=status) diff --git a/tests/test_aiohttp_validate.py b/tests/test_aiohttp_validate.py index e5cf7bf..ff49671 100644 --- a/tests/test_aiohttp_validate.py +++ b/tests/test_aiohttp_validate.py @@ -9,6 +9,8 @@ """ from datetime import datetime +import jsonschema + from aiohttp_validate import validate from aiohttp import web @@ -335,3 +337,49 @@ async def test_tuple_data_serialized_as_array(aiohttp_client): assert resp.status == 200 data = await resp.json() assert data == ["a", "b"] + + +async def _delegate_target(request, *args): + return {"delegated": True} + + +# A plain (non-async) callable returning an awaitable - 1.x supported this +delegating_handler = validate(request_schema={"type": "object"})( + lambda request, *args: _delegate_target(request, *args)) + + +@validate( + request_schema={ + "type": "object", + "properties": {"when": {"type": "string", "format": "date"}}, + "required": ["when"], + }, + format_checker=jsonschema.FormatChecker(), +) +async def needs_datetime(request, *args): + return {"ok": True} + + +async def test_sync_handler_returning_awaitable(aiohttp_client): + app = web.Application() + app.router.add_post('/', delegating_handler) + client = await aiohttp_client(app) + + resp = await client.post('/', data='{}') + assert resp.status == 200 + data = await resp.json() + assert data["delegated"] is True + + +async def test_format_checker(aiohttp_client): + app = web.Application() + app.router.add_post('/', needs_datetime) + client = await aiohttp_client(app) + + resp = await client.post('/', data='{"when": "2026-07-19"}') + assert resp.status == 200 + + resp = await client.post('/', data='{"when": "not a date"}') + assert resp.status == 400 + data = await resp.json() + assert data["errors"]["when"] From 1fd6be33829012cd9d49fb3ab2b5066ad05cc0e1 Mon Sep 17 00:00:00 2001 From: Dmitry Chaplinsky Date: Sun, 19 Jul 2026 15:09:05 +0000 Subject: [PATCH 5/5] Collapse the handler dispatch to a single awaitable check - Calling the handler and awaiting the result if it is awaitable covers coroutine functions and plain callables alike, so the hoisted iscoroutinefunction dispatch is gone entirely - format_checker is typed as Optional[FormatChecker] instead of Any - Validator setup uses single conditional bindings Co-Authored-By: Claude Fable 5 Claude-Session: https://claude.ai/code/session_01Ha16zNy2fDMdrZBMQMGgpBt --- aiohttp_validate/__init__.py | 31 +++++++++++++------------------ 1 file changed, 13 insertions(+), 18 deletions(-) diff --git a/aiohttp_validate/__init__.py b/aiohttp_validate/__init__.py index d6a61d0..7e9acdb 100644 --- a/aiohttp_validate/__init__.py +++ b/aiohttp_validate/__init__.py @@ -10,6 +10,7 @@ from aiohttp import web from aiohttp.abc import AbstractView +from jsonschema import FormatChecker from jsonschema.validators import validator_for __author__ = """Dmitry Chaplinsky""" @@ -93,7 +94,7 @@ def set_nested_item(dataDict, mapList, key, val): def validate(request_schema: Optional[dict] = None, response_schema: Optional[dict] = None, - format_checker: Optional[Any] = None): + format_checker: Optional[FormatChecker] = None): """ Decorate request handler to make it automagically validate its request and response. @@ -121,15 +122,12 @@ def build_validator(schema): validator_cls.check_schema(schema) return validator_cls(schema, format_checker=format_checker) - _request_validator = None - if request_schema is not None: - _request_validator = build_validator(request_schema) - - _response_validator = None - if response_schema is not None: - _response_validator = build_validator(response_schema) - - func_is_coro = inspect.iscoroutinefunction(func) + _request_validator = ( + build_validator(request_schema) + if request_schema is not None else None) + _response_validator = ( + build_validator(response_schema) + if response_schema is not None else None) @functools.wraps(func) async def wrapped(*args): @@ -160,14 +158,11 @@ async def wrapped(*args): if class_based: coro_args = (args[0],) + coro_args - if func_is_coro: - context = await func(*coro_args) - else: - context = func(*coro_args) - # 1.x compat: a plain function may hand back an awaitable - # (e.g. a lambda delegating to a coroutine function) - if inspect.isawaitable(context): - context = await context + # Covers both coroutine functions and plain callables that + # return an awaitable (1.x supported the latter too) + context = func(*coro_args) + if inspect.isawaitable(context): + context = await context # No validation of response for websockets stream if isinstance(context, web.StreamResponse):