Skip to content

Commit

Permalink
Merge cd006b2 into 1c5dd5c
Browse files Browse the repository at this point in the history
  • Loading branch information
sjaensch committed May 27, 2019
2 parents 1c5dd5c + cd006b2 commit 906c144
Show file tree
Hide file tree
Showing 19 changed files with 484 additions and 364 deletions.
7 changes: 3 additions & 4 deletions .pre-commit-config.yaml
Expand Up @@ -29,11 +29,10 @@ repos:
- id: requirements-txt-fixer
language_version: python3.6
files: requirements-dev.txt
- repo: git://github.com/pre-commit/mirrors-autopep8
rev: v1.4.3
- repo: https://github.com/ambv/black
rev: 19.3b0
hooks:
- id: autopep8
args: ['-i', '--ignore=E309,E501']
- id: black
language_version: python3.6
- repo: https://gitlab.com/pycqa/flake8.git
rev: 3.7.6
Expand Down
4 changes: 2 additions & 2 deletions bravado_asyncio/__init__.py
@@ -1,4 +1,4 @@
__all__ = ['version']
__all__ = ["version"]


version = '1.4.1'
version = "1.4.1"
10 changes: 4 additions & 6 deletions bravado_asyncio/definitions.py
Expand Up @@ -6,13 +6,11 @@


class RunMode(Enum):
THREAD = 'thread'
FULL_ASYNCIO = 'full_asyncio'
THREAD = "thread"
FULL_ASYNCIO = "full_asyncio"


AsyncioResponse = NamedTuple(
'AsyncioResponse', [
('response', aiohttp.ClientResponse),
('remaining_timeout', Optional[float]),
]
"AsyncioResponse",
[("response", aiohttp.ClientResponse), ("remaining_timeout", Optional[float])],
)
5 changes: 3 additions & 2 deletions bravado_asyncio/future_adapter.py
Expand Up @@ -11,9 +11,10 @@


class BaseFutureAdapter(BravadoFutureAdapter):

def __init__(self, future: Any) -> None:
raise NotImplementedError('Do not instantiate BaseFutureAdapter, use one of its subclasses')
raise NotImplementedError(
"Do not instantiate BaseFutureAdapter, use one of its subclasses"
)


