Skip to content

Commit

Permalink
Apply black (#69)
Browse files Browse the repository at this point in the history
* Add black to dev-env requirements

* Apply black to everything
  • Loading branch information
ulgens authored Jul 1, 2021
1 parent 3595910 commit 3ca01d4
Show file tree
Hide file tree
Showing 15 changed files with 449 additions and 316 deletions.
1 change: 1 addition & 0 deletions dev-env-requirements.txt
Original file line number Diff line number Diff line change
Expand Up @@ -6,3 +6,4 @@ pytest-django==3.5.0
pytest-cov==2.7.1
flake8==3.7.7
mock==2.0.0
black==21.6b0
51 changes: 28 additions & 23 deletions graphene_django_optimizer/query.py
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ class QueryOptimizer(object):

def __init__(self, info, **options):
self.root_info = info
self.disable_abort_only = options.pop('disable_abort_only', False)
self.disable_abort_only = options.pop("disable_abort_only", False)

def optimize(self, queryset):
info = self.root_info
Expand All @@ -61,15 +61,15 @@ def optimize(self, queryset):

def _get_type(self, field_def):
a_type = field_def.type
while hasattr(a_type, 'of_type'):
while hasattr(a_type, "of_type"):
a_type = a_type.of_type
return a_type

def _get_possible_types(self, graphql_type):
if isinstance(graphql_type, (GraphQLInterfaceType, GraphQLUnionType)):
return self.root_info.schema.get_possible_types(graphql_type)
else:
return (graphql_type, )
return (graphql_type,)

def _get_base_model(self, graphql_types):
models = tuple(t.graphene_type._meta.model for t in graphql_types)
Expand All @@ -87,10 +87,10 @@ def handle_inline_fragment(self, selection, schema, possible_types, store):
parent_model = self._get_base_model(possible_types)
if not parent_model:
continue
path_from_parent = _get_path_from_parent(
fragment_model._meta, parent_model)
path_from_parent = _get_path_from_parent(fragment_model._meta, parent_model)
select_related_name = LOOKUP_SEP.join(
p.join_field.name for p in path_from_parent)
p.join_field.name for p in path_from_parent
)
if not select_related_name:
continue
fragment_store = self._optimize_gql_selections(
Expand Down Expand Up @@ -124,8 +124,7 @@ def _optimize_gql_selections(self, field_type, field_ast):
possible_types = self._get_possible_types(graphql_type)
for selection in selection_set.selections:
if isinstance(selection, InlineFragment):
self.handle_inline_fragment(
selection, schema, possible_types, store)
self.handle_inline_fragment(selection, schema, possible_types, store)
else:
name = selection.name.value
if isinstance(selection, FragmentSpread):
Expand All @@ -138,9 +137,9 @@ def _optimize_gql_selections(self, field_type, field_ast):

graphene_type = possible_type.graphene_type
# Check if graphene type is a relay connection or a relay edge
if hasattr(graphene_type._meta, 'node') or (
hasattr(graphene_type, 'cursor')
and hasattr(graphene_type, 'node')
if hasattr(graphene_type._meta, "node") or (
hasattr(graphene_type, "cursor")
and hasattr(graphene_type, "node")
):
relay_store = self._optimize_gql_selections(
self._get_type(selection_field_def),
Expand All @@ -152,7 +151,7 @@ def _optimize_gql_selections(self, field_type, field_ast):
except ImportError:
store.abort_only_optimization()
else:
model = getattr(graphene_type._meta, 'model', None)
model = getattr(graphene_type._meta, "model", None)
if model and name not in optimized_fields_by_model:
field_model = optimized_fields_by_model[name] = model
if field_model == model:
Expand All @@ -167,9 +166,11 @@ def _optimize_gql_selections(self, field_type, field_ast):

def _optimize_field(self, store, model, selection, field_def, parent_type):
optimized_by_name = self._optimize_field_by_name(
store, model, selection, field_def)
store, model, selection, field_def
)
optimized_by_hints = self._optimize_field_by_hints(
store, selection, field_def, parent_type)
store, selection, field_def, parent_type
)
optimized = optimized_by_name or optimized_by_hints
if not optimized:
store.abort_only_optimization()
Expand Down Expand Up @@ -211,7 +212,7 @@ def _optimize_field_by_name(self, store, model, selection, field_def):
return False

def _get_optimization_hints(self, resolver):
return getattr(resolver, 'optimization_hints', None)
return getattr(resolver, "optimization_hints", None)

def _get_value(self, info, value):
if isinstance(value, Variable):
Expand Down Expand Up @@ -267,7 +268,7 @@ def _get_name_from_resolver(self, resolver):
if name_fn:
return name_fn()
if self._is_resolver_for_id_field(resolver):
return 'id'
return "id"
elif isinstance(resolver, functools.partial):
resolver_fn = resolver
if resolver_fn.func != default_resolver:
Expand All @@ -280,16 +281,19 @@ def _get_name_from_resolver(self, resolver):
# No suitable instances found, default to first arg
arg = resolver_fn.args[0]
resolver_fn = arg
if isinstance(resolver_fn, functools.partial) and resolver_fn.func == default_resolver:
if (
isinstance(resolver_fn, functools.partial)
and resolver_fn.func == default_resolver
):
return resolver_fn.args[0]
if self._is_resolver_for_id_field(resolver_fn):
return 'id'
return "id"
return resolver_fn

def _is_resolver_for_id_field(self, resolver):
resolve_id = DjangoObjectType.resolve_id
# For python 2 unbound method:
if hasattr(resolve_id, 'im_func'):
if hasattr(resolve_id, "im_func"):
resolve_id = resolve_id.im_func
return resolver == resolve_id

Expand All @@ -300,8 +304,9 @@ def _get_model_field_from_name(self, model, name):
descriptor = model.__dict__.get(name)
if not descriptor:
return None
return getattr(descriptor, 'rel', None) \
or getattr(descriptor, 'related', None) # Django < 1.9
return getattr(descriptor, "rel", None) or getattr(
descriptor, "related", None
) # Django < 1.9

def _is_foreign_key_id(self, model_field, name):
return (
Expand All @@ -325,7 +330,7 @@ def _create_resolve_info(self, field_name, field_asts, return_type, parent_type)
)


class QueryOptimizerStore():
class QueryOptimizerStore:
def __init__(self, disable_abort_only=False):
self.select_list = []
self.prefetch_list = []
Expand Down Expand Up @@ -402,7 +407,7 @@ def _get_path_from_parent(self, parent):
model to the current model, or an empty list if parent is not a
parent of the current model.
"""
if hasattr(self, 'get_path_from_parent'):
if hasattr(self, "get_path_from_parent"):
return self.get_path_from_parent(parent)
if self.model is parent:
return []
Expand Down
3 changes: 2 additions & 1 deletion graphene_django_optimizer/types.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,8 @@ class Meta:
def can_optimize_resolver(cls, resolver_info):
return (
isinstance(resolver_info.return_type, GrapheneObjectType)
and resolver_info.return_type.graphene_type is cls)
and resolver_info.return_type.graphene_type is cls
)

@classmethod
def get_queryset(cls, queryset, info):
Expand Down
2 changes: 1 addition & 1 deletion graphene_django_optimizer/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,4 +2,4 @@


def is_iterable(obj):
return hasattr(obj, '__iter__') and not isinstance(obj, str)
return hasattr(obj, "__iter__") and not isinstance(obj, str)
64 changes: 32 additions & 32 deletions setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,46 +4,46 @@
import sys
from setuptools import setup

needs_pytest = {'pytest', 'test', 'ptr'}.intersection(sys.argv)
pytest_runner = ['pytest-runner >=4.0,<5dev'] if needs_pytest else []
needs_pytest = {"pytest", "test", "ptr"}.intersection(sys.argv)
pytest_runner = ["pytest-runner >=4.0,<5dev"] if needs_pytest else []


def read(fname):
return open(os.path.join(os.path.dirname(__file__), fname)).read()


setup(
name='graphene-django-optimizer',
version='0.8.0',
author='Tomás Fox',
author_email='[email protected]',
description='Optimize database access inside graphene queries.',
license='MIT',
keywords='graphene django optimizer optimize graphql query prefetch select related',
url='https://github.com/tfoxy/graphene-django-optimizer',
packages=['graphene_django_optimizer'],
name="graphene-django-optimizer",
version="0.8.0",
author="Tomás Fox",
author_email="[email protected]",
description="Optimize database access inside graphene queries.",
license="MIT",
keywords="graphene django optimizer optimize graphql query prefetch select related",
url="https://github.com/tfoxy/graphene-django-optimizer",
packages=["graphene_django_optimizer"],
setup_requires=pytest_runner,
long_description=read('README.md'),
long_description_content_type='text/markdown',
long_description=read("README.md"),
long_description_content_type="text/markdown",
classifiers=[
'Development Status :: 4 - Beta',
'Environment :: Web Environment',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: 3.6',
'Programming Language :: Python :: 3.7',
'Programming Language :: Python :: 3.8',
'Framework :: Django',
'Framework :: Django :: 1.11',
'Framework :: Django :: 2.0',
'Framework :: Django :: 2.1',
'Framework :: Django :: 2.2',
'Framework :: Django :: 3.0',
'Framework :: Django :: 3.1',
"Development Status :: 4 - Beta",
"Environment :: Web Environment",
"Intended Audience :: Developers",
"License :: OSI Approved :: MIT License",
"Operating System :: OS Independent",
"Programming Language :: Python",
"Programming Language :: Python :: 2.7",
"Programming Language :: Python :: 3",
"Programming Language :: Python :: 3.5",
"Programming Language :: Python :: 3.6",
"Programming Language :: Python :: 3.7",
"Programming Language :: Python :: 3.8",
"Framework :: Django",
"Framework :: Django :: 1.11",
"Framework :: Django :: 2.0",
"Framework :: Django :: 2.1",
"Framework :: Django :: 2.2",
"Framework :: Django :: 3.0",
"Framework :: Django :: 3.1",
],
)
6 changes: 3 additions & 3 deletions tests/graphql_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@


def create_execution_context(schema, request_string, variables=None):
source = Source(request_string, 'GraphQL request')
source = Source(request_string, "GraphQL request")
document_ast = parse(source)
return ExecutionContext(
schema,
Expand All @@ -35,7 +35,7 @@ def get_field_asts_from_execution_context(exe_context):
type,
exe_context.operation.selection_set,
DefaultOrderedDict(list),
set()
set(),
)
# field_asts = next(iter(fields.values()))
field_asts = tuple(fields.values())[0]
Expand Down Expand Up @@ -69,5 +69,5 @@ def create_resolve_info(schema, request_string, variables=None):
root_value=exe_context.root_value,
operation=exe_context.operation,
variable_values=exe_context.variable_values,
context=context
context=context,
)
14 changes: 9 additions & 5 deletions tests/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,13 @@

class Item(models.Model):
name = models.CharField(max_length=100, blank=True)
parent = models.ForeignKey('Item', on_delete=models.SET_NULL, null=True, related_name='children')
item = models.ForeignKey('Item', on_delete=models.SET_NULL, null=True)
parent = models.ForeignKey(
"Item", on_delete=models.SET_NULL, null=True, related_name="children"
)
item = models.ForeignKey("Item", on_delete=models.SET_NULL, null=True)
value = models.IntegerField(default=10)

item_type = 'simple'
item_type = "simple"

@property
def title(self):
Expand All @@ -32,7 +34,7 @@ class RelatedItem(Item):

class RelatedOneToManyItem(models.Model):
name = models.CharField(max_length=100, blank=True)
item = models.ForeignKey(Item, on_delete=models.PROTECT, related_name='otm_items')
item = models.ForeignKey(Item, on_delete=models.PROTECT, related_name="otm_items")


class ExtraDetailedItem(DetailedItem):
Expand All @@ -49,4 +51,6 @@ class SomeOtherItem(models.Model):

class OtherItem(models.Model):
name = models.CharField(max_length=100, blank=True)
some_other_item = models.ForeignKey('SomeOtherItem', on_delete=models.PROTECT, null=False)
some_other_item = models.ForeignKey(
"SomeOtherItem", on_delete=models.PROTECT, null=False
)
Loading

0 comments on commit 3ca01d4

Please sign in to comment.