Skip to content

Commit

Permalink
First commit
Browse files Browse the repository at this point in the history
  • Loading branch information
ri-gilfanov committed Apr 14, 2021
1 parent ce5ef96 commit 26acbc0
Show file tree
Hide file tree
Showing 13 changed files with 1,426 additions and 0 deletions.
63 changes: 63 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
# ===========================================================
# Untracked file templates by Git version control system
# Шаблоны файлов неотслеживаемых системой контроля версий Git
# ===========================================================

# Python programming language
# Язык программирования Python
# ============================

# Python bytecode
# Байт-код Python
*.pyc

# Python virtual environment
# Виртуальное окружение Python
.venv

# Documentation generator Sphinx
# Генератор документации Sphinx
docs/_build

# dependency and packaging manager Poetry
# менеджер зависимостей и пакетирования Poetry
dist
*.egg-info

# Checkers
.mypy_cache


# Database (DB)
# Базы данных
# =============
*.sqlite3

# Integrated Development Environment (IDE)
# Интегрированные среды разработки
# ========================================

# Atom
.atom/

# Geany
*.geany

# JetBrains (AppCode, CLion, DataGrip, GoLand, IntelliJ IDEA, PhpStorm,
# PyCharm, Rider, RubyMine, WebStorm)
.idea/

# Sublime Text
*.sublime-*

# Visual Studio Code
.vscode
*.code-workspace


# Other text editors
# Другие текстовые редакторы
# ==========================

# Nano
*.swp
5 changes: 5 additions & 0 deletions .mypy.ini
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
[mypy]
files = aiohttp_sqlalchemy, tests

[mypy-sqlalchemy.*]
ignore_missing_imports = True
22 changes: 22 additions & 0 deletions .readthedocs.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
# .readthedocs.yml
# Read the Docs configuration file
# See https://docs.readthedocs.io/en/stable/config-file/v2.html for details

# Required
version: 2

# Build documentation in the docs/ directory with Sphinx
sphinx:
configuration: docs/conf.py

# Build documentation with MkDocs
#mkdocs:
# configuration: mkdocs.yml

# Optionally build your docs in additional formats such as PDF and ePub
formats: all

# Optionally set the version of Python and requirements required to build your docs
python:
version: 3.9

33 changes: 33 additions & 0 deletions README.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
==================
aiohttp-sqlalchemy
==================

SQLAlchemy >= 1.4 support for aiohttp.

Install
-------
::

pip install aiohttp-sqlalchemy


Example
-------

.. code-block:: python
from aiohttp import web
import aiohttp_sqlalchemy
from aiohttp_sqlalchemy import sa_engine, sa_middleware
routes = web.RouteTableDef()
@routes.get('/')
async def main(request):
async with request['sa_main'].begin():
# some code
app = web.Application(middlewares=[sa_middleware()])
aiohttp_sqlalchemy.setup(app, [sa_engine('sqlite+aiosqlite:///')])
app.add_routes(routes)
web.run_app(app)
54 changes: 54 additions & 0 deletions aiohttp_sqlalchemy/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
from aiohttp.web import middleware
from aiohttp.abc import AbstractView
from asyncio import iscoroutinefunction
from functools import wraps
from sqlalchemy.ext.asyncio import AsyncSession, create_async_engine
from typing import TYPE_CHECKING

if TYPE_CHECKING:
from aiohttp.web import Application, Request, Response
from sqlalchemy.ext.asyncio import AsyncEngine
from typing import Callable, Iterable, Tuple


__version__ = '0.1a1'


def sa_decorator(key: str = 'sa_main'):
def wrapper(handler):
@wraps(handler)
async def wrapped(*args, **kwargs):
# Class based view decorating
if issubclass(handler, AbstractView):
request = args[0].request
async with AsyncSession(request.app[key]) as request[key]:
return await handler(request)

# Coroutine function decorating
elif iscoroutinefunction(handler):
request = args[0]
async with AsyncSession(request.app[key]) as request[key]:
return await handler(request)

else:
raise TypeError('Unsupported handler type')

return wrapped
return wrapper


def sa_middleware(key: str = 'sa_main') -> 'Callable':
@middleware
async def sa_middleware_(request: 'Request', handler: 'Callable') -> 'Response':
async with AsyncSession(request.app[key]) as request[key]:
return await handler(request)
return sa_middleware_


def sa_engine(key: str = 'sa_main', *args, **kwargs) -> 'Tuple[str, AsyncEngine]':
return key, create_async_engine(*args, **kwargs)


def setup(app: 'Application', engines: 'Iterable[Tuple[str, AsyncEngine]]'):
for app_key, engine in engines:
app[app_key] = engine
20 changes: 20 additions & 0 deletions docs/Makefile
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
# Minimal makefile for Sphinx documentation
#

# You can set these variables from the command line, and also
# from the environment for the first two.
SPHINXOPTS ?=
SPHINXBUILD ?= sphinx-build
SOURCEDIR = .
BUILDDIR = _build

# Put it first so that "make" without argument is like "make help".
help:
@$(SPHINXBUILD) -M help "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O)

.PHONY: help Makefile

# Catch-all target: route all unknown targets to Sphinx using the new
# "make mode" option. $(O) is meant as a shortcut for $(SPHINXOPTS).
%: Makefile
@$(SPHINXBUILD) -M $@ "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O)
59 changes: 59 additions & 0 deletions docs/conf.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
# Configuration file for the Sphinx documentation builder.
#
# This file only contains a selection of the most common options. For a full
# list see the documentation:
# https://www.sphinx-doc.org/en/master/usage/configuration.html

# -- Path setup --------------------------------------------------------------

# 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.
#
# import os
# import sys
# sys.path.insert(0, os.path.abspath('.'))


# -- Project information -----------------------------------------------------

project = 'aiohttp-sqlalchemy'
copyright = '2021, Ruslan Ilyasovich Gilfanov'
author = 'Ruslan Ilyasovich Gilfanov'

# The full version, including alpha/beta/rc tags
release = '0.1a1'


# -- General configuration ---------------------------------------------------

# Add any Sphinx extension module names here, as strings. They can be
# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom
# ones.
extensions = [
]

# Add any paths that contain templates here, relative to this directory.
templates_path = ['_templates']

# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
# This pattern also affects html_static_path and html_extra_path.
exclude_patterns = ['_build', 'Thumbs.db', '.DS_Store']


# -- Read the Docs -----------------------------------------------------------
master_doc = 'index'


# -- 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 = 'alabaster'

# 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']

0 comments on commit 26acbc0

Please sign in to comment.