Skip to content

Commit 5016de7

Browse files
committed
PEP8 and utils Fixes
1 parent ea3cadd commit 5016de7

File tree

5 files changed

+65
-55
lines changed

5 files changed

+65
-55
lines changed

src/viur/core/db/__init__.py

+5-5
Original file line numberDiff line numberDiff line change
@@ -3,12 +3,12 @@
33
from .errors import *
44
from .query import Query
55
# new exports for 3.8
6-
from .transport import AllocateIDs, Count, Delete, Get, Put, RunInTransaction, allocate_ids, count, delete, get, \
7-
is_in_transaction, put, run_in_transaction
6+
from .transport import (AllocateIDs, Count, Delete, Get, Put, RunInTransaction, allocate_ids, count, delete, get, put,
7+
run_in_transaction)
88
from .types import (DATASTORE_BASE_TYPES, Entity, KEY_SPECIAL_PROPERTY, Key, QueryDefinition, SortOrder,
99
currentDbAccessLog)
10-
from .utils import (GetOrInsert, IsInTransaction, acquireTransactionSuccessMarker, encodeKey, endDataAccessLog,
11-
fixUnindexableProperties, keyHelper, normalizeKey, startDataAccessLog)
10+
from .utils import (GetOrInsert, IsInTransaction, is_in_transaction, acquireTransactionSuccessMarker, encodeKey,
11+
endDataAccessLog, fix_unindexable_properties, keyHelper, normalizeKey, startDataAccessLog)
1212