class FutureAdapter(BaseFutureAdapter):
Expand Down
57 changes: 36 additions & 21 deletions bravado_asyncio/http_client.py
Expand Up @@ -95,7 +95,9 @@ def __init__(
self.bravado_future_class = AsyncioHttpFuture
self.future_adapter = AsyncioFutureAdapter
else:
raise ValueError('Don\'t know how to handle run mode {}'.format(str(run_mode)))
raise ValueError(
"Don't know how to handle run mode {}".format(str(run_mode))
)

# don't use the shared client_session if we've been passed an explicit loop argument
if loop:
Expand All @@ -110,7 +112,9 @@ def __init__(
cafile = None
if isinstance(ssl_verify, str):
cafile = ssl_verify
self.ssl_context = ssl.create_default_context(cafile=cafile) # type: Optional[ssl.SSLContext]
self.ssl_context = ssl.create_default_context(
cafile=cafile
) # type: Optional[ssl.SSLContext]
if ssl_cert:
if isinstance(ssl_cert, str):
ssl_cert = [ssl_cert]
Expand All @@ -137,43 +141,50 @@ def request(
:rtype: :class: `bravado_core.http_future.HttpFuture`
"""

orig_data = request_params.get('data', {})
orig_data = request_params.get("data", {})
if isinstance(orig_data, Mapping):
data = FormData()
for name, value in orig_data.items():
str_value = str(value) if not is_list_like(value) else [str(v) for v in value]
str_value = (
str(value) if not is_list_like(value) else [str(v) for v in value]
)
data.add_field(name, str_value)
else:
data = orig_data

if isinstance(data, FormData):
for name, file_tuple in request_params.get('files', {}):
for name, file_tuple in request_params.get("files", {}):
stream_obj = file_tuple[1]
data.add_field(name, stream_obj, filename=file_tuple[0])

params = self.prepare_params(request_params.get('params'))
params = self.prepare_params(request_params.get("params"))

connect_timeout = request_params.get('connect_timeout') # type: Optional[float]
request_timeout = request_params.get('timeout') # type: Optional[float]
connect_timeout = request_params.get("connect_timeout") # type: Optional[float]
request_timeout = request_params.get("timeout") # type: Optional[float]
# mypy thinks the type of total and connect is float, even though it is Optional[float]. Let's ignore the error.
timeout = aiohttp.ClientTimeout(
total=request_timeout,
connect=connect_timeout,
) if (connect_timeout or request_timeout) else None
timeout = (
aiohttp.ClientTimeout(total=request_timeout, connect=connect_timeout)
if (connect_timeout or request_timeout)
else None
)

# aiohttp always adds a Content-Type header, and this breaks some servers that don't
# expect it for non-POST/PUT requests: https://github.com/aio-libs/aiohttp/issues/457
skip_auto_headers = ['Content-Type'] if request_params.get('method') not in ['POST', 'PUT'] else None
skip_auto_headers = (
["Content-Type"]
if request_params.get("method") not in ["POST", "PUT"]
else None
)

coroutine = self.client_session.request(
method=request_params.get('method') or 'GET',
url=cast(str, request_params.get('url', '')),
method=request_params.get("method") or "GET",
url=cast(str, request_params.get("url", "")),
params=params,
data=data,
headers={
# Convert not string headers to string
k: from_bytes(v) if isinstance(v, bytes) else str(v)
for k, v in request_params.get('headers', {}).items()
for k, v in request_params.get("headers", {}).items()
},
skip_auto_headers=skip_auto_headers,
timeout=timeout,
Expand All @@ -189,17 +200,21 @@ def request(
request_config=request_config,
)

def prepare_params(self, params: Optional[Dict[str, Any]]) -> Union[Optional[Dict[str, Any]], MultiDict]:
def prepare_params(
self, params: Optional[Dict[str, Any]]
) -> Union[Optional[Dict[str, Any]], MultiDict]:
if not params:
return params

items = []
for key, value in params.items():
entries = [(key, str(value))] if not is_list_like(value) else [(key, str(v)) for v in value]
entries = (
[(key, str(value))]
if not is_list_like(value)
else [(key, str(v)) for v in value]
)
items.extend(entries)
return MultiDict(items)

def _get_ssl_params(self) -> Dict[str, Any]:
return {
'ssl': self.ssl_context if self.ssl_context else self.ssl_verify
}
return {"ssl": self.ssl_context if self.ssl_context else self.ssl_verify}
18 changes: 13 additions & 5 deletions bravado_asyncio/response_adapter.py
Expand Up @@ -10,7 +10,7 @@
from bravado_asyncio.definitions import AsyncioResponse


T = TypeVar('T')
T = TypeVar("T")


class AioHTTPResponseAdapter(IncomingResponse):
Expand Down Expand Up @@ -41,7 +41,9 @@ def raw_bytes(self) -> bytes:

@property
def reason(self) -> str:
return cast(str, self._delegate.reason) # aiohttp 3.4.0 doesn't annotate this attribute correctly
return cast(
str, self._delegate.reason
) # aiohttp 3.4.0 doesn't annotate this attribute correctly

@property
def headers(self) -> CIMultiDict:
Expand All @@ -58,11 +60,17 @@ class AsyncioHTTPResponseAdapter(AioHTTPResponseAdapter):

@property
async def text(self) -> str: # type: ignore
return await asyncio.wait_for(self._delegate.text(), timeout=self._remaining_timeout, loop=self._loop)
return await asyncio.wait_for(
self._delegate.text(), timeout=self._remaining_timeout, loop=self._loop
)

@property
async def raw_bytes(self) -> bytes: # type: ignore
return await asyncio.wait_for(self._delegate.read(), timeout=self._remaining_timeout, loop=self._loop)
return await asyncio.wait_for(
self._delegate.read(), timeout=self._remaining_timeout, loop=self._loop
)

async def json(self, **_: Any) -> Dict[str, Any]: # type: ignore
return await asyncio.wait_for(self._delegate.json(), timeout=self._remaining_timeout, loop=self._loop)
return await asyncio.wait_for(
self._delegate.json(), timeout=self._remaining_timeout, loop=self._loop
)
4 changes: 3 additions & 1 deletion bravado_asyncio/thread_loop.py
Expand Up @@ -17,6 +17,8 @@ def get_thread_loop() -> asyncio.AbstractEventLoop:
global event_loop
if event_loop is None:
event_loop = asyncio.new_event_loop()
thread = threading.Thread(target=run_event_loop, args=(event_loop,), daemon=True)
thread = threading.Thread(
target=run_event_loop, args=(event_loop,), daemon=True
)
thread.start()
return event_loop
52 changes: 26 additions & 26 deletions docs/conf.py
Expand Up @@ -20,9 +20,9 @@
import sphinx_rtd_theme


base_dir = os.path.join(os.path.dirname(__file__), '..')
base_dir = os.path.join(os.path.dirname(__file__), "..")
about = {}
with open(os.path.join(base_dir, 'bravado_asyncio', '__init__.py')) as f:
with open(os.path.join(base_dir, "bravado_asyncio", "__init__.py")) as f:
exec(f.read(), about)


Expand All @@ -36,36 +36,36 @@
# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom
# ones.
extensions = [
'sphinx.ext.autodoc',
'sphinx.ext.intersphinx',
'sphinx_autodoc_annotation',
"sphinx.ext.autodoc",
"sphinx.ext.intersphinx",
"sphinx_autodoc_annotation",
]

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

# The suffix(es) of source filenames.
# You can specify multiple suffix as a list of string:
#
# source_suffix = ['.rst', '.md']
source_suffix = '.rst'
source_suffix = ".rst"

# The master toctree document.
master_doc = 'index'
master_doc = "index"

# General information about the project.
project = 'bravado-asyncio'
copyright = '2017,2018, Stephan Jaensch'
author = 'Stephan Jaensch'
project = "bravado-asyncio"
copyright = "2017,2018, Stephan Jaensch"
author = "Stephan Jaensch"

# 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 = about['version']
version = about["version"]
# The full version, including alpha/beta/rc tags.
release = about['version']
release = about["version"]

# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
Expand All @@ -77,10 +77,10 @@
# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
# This patterns also effect to html_static_path and html_extra_path
exclude_patterns = ['_build', 'Thumbs.db', '.DS_Store']
exclude_patterns = ["_build", "Thumbs.db", ".DS_Store"]

# The name of the Pygments (syntax highlighting) style to use.
pygments_style = 'sphinx'
pygments_style = "sphinx"

# If true, `todo` and `todoList` produce output, else they produce nothing.
todo_include_todos = False
Expand All @@ -91,7 +91,7 @@
# The theme to use for HTML and HTML Help pages. See the documentation for
# a list of builtin themes.
#
html_theme = 'sphinx_rtd_theme'
html_theme = "sphinx_rtd_theme"
html_theme_path = [sphinx_rtd_theme.get_html_theme_path()]

# Theme options are theme-specific and customize the look and feel of a theme
Expand All @@ -103,34 +103,34 @@
# 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']
html_static_path = ["_static"]

# Custom sidebar templates, must be a dictionary that maps document names
# to template names.
#
# This is required for the alabaster theme
# refs: http://alabaster.readthedocs.io/en/latest/installation.html#sidebars
html_sidebars = {
'**': [
'relations.html', # needs 'show_related': True theme option to display
'searchbox.html',
"**": [
"relations.html", # needs 'show_related': True theme option to display
"searchbox.html",
]
}


# -- Options for HTMLHelp output ------------------------------------------

# Output file base name for HTML help builder.
htmlhelp_basename = 'bravado-asynciodoc'
htmlhelp_basename = "bravado-asynciodoc"


# -- Intersphinx settings -------------------------------------------------
intersphinx_mapping = {
'python': ('https://docs.python.org/3.6', None),
'aiobravado': ('https://aiobravado.readthedocs.io/en/stable/', None),
'aiohttp': ('https://aiohttp.readthedocs.io/en/stable/', None),
'bravado': ('https://bravado.readthedocs.io/en/stable/', None),
'bravado_core': ('https://bravado-core.readthedocs.io/en/stable/', None),
"python": ("https://docs.python.org/3.6", None),
"aiobravado": ("https://aiobravado.readthedocs.io/en/stable/", None),
"aiohttp": ("https://aiohttp.readthedocs.io/en/stable/", None),
"bravado": ("https://bravado.readthedocs.io/en/stable/", None),
"bravado_core": ("https://bravado-core.readthedocs.io/en/stable/", None),
}

# -- Autodoc: don't skip __init__ methods ---------------------------------
Expand Down

0 comments on commit 906c144

Please sign in to comment.