Skip to content

Commit b207d51

Browse files
committed
Rename Methods
1 parent d52f391 commit b207d51

21 files changed

+128
-128
lines changed

src/viur/core/__init__.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -288,14 +288,14 @@ def setup(modules: ModuleType | object, render: ModuleType | object = None, de
288288
if conf.file_hmac_key is None:
289289
from viur.core import db
290290
key = db.Key("viur-conf", "viur-conf")
291-
if not (obj := db.Get(key)): # create a new "viur-conf"?
291+
if not (obj := db.get(key)): # create a new "viur-conf"?
292292
logging.info("Creating new viur-conf")
293293
obj = db.Entity(key)
294294

295295
if "hmacKey" not in obj: # create a new hmacKey
296296
logging.info("Creating new hmacKey")
297297
obj["hmacKey"] = utils.string.random(length=20)
298-
db.Put(obj)
298+
db.put(obj)
299299

300300
conf.file_hmac_key = bytes(obj["hmacKey"], "utf-8")
301301

src/viur/core/bones/base.py

+4-4
Original file line numberDiff line numberDiff line change
@@ -1054,7 +1054,7 @@ def unserialize_compute(self, skel: "SkeletonInstance", name: str) -> bool:
10541054
from viur.core.skeleton import RefSkel # noqa: E402 # import works only here because circular imports
10551055

10561056
if issubclass(skel.skeletonCls, RefSkel): # we have a ref skel we must load the complete Entity
1057-
db_obj = db.Get(skel["key"])
1057+
db_obj = db.get(skel["key"])
10581058
last_update = db_obj.get(f"_viur_compute_{name}_")
10591059
else:
10601060
last_update = skel.dbEntity.get(f"_viur_compute_{name}_")
@@ -1064,15 +1064,15 @@ def unserialize_compute(self, skel: "SkeletonInstance", name: str) -> bool:
10641064
# if so, recompute and refresh updated value
10651065
skel.accessedValues[name] = value = self._compute(skel, name)
10661066
def transact():
1067-
db_obj = db.Get(skel["key"])
1067+
db_obj = db.get(skel["key"])
10681068
db_obj[f"_viur_compute_{name}_"] = now
10691069
db_obj[name] = value
1070-
db.Put(db_obj)
1070+
db.put(db_obj)
10711071

10721072
if db.IsInTransaction():
10731073
transact()
10741074
else:
1075-
db.RunInTransaction(transact)
1075+
db.run_in_transaction(transact)
10761076

10771077
return True
10781078

src/viur/core/bones/file.py

+4-4
Original file line numberDiff line numberDiff line change
@@ -67,7 +67,7 @@ def ensureDerived(key: db.Key, srcKey, deriveMap: dict[str, t.Any], refreshKey:
6767
}
6868

6969
def updateTxn(key, resDict):
70-
obj = db.Get(key)
70+
obj = db.get(key)
7171
if not obj: # File-object got deleted during building of our derives
7272
return
7373
obj["derived"] = obj.get("derived") or {}
@@ -77,10 +77,10 @@ def updateTxn(key, resDict):
7777
obj["derived"]["deriveStatus"][k] = v["version"]
7878
for fileName, fileDict in v["files"].items():
7979
obj["derived"]["files"][fileName] = fileDict
80-
db.Put(obj)
80+
db.put(obj)
8181

8282
if resDict: # Write updated results back and queue updateRelationsTask
83-
db.RunInTransaction(updateTxn, key, resDict)
83+
db.run_in_transaction(updateTxn, key, resDict)
8484
# Queue that updateRelations call at least 30 seconds into the future, so that other ensureDerived calls from
8585
# the same FileBone have the chance to finish, otherwise that updateRelations Task will call postSavedHandler
8686
# on that FileBone again - re-queueing any ensureDerivedCalls that have not finished yet.
@@ -93,7 +93,7 @@ def refreshTxn():
9393
skel.refresh()
9494
skel.write(update_relations=False)
9595

96-
db.RunInTransaction(refreshTxn)
96+
db.run_in_transaction(refreshTxn)
9797

9898

9999
class FileBone(TreeLeafBone):

src/viur/core/bones/key.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -65,7 +65,7 @@ def singleValueFromClient(self, value, skel=None, bone_name=None, client_data=No
6565
return self.getEmptyValue(), [ReadFromClientError(ReadFromClientErrorSeverity.Invalid, err)]
6666

6767
if self.check:
68-
if db.Get(key) is None:
68+
if db.get(key) is None:
6969
return self.getEmptyValue(), [
7070
ReadFromClientError(
7171
ReadFromClientErrorSeverity.Invalid,

src/viur/core/bones/relational.py

+9-9
Original file line numberDiff line numberDiff line change
@@ -136,7 +136,7 @@ class RelationalBone(BaseBone):
136136
- RelationalConsistency.PreventDeletion
137137
Will prevent deleting the referenced entity as long as it's selected in this bone (calling
138138
skel.delete() on the referenced entity will raise errors.Locked). It's still (technically)
139-
possible to remove the underlying datastore entity using db.Delete manually, but this *must not*
139+
possible to remove the underlying datastore entity using db.delete manually, but this *must not*
140140
be used on a skeleton object as it will leave a whole bunch of references in a stale state.
141141
142142
- RelationalConsistency.SetNull
@@ -228,7 +228,7 @@ def __init__(
228228
:param RelationalConsistency.PreventDeletion:
229229
Will prevent deleting the referenced entity as long as it's
230230
selected in this bone (calling skel.delete() on the referenced entity will raise errors.Locked).
231-
It's still (technically) possible to remove the underlying datastore entity using db.Delete
231+
It's still (technically) possible to remove the underlying datastore entity using db.delete
232232
manually, but this *must not* be used on a skeleton object as it will leave a whole bunch of
233233
references in a stale state.
234234
@@ -521,10 +521,10 @@ def postSavedHandler(self, skel, boneName, key) -> None:
521521
for dbObj in dbVals.iter():
522522
try:
523523
if not dbObj["dest"].key in [x["dest"]["key"] for x in values]: # Relation has been removed
524-
db.Delete(dbObj.key)
524+
db.delete(dbObj.key)
525525
continue
526526
except: # This entry is corrupt
527-
db.Delete(dbObj.key)
527+
db.delete(dbObj.key)
528528
else: # Relation: Updated
529529
data = [x for x in values if x["dest"]["key"] == dbObj["dest"].key][0]
530530
# Write our (updated) values in
@@ -539,7 +539,7 @@ def postSavedHandler(self, skel, boneName, key) -> None:
539539
dbObj["viur_relational_consistency"] = self.consistency.value
540540
dbObj["viur_foreign_keys"] = list(self.refKeys)
541541
dbObj["viurTags"] = srcEntity.get("viurTags") # Copy tags over so we can still use our searchengine
542-
db.Put(dbObj)
542+
db.put(dbObj)
543543
values.remove(data)
544544
# Add any new Relation
545545
for val in values:
@@ -557,7 +557,7 @@ def postSavedHandler(self, skel, boneName, key) -> None:
557557
dbObj["viur_relational_updateLevel"] = self.updateLevel.value
558558
dbObj["viur_relational_consistency"] = self.consistency.value
559559
dbObj["viur_foreign_keys"] = list(self._ref_keys)
560-
db.Put(dbObj)
560+
db.put(dbObj)
561561

562562
def postDeletedHandler(self, skel: "SkeletonInstance", boneName: str, key: db.Key) -> None:
563563
"""
@@ -575,7 +575,7 @@ def postDeletedHandler(self, skel: "SkeletonInstance", boneName: str, key: db.Ke
575575
query.filter("viur_dest_kind =", self.kind)
576576
query.filter("viur_src_property =", boneName)
577577
query.filter("src.__key__ =", key)
578-
db.Delete([entity for entity in query.run()])
578+
db.delete([entity for entity in query.run()])
579579

580580
def isInvalid(self, key) -> None:
581581
"""
@@ -613,7 +613,7 @@ def restoreSkels(key, usingData, index=None):
613613
errors = []
614614
try:
615615
dbKey = db.keyHelper(key, self.kind)
616-
entry = db.Get(dbKey)
616+
entry = db.get(dbKey)
617617
assert entry
618618
except: # Invalid key or something like that
619619
logging.info(f"Invalid reference key >{key}< detected on bone '{bone_name}'")
@@ -1091,7 +1091,7 @@ def relskels_from_keys(self, key_rel_list: list[tuple[db.Key, dict | None]]) ->
10911091
:return: A dictionary containing a reference skeleton and optional relation data.
10921092
"""
10931093

1094-
if not all(db_objs := db.Get([db.keyHelper(value[0], self.kind) for value in key_rel_list])):
1094+
if not all(db_objs := db.get([db.keyHelper(value[0], self.kind) for value in key_rel_list])):
10951095
return [] # return emtpy data when not all data is found
10961096
res_rel_skels = []
10971097
for (key, rel), db_obj in zip(key_rel_list, db_objs):

src/viur/core/bones/uid.py

+3-3
Original file line numberDiff line numberDiff line change
@@ -12,12 +12,12 @@ def generate_number(db_key: db.Key) -> int:
1212
def transact(_key: db.Key):
1313
for i in range(3):
1414
try:
15-
if db_obj := db.Get(_key):
15+
if db_obj := db.get(_key):
1616
db_obj["count"] += 1
1717
else:
1818
db_obj = db.Entity(_key)
1919
db_obj["count"] = 0
20-
db.Put(db_obj)
20+
db.put(db_obj)
2121
break
2222
except db.CollisionError: # recall the function
2323
time.sleep(i + 1)
@@ -28,7 +28,7 @@ def transact(_key: db.Key):
2828
if db.IsInTransaction():
2929
return transact(db_key)
3030
else:
31-
return db.RunInTransaction(transact, db_key)
31+
return db.run_in_transaction(transact, db_key)
3232

3333

3434
def generate_uid(skel, bone):

src/viur/core/cache.py

+8-8
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,7 @@
1717
http Header along with their requests. Entities in this cache will expire if
1818
- Their TTL is exceeded
1919
- They're explicitly removed from the cache by calling :meth:`viur.core.cache.flushCache` using their path
20-
- A Datastore entity that has been accessed using db.Get() from within the cached function has been modified
20+
- A Datastore entity that has been accessed using db.get() from within the cached function has been modified
2121
- The wrapped function has run a query over a kind in which an entity has been added/edited/deleted
2222
2323
..Warning: As this cache is intended to be used with exposed functions, it will not only store the result of the
@@ -142,7 +142,7 @@ def wrapF(self, *args, **kwargs) -> str | bytes:
142142
# Something is wrong (possibly the parameter-count)
143143
# Let's call f, but we knew already that this will clash
144144
return f(self, *args, **kwargs)
145-
dbRes = db.Get(db.Key(viurCacheName, key))
145+
dbRes = db.get(db.Key(viurCacheName, key))
146146
if dbRes is not None:
147147
if (
148148
not maxCacheTime or dbRes["creationtime"] > utils.utcNow()
@@ -165,7 +165,7 @@ def wrapF(self, *args, **kwargs) -> str | bytes:
165165
dbEntity["content-type"] = currReq.response.headers['Content-Type']
166166
dbEntity["accessedEntries"] = list(accessedEntries)
167167
dbEntity.exclude_from_indexes = {"data", "content-type"} # save two DB-writes.
168-
db.Put(dbEntity)
168+
db.put(dbEntity)
169169
logging.debug("This request was a cache-miss. Cache has been updated.")
170170
return res
171171

@@ -234,31 +234,31 @@ def flushCache(prefix: str = None, key: db.Key | None = None, kind: str | None
234234
if prefix is not None:
235235
items = db.Query(viurCacheName).filter("path =", prefix.rstrip("*")).iter()
236236
for item in items:
237-
db.Delete(item)
237+
db.delete(item)
238238
if prefix.endswith("*"):
239239
items = db.Query(viurCacheName) \
240240
.filter("path >", prefix.rstrip("*")) \
241241
.filter("path <", prefix.rstrip("*") + u"\ufffd") \
242242
.iter()
243243
for item in items:
244-
db.Delete(item)
244+
db.delete(item)
245245
logging.debug(f"Flushing cache succeeded. Everything matching {prefix=} is gone.")
246246
if key is not None:
247247
items = db.Query(viurCacheName).filter("accessedEntries =", key).iter()
248248
for item in items:
249249
logging.info(f"""Deleted cache entry {item["path"]!r}""")
250-
db.Delete(item.key)
250+
db.delete(item.key)
251251
if not isinstance(key, db.Key):
252252
key = db.Key.from_legacy_urlsafe(key) # hopefully is a string
253253
items = db.Query(viurCacheName).filter("accessedEntries =", key.kind).iter()
254254
for item in items:
255255
logging.info(f"""Deleted cache entry {item["path"]!r}""")
256-
db.Delete(item.key)
256+
db.delete(item.key)
257257
if kind is not None:
258258
items = db.Query(viurCacheName).filter("accessedEntries =", kind).iter()
259259
for item in items:
260260
logging.info(f"""Deleted cache entry {item["path"]!r}""")
261-
db.Delete(item.key)
261+
db.delete(item.key)
262262

263263

264264
__all__ = ["enableCache", "flushCache"]

src/viur/core/db/query.py

+10-10
Original file line numberDiff line numberDiff line change
@@ -380,6 +380,7 @@ def limit(self, limit: int) -> t.Self:
380380
:param limit: The maximum number of entities.
381381
:returns: Returns the query itself for chaining.
382382
"""
383+
# TODO Add a check for the limit (<=100) ?
383384
if isinstance(self.queries, QueryDefinition):
384385
self.queries.limit = limit
385386
elif isinstance(self.queries, list):
@@ -657,14 +658,14 @@ def fetch(self, limit: int = -1) -> "SkelList['SkeletonInstance']" | None:
657658
logging.error(("Limit", limit))
658659
raise NotImplementedError(
659660
"This query is not limited! You must specify an upper bound using limit() between 1 and 100")
660-
dbRes = self.run(limit)
661-
if dbRes is None:
661+
662+
if not (db_res := self.run(limit)):
662663
return None
663664
res = SkelList(self.srcSkel)
664-
for e in dbRes:
665-
skelInstance = SkeletonInstance(self.srcSkel.skeletonCls, bone_map=self.srcSkel.boneMap)
666-
skelInstance.dbEntity = e
667-
res.append(skelInstance)
665+
for e in db_res:
666+
skel_instance = SkeletonInstance(self.srcSkel.skeletonCls, bone_map=self.srcSkel.boneMap)
667+
skel_instance.dbEntity = e
668+
res.append(skel_instance)
668669
res.getCursor = lambda: self.getCursor()
669670
res.get_orders = lambda: self.get_orders()
670671
return res
@@ -688,8 +689,7 @@ def iter(self) -> t.Iterator[Entity]:
688689
elif isinstance(self.queries, list):
689690
raise ValueError("No iter on Multiqueries")
690691
while True:
691-
qryRes = self._run_single_filter_query(self.queries, 20)
692-
yield from qryRes
692+
yield from self._run_single_filter_query(self.queries, 100)
693693
if not self.queries.currentCursor: # We reached the end of that query
694694
break
695695
self.queries.startCursor = self.queries.currentCursor
@@ -718,8 +718,8 @@ def getSkel(self) -> t.Optional["SkeletonInstance"]:
718718
"""
719719
if self.srcSkel is None:
720720
raise NotImplementedError("This query has not been created using skel.all()")
721-
res = self.getEntry()
722-
if res is None:
721+
722+
if not (res:= self.getEntry()):
723723
return None
724724
self.srcSkel.setEntity(res)
725725
return self.srcSkel

src/viur/core/db/utils.py

+7-7
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22
from deprecated.sphinx import deprecated
33
import typing as t
44

5-
from .transport import Get, Put, RunInTransaction
5+
from .transport import get, put, run_in_transaction
66
from .types import Entity, Key, currentDbAccessLog, currentTransaction
77

88

@@ -110,7 +110,7 @@ def GetOrInsert(key: Key, **kwargs) -> Entity:
110110
"""
111111
Either creates a new entity with the given key, or returns the existing one.
112112
113-
Its guaranteed that there is no race-condition here; it will never overwrite an
113+
Its guaranteed that there is no race-condition here; it will never overwrite a
114114
previously created entity. Extra keyword arguments passed to this function will be
115115
used to populate the entity if it has to be created; otherwise they are ignored.
116116
@@ -119,17 +119,17 @@ def GetOrInsert(key: Key, **kwargs) -> Entity:
119119
"""
120120

121121
def txn(key, kwargs):
122-
obj = Get(key)
122+
obj = get(key)
123123
if not obj:
124124
obj = Entity(key)
125125
for k, v in kwargs.items():
126126
obj[k] = v
127-
Put(obj)
127+
put(obj)
128128
return obj
129129

130-
if IsInTransaction():
130+
if is_in_transaction():
131131
return txn(key, kwargs)
132-
return RunInTransaction(txn, key, kwargs)
132+
return run_in_transaction(txn, key, kwargs)
133133

134134

135135
def encodeKey(key: Key) -> str:
@@ -153,7 +153,7 @@ def acquireTransactionSuccessMarker() -> str:
153153
if "viurTxnMarkerSet" not in txn:
154154
e = Entity(Key("viur-transactionmarker", marker))
155155
e["creationdate"] = datetime.datetime.utcnow()
156-
Put(e)
156+
put(e)
157157
txn["viurTxnMarkerSet"] = True
158158
return marker
159159

0 commit comments

Comments
 (0)