1313
__all__ = [
1414
"KEY_SPECIAL_PROPERTY",
@@ -18,7 +18,7 @@
1818
"QueryDefinition",
1919
"Key",
2020
"Query",
21-
"fixUnindexableProperties",
21+
"fix_unindexable_properties",
2222
"normalizeKey",
2323
"keyHelper",
2424
"Get",

src/viur/core/db/query.py

+18-19
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@
77
import typing as t
88

99
from .config import conf
10-
from .transport import Count, Get, runSingleFilter
10+
from .transport import Count, Get, run_single_filter
1111
from .types import (
1212
DATASTORE_BASE_TYPES,
1313
Entity,
@@ -17,7 +17,7 @@
1717
TFilters,
1818
TOrders,
1919
)
20-
from .utils import IsInTransaction
20+
from . import utils
2121

2222
if t.TYPE_CHECKING:
2323
from viur.core.skeleton import SkeletonInstance, SkelList
@@ -444,39 +444,38 @@ def getKind(self) -> str:
444444
"""
445445
return self.kind
446446

447-
def _runSingleFilterQuery(self, query: QueryDefinition, limit: int) -> t.List[Entity]:
447+
def _run_single_filter_query(self, query: QueryDefinition, limit: int) -> t.List[Entity]:
448448
"""
449449
Internal helper function that runs a single query definition on the datastore and returns a list of
450450
entities found.
451451
:param query: The querydefinition (filters, orders, distinct etc.) to run against the datastore
452452
:param limit: How many results should at most be returned
453453
:return: The first *limit* entities that matches this query
454454
"""
455-
return runSingleFilter(query, limit)
455+
return run_single_filter(query, limit)
456456

457-
def _mergeMultiQueryResults(self, inputRes: t.List[t.List[Entity]]) -> t.List[Entity]:
457+
def _merge_multi_query_results(self, input_result: t.List[t.List[Entity]]) -> t.List[Entity]:
458458
"""
459459
Merge the lists of entries into a single list; removing duplicates and restoring sort-order
460-
:param inputRes: Nested Lists of Entries returned by each individual query run
460+
:param input_result: Nested Lists of Entries returned by each individual query run
461461
:return: Sorted & deduplicated list of entries
462462
"""
463-
seenKeys = set()
463+
seen_keys = set()
464464
res = []
465-
for subList in inputRes:
465+
for subList in input_result:
466466
for entry in subList:
467467
key = entry.key
468-
if key in seenKeys:
468+
if key in seen_keys:
469469
continue
470-
seenKeys.add(key)
470+
seen_keys.add(key)
471471
res.append(entry)
472472
# FIXME: What about filters that mix different inequality filters?
473473
# Currently, we'll now simply ignore any implicit sortorder.
474-
return self._resortResult(res, {}, self.queries[0].orders)
474+
return self._resort_result(res, {}, self.queries[0].orders)
475475

476-
def _resortResult(
476+
def _resort_result(
477477
self,
478-
entities:
479-
t.List[Entity],
478+
entities: t.List[Entity],
480479
filters: t.Dict[str, DATASTORE_BASE_TYPES],
481480
orders: t.List[t.Tuple[str, SortOrder]],
482481
) -> t.List[Entity]:
@@ -578,7 +577,7 @@ def run(self, limit: int = -1) -> t.List[Entity]:
578577
return []
579578

580579
if self._fulltextQueryString:
581-
if IsInTransaction():
580+
if utils.is_in_transaction():
582581
raise ValueError("Can't run fulltextSearch inside transactions!") # InvalidStateError FIXME!
583582
qryStr = self._fulltextQueryString
584583
self._fulltextQueryString = None # Reset, so the adapter can still work with this query
@@ -596,17 +595,17 @@ def run(self, limit: int = -1) -> t.List[Entity]:
596595
res = []
597596
# We run all queries first (preventing multiple round-trips to the server)
598597
for singleQuery in self.queries:
599-
res.append(self._runSingleFilterQuery(singleQuery, limit if limit != -1 else singleQuery.limit))
598+
res.append(self._run_single_filter_query(singleQuery, limit if limit != -1 else singleQuery.limit))
600599
# Wait for the actual results to arrive and convert the protobuffs to Entries
601600
res = [self._fixKind(x) for x in res]
602601
if self._customMultiQueryMerge:
603602
# We have a custom merge function, use that
604603
res = self._customMultiQueryMerge(self, res, limit if limit != -1 else self.queries[0].limit)
605604
else:
606605
# We must merge (and sort) the results ourself
607-
res = self._mergeMultiQueryResults(res)
606+
res = self._merge_multi_query_results(res)
608607
else: # We have just one single query
609-
res = self._fixKind(self._runSingleFilterQuery(self.queries, limit if limit != -1 else self.queries.limit))
608+
res = self._fixKind(self._run_single_filter_query(self.queries, limit if limit != -1 else self.queries.limit))
610609
if res:
611610
self._lastEntry = res[-1]
612611
return res
@@ -688,7 +687,7 @@ def iter(self) -> t.Iterator[Entity]:
688687
elif isinstance(self.queries, list):
689688
raise ValueError("No iter on Multiqueries")
690689
while True:
691-
qryRes = self._runSingleFilterQuery(self.queries, 20)
690+
qryRes = self._run_single_filter_query(self.queries, 20)
692691
yield from qryRes
693692
if not self.queries.currentCursor: # We reached the end of that query
694693
break

src/viur/core/db/transport.py

+14-11
Original file line numberDiff line numberDiff line change
@@ -104,12 +104,9 @@ def Delete(keys: t.Union[Entity, t.List[Entity], Key, t.List[Key]]):
104104
return delete(keys)
105105

106106

107-
def is_in_transaction() -> bool:
108-
return __client__.current_transaction is not None
109-
110-
111-
@deprecated(version="3.8.0", reason="Use 'db.is_in_transaction' instead")
107+
@deprecated(version="3.8.0", reason="Use 'db.utils.is_in_transaction' instead")
112108
def IsInTransaction() -> bool:
109+
from .utils import is_in_transaction # noqa: E402 # import works only here because circular imports
113110
return is_in_transaction()
114111

115112

@@ -167,14 +164,15 @@ def Count(kind: str = None, up_to=2 ** 31 - 1, queryDefinition: QueryDefinition
167164
return count(kind, up_to, queryDefinition)
168165

169166

170-
def runSingleFilter(query: QueryDefinition, limit: int) -> t.List[Entity]:
167+
def run_single_filter(query: QueryDefinition, limit: int) -> t.List[Entity]:
171168
"""
172-
Internal helper function that runs a single query definition on the datastore and returns a list of
173-
entities found.
174-
:param query: The querydefinition (filters, orders, distinct etc.) to run against the datastore
175-
:param limit: How many results should at most be returned
176-
:return: The first *limit* entities that matches this query
169+
Internal helper function that runs a single query definition on the datastore and returns a list of
170+
entities found.
171+
:param query: The querydefinition (filters, orders, distinct etc.) to run against the datastore
172+
:param limit: How many results should at most be returned
173+
:return: The first *limit* entities that matches this query
177174
"""
175+
178176
qry = __client__.query(kind=query.kind)
179177
startCursor = None
180178
endCursor = None
@@ -217,4 +215,9 @@ def runSingleFilter(query: QueryDefinition, limit: int) -> t.List[Entity]:
217215
return res
218216

219217

218+
@deprecated(version="3.8.0", reason="Use 'run_single_filter' instead")
219+
def runSingleFilter(query: QueryDefinition, limit: int) -> t.List[Entity]:
220+
run_single_filter(query, limit)
221+
222+
220223
__all__ = [AllocateIDs, Delete, Get, Put, RunInTransaction, Count]

src/viur/core/db/utils.py

+27-19
Original file line numberDiff line numberDiff line change
@@ -1,41 +1,44 @@
11
import datetime
2+
from deprecated.sphinx import deprecated
23
import typing as t
34

45
from .transport import Get, Put, RunInTransaction
56
from .types import Entity, Key, currentDbAccessLog, currentTransaction
67

78

8-
def fixUnindexableProperties(entry: Entity) -> Entity:
9+
def fix_unindexable_properties(entry: Entity) -> Entity:
910
"""
1011
Recursively walk the given Entity and add all properties to the list of unindexed properties if they contain
11-
a string longer than 500 bytes (which is maximum size of a string that can be indexed). The datastore would
12+
a string longer than 1500 bytes (which is maximum size of a string that can be indexed). The datastore would
1213
return an error otherwise.
14+
https://cloud.google.com/datastore/docs/concepts/limits?hl=en#limits
1315
:param entry: The entity to fix (inplace)
1416
:return: The fixed entity
1517
"""
1618

17-
def hasUnindexableProperty(prop):
19+
def has_unindexable_property(prop):
1820
if isinstance(prop, dict):
19-
return any([hasUnindexableProperty(x) for x in prop.values()])
21+
return any([has_unindexable_property(x) for x in prop.values()])
2022
elif isinstance(prop, list):
21-
return any([hasUnindexableProperty(x) for x in prop])
23+
return any([has_unindexable_property(x) for x in prop])
2224
elif isinstance(prop, (str, bytes)):
23-
return len(prop) >= 500
25+
return len(prop) >= 1500
2426
else:
2527
return False
2628

27-
resList = set()
28-
for k, v in entry.items():
29-
if hasUnindexableProperty(v):
30-
if isinstance(v, dict):
31-
innerEntry = Entity()
32-
innerEntry.update(v)
33-
entry[k] = fixUnindexableProperties(innerEntry)
34-
if isinstance(v, Entity):
35-
innerEntry.key = v.key
36-
else:
37-
resList.add(k)
38-
entry.exclude_from_indexes = resList
29+
unindexable_properties = set()
30+
for key, value in entry.items():
31+
if not has_unindexable_property(value):
32+
continue
33+
if isinstance(value, dict):
34+
inner_entity = Entity()
35+
inner_entity.update(value)
36+
entry[key] = fix_unindexable_properties(inner_entity)
37+
if isinstance(value, Entity):
38+
inner_entity.key = value.key
39+
else:
40+
unindexable_properties.add(key)
41+
entry.exclude_from_indexes = unindexable_properties
3942
return entry
4043

4144

@@ -94,10 +97,15 @@ def keyHelper(
9497
raise NotImplementedError(f"Unsupported key type {type(inKey)}")
9598

9699

97-
def IsInTransaction() -> bool:
100+
def is_in_transaction() -> bool:
98101
return currentTransaction.get() is not None
99102

100103

104+
@deprecated(version="3.8.0", reason="Use 'db.utils.is_in_transaction' instead")
105+
def IsInTransaction() -> bool:
106+
return is_in_transaction()
107+
108+
101109
def GetOrInsert(key: Key, **kwargs) -> Entity:
102110
"""
103111
Either creates a new entity with the given key, or returns the existing one.

src/viur/core/session.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -121,7 +121,7 @@ def save(self):
121121

122122
dbSession = db.Entity(db.Key(self.kindName, self.cookie_key))
123123

124-
dbSession["data"] = db.fixUnindexableProperties(self)
124+
dbSession["data"] = db.fix_unindexable_properties(self)
125125
dbSession["static_security_key"] = self.static_security_key
126126
dbSession["lastseen"] = time.time()
127127
dbSession["user"] = str(user_key) # allow filtering for users

0 commit comments

Comments
 (0)