Ran black on branc

This commit is contained in:
Griatch 2019-12-16 20:31:42 +01:00
parent 6effb6f456
commit 4ea6209123
230 changed files with 7108 additions and 2395 deletions

View file

@ -126,7 +126,9 @@ class TagFormSet(forms.BaseInlineFormSet):
handler.remove(obj.tag_key, category=obj.tag_category)
for instance in instances:
handler = get_handler(instance)
handler.add(instance.tag_key, category=instance.tag_category, data=instance.tag_data)
handler.add(
instance.tag_key, category=instance.tag_category, data=instance.tag_data
)
class TagInline(admin.TabularInline):
@ -142,7 +144,9 @@ class TagInline(admin.TabularInline):
model = None
form = TagForm
formset = TagFormSet
related_field = None # Must be 'objectdb', 'accountdb', 'msg', etc. Set when subclassing
related_field = (
None
) # Must be 'objectdb', 'accountdb', 'msg', etc. Set when subclassing
# raw_id_fields = ('tag',)
# readonly_fields = ('tag',)
extra = 0
@ -177,9 +181,14 @@ class AttributeForm(forms.ModelForm):
label="Attribute Name", required=False, initial="Enter Attribute Name Here"
)
attr_category = forms.CharField(
label="Category", help_text="type of attribute, for sorting", required=False, max_length=128
label="Category",
help_text="type of attribute, for sorting",
required=False,
max_length=128,
)
attr_value = PickledFormField(
label="Value", help_text="Value to pickle/save", required=False
)
attr_value = PickledFormField(label="Value", help_text="Value to pickle/save", required=False)
attr_type = forms.CharField(
label="Type",
help_text='Internal use. Either unset (normal Attribute) or "nick"',
@ -194,7 +203,13 @@ class AttributeForm(forms.ModelForm):
)
class Meta:
fields = ("attr_key", "attr_value", "attr_category", "attr_lockstring", "attr_type")
fields = (
"attr_key",
"attr_value",
"attr_category",
"attr_lockstring",
"attr_type",
)
def __init__(self, *args, **kwargs):
"""
@ -242,7 +257,9 @@ class AttributeForm(forms.ModelForm):
"""
# we are spoofing an Attribute for the Handler that will be called
instance = self.instance
instance.attr_key = self.cleaned_data["attr_key"] or "no_name_entered_for_attribute"
instance.attr_key = (
self.cleaned_data["attr_key"] or "no_name_entered_for_attribute"
)
instance.attr_category = self.cleaned_data["attr_category"] or None
instance.attr_value = self.cleaned_data["attr_value"]
# convert the serialized string value into an object, if necessary, for AttributeHandler
@ -320,7 +337,9 @@ class AttributeInline(admin.TabularInline):
model = None
form = AttributeForm
formset = AttributeFormSet
related_field = None # Must be 'objectdb', 'accountdb', 'msg', etc. Set when subclassing
related_field = (
None
) # Must be 'objectdb', 'accountdb', 'msg', etc. Set when subclassing
# raw_id_fields = ('attribute',)
# readonly_fields = ('attribute',)
extra = 0

View file

@ -70,7 +70,10 @@ class Attribute(SharedMemoryModel):
"cannot be edited through the admin interface.",
)
db_strvalue = models.TextField(
"strvalue", null=True, blank=True, help_text="String-specific storage for quick look-up"
"strvalue",
null=True,
blank=True,
help_text="String-specific storage for quick look-up",
)
db_category = models.CharField(
"category",
@ -104,7 +107,9 @@ class Attribute(SharedMemoryModel):
help_text="Subclass of Attribute (None or nick)",
)
# time stamp
db_date_created = models.DateTimeField("date_created", editable=False, auto_now_add=True)
db_date_created = models.DateTimeField(
"date_created", editable=False, auto_now_add=True
)
# Database manager
# objects = managers.AttributeManager()
@ -204,7 +209,9 @@ class Attribute(SharedMemoryModel):
result (bool): If the lock was passed or not.
"""
result = self.locks.check(accessing_obj, access_type=access_type, default=default)
result = self.locks.check(
accessing_obj, access_type=access_type, default=default
)
return result
@ -237,7 +244,8 @@ class AttributeHandler(object):
def _fullcache(self):
"""Cache all attributes of this object"""
if not _TYPECLASS_AGGRESSIVE_CACHE: return
if not _TYPECLASS_AGGRESSIVE_CACHE:
return
query = {
"%s__id" % self._model: self._objid,
"attribute__db_model__iexact": self._model,
@ -245,7 +253,9 @@ class AttributeHandler(object):
}
attrs = [
conn.attribute
for conn in getattr(self.obj, self._m2m_fieldname).through.objects.filter(**query)
for conn in getattr(self.obj, self._m2m_fieldname).through.objects.filter(
**query
)
]
self._cache = dict(
(
@ -310,14 +320,18 @@ class AttributeHandler(object):
"attribute__db_model__iexact": self._model,
"attribute__db_attrtype": self._attrtype,
"attribute__db_key__iexact": key.lower(),
"attribute__db_category__iexact": category.lower() if category else None,
"attribute__db_category__iexact": category.lower()
if category
else None,
}
if not self.obj.pk:
return []
conn = getattr(self.obj, self._m2m_fieldname).through.objects.filter(**query)
conn = getattr(self.obj, self._m2m_fieldname).through.objects.filter(
**query
)
if conn:
attr = conn[0].attribute
if _TYPECLASS_AGGRESSIVE_CACHE:
if _TYPECLASS_AGGRESSIVE_CACHE:
self._cache[cachekey] = attr
return [attr] if attr.pk else []
else:
@ -333,20 +347,26 @@ class AttributeHandler(object):
# for this category before
catkey = "-%s" % category
if _TYPECLASS_AGGRESSIVE_CACHE and catkey in self._catcache:
return [attr for key, attr in self._cache.items() if key.endswith(catkey) and attr]
return [
attr
for key, attr in self._cache.items()
if key.endswith(catkey) and attr
]
else:
# we have to query to make this category up-date in the cache
query = {
"%s__id" % self._model: self._objid,
"attribute__db_model__iexact": self._model,
"attribute__db_attrtype": self._attrtype,
"attribute__db_category__iexact": category.lower() if category else None,
"attribute__db_category__iexact": category.lower()
if category
else None,
}
attrs = [
conn.attribute
for conn in getattr(self.obj, self._m2m_fieldname).through.objects.filter(
**query
)
for conn in getattr(
self.obj, self._m2m_fieldname
).through.objects.filter(**query)
]
if _TYPECLASS_AGGRESSIVE_CACHE:
for attr in attrs:
@ -367,7 +387,8 @@ class AttributeHandler(object):
attr_obj (Attribute): The newly saved attribute
"""
if not _TYPECLASS_AGGRESSIVE_CACHE: return
if not _TYPECLASS_AGGRESSIVE_CACHE:
return
if not key: # don't allow an empty key in cache
return
cachekey = "%s-%s" % (key, category)
@ -616,11 +637,15 @@ class AttributeHandler(object):
strattr = kwargs.get("strattr", False)
for tup in args:
if not is_iter(tup) or len(tup) < 2:
raise RuntimeError("batch_add requires iterables as arguments (got %r)." % tup)
raise RuntimeError(
"batch_add requires iterables as arguments (got %r)." % tup
)
ntup = len(tup)
keystr = str(tup[0]).strip().lower()
new_value = tup[1]
category = str(tup[2]).strip().lower() if ntup > 2 and tup[2] is not None else None
category = (
str(tup[2]).strip().lower() if ntup > 2 and tup[2] is not None else None
)
lockstring = tup[3] if ntup > 3 else ""
attr_objs = self._getcache(keystr, category)
@ -695,7 +720,9 @@ class AttributeHandler(object):
if key is None:
self.clear(
category=category, accessing_obj=accessing_obj, default_access=default_access
category=category,
accessing_obj=accessing_obj,
default_access=default_access,
)
return
@ -708,7 +735,9 @@ class AttributeHandler(object):
for attr_obj in attr_objs:
if not (
accessing_obj
and not attr_obj.access(accessing_obj, self._attredit, default=default_access)
and not attr_obj.access(
accessing_obj, self._attredit, default=default_access
)
):
try:
attr_obj.delete()
@ -749,7 +778,8 @@ class AttributeHandler(object):
[
attr.delete()
for attr in attrs
if attr and attr.access(accessing_obj, self._attredit, default=default_access)
if attr
and attr.access(accessing_obj, self._attredit, default=default_access)
]
else:
[attr.delete() for attr in attrs if attr and attr.pk]
@ -776,7 +806,9 @@ class AttributeHandler(object):
"""
if not self._cache_complete:
self._fullcache()
attrs = sorted([attr for attr in self._cache.values() if attr], key=lambda o: o.id)
attrs = sorted(
[attr for attr in self._cache.values() if attr], key=lambda o: o.id
)
if accessing_obj:
return [
attr
@ -855,14 +887,20 @@ def initialize_nick_templates(in_template, out_template):
# validate the templates
regex_args = [match.group(2) for match in _RE_NICK_ARG.finditer(regex_string)]
temp_args = [match.group(2) for match in _RE_NICK_TEMPLATE_ARG.finditer(out_template)]
temp_args = [
match.group(2) for match in _RE_NICK_TEMPLATE_ARG.finditer(out_template)
]
if set(regex_args) != set(temp_args):
# We don't have the same $-tags in input/output.
raise NickTemplateInvalid
regex_string = _RE_NICK_SPACE.sub(r"\\s+", regex_string)
regex_string = _RE_NICK_ARG.sub(lambda m: "(?P<arg%s>.+?)" % m.group(2), regex_string)
template_string = _RE_NICK_TEMPLATE_ARG.sub(lambda m: "{arg%s}" % m.group(2), out_template)
regex_string = _RE_NICK_ARG.sub(
lambda m: "(?P<arg%s>.+?)" % m.group(2), regex_string
)
template_string = _RE_NICK_TEMPLATE_ARG.sub(
lambda m: "{arg%s}" % m.group(2), out_template
)
return regex_string, template_string
@ -958,10 +996,17 @@ class NickHandler(AttributeHandler):
"""
if category == "channel":
nick_regex, nick_template = initialize_nick_templates(key + " $1", replacement + " $1")
nick_regex, nick_template = initialize_nick_templates(
key + " $1", replacement + " $1"
)
else:
nick_regex, nick_template = initialize_nick_templates(key, replacement)
super().add(key, (nick_regex, nick_template, key, replacement), category=category, **kwargs)
super().add(
key,
(nick_regex, nick_template, key, replacement),
category=category,
**kwargs
)
def remove(self, key, category="inputline", **kwargs):
"""
@ -977,7 +1022,9 @@ class NickHandler(AttributeHandler):
"""
super().remove(key, category=category, **kwargs)
def nickreplace(self, raw_string, categories=("inputline", "channel"), include_account=True):
def nickreplace(
self, raw_string, categories=("inputline", "channel"), include_account=True
):
"""
Apply nick replacement of entries in raw_string with nick replacement.
@ -1011,7 +1058,9 @@ class NickHandler(AttributeHandler):
{
nick.key: nick
for nick in make_iter(
self.obj.account.nicks.get(category=category, return_obj=True)
self.obj.account.nicks.get(
category=category, return_obj=True
)
)
if nick and nick.key
}
@ -1023,7 +1072,9 @@ class NickHandler(AttributeHandler):
regex = re.compile(nick_regex, re.I + re.DOTALL + re.U)
self._regex_cache[nick_regex] = regex
is_match, raw_string = parse_nick_template(raw_string.strip(), regex, template)
is_match, raw_string = parse_nick_template(
raw_string.strip(), regex, template
)
if is_match:
break
return raw_string
@ -1114,5 +1165,9 @@ class NAttributeHandler(object):
"""
if return_tuples:
return [(key, value) for (key, value) in self._store.items() if not key.startswith("_")]
return [
(key, value)
for (key, value) in self._store.items()
if not key.startswith("_")
]
return [key for key in self._store if not key.startswith("_")]

View file

@ -30,7 +30,13 @@ class TypedObjectManager(idmapper.manager.SharedMemoryManager):
# Attribute manager methods
def get_attribute(
self, key=None, category=None, value=None, strvalue=None, obj=None, attrtype=None
self,
key=None,
category=None,
value=None,
strvalue=None,
obj=None,
attrtype=None,
):
"""
Return Attribute objects by key, by category, by value, by
@ -73,9 +79,9 @@ class TypedObjectManager(idmapper.manager.SharedMemoryManager):
# no reason to make strvalue/value mutually exclusive at this level
query.append(("attribute__db_value", value))
return Attribute.objects.filter(
pk__in=self.model.db_attributes.through.objects.filter(**dict(query)).values_list(
"attribute_id", flat=True
)
pk__in=self.model.db_attributes.through.objects.filter(
**dict(query)
).values_list("attribute_id", flat=True)
)
def get_nick(self, key=None, category=None, value=None, strvalue=None, obj=None):
@ -101,7 +107,9 @@ class TypedObjectManager(idmapper.manager.SharedMemoryManager):
key=key, category=category, value=value, strvalue=strvalue, obj=obj
)
def get_by_attribute(self, key=None, category=None, value=None, strvalue=None, attrtype=None):
def get_by_attribute(
self, key=None, category=None, value=None, strvalue=None, attrtype=None
):
"""
Return objects having attributes with the given key, category,
value, strvalue or combination of those criteria.
@ -127,7 +135,10 @@ class TypedObjectManager(idmapper.manager.SharedMemoryManager):
"""
dbmodel = self.model.__dbclass__.__name__.lower()
query = [("db_attributes__db_attrtype", attrtype), ("db_attributes__db_model", dbmodel)]
query = [
("db_attributes__db_attrtype", attrtype),
("db_attributes__db_model", dbmodel),
]
if key:
query.append(("db_attributes__db_key", key))
if category:
@ -153,11 +164,15 @@ class TypedObjectManager(idmapper.manager.SharedMemoryManager):
obj (list): Objects having the matching Nicks.
"""
return self.get_by_attribute(key=key, category=category, strvalue=nick, attrtype="nick")
return self.get_by_attribute(
key=key, category=category, strvalue=nick, attrtype="nick"
)
# Tag manager methods
def get_tag(self, key=None, category=None, obj=None, tagtype=None, global_search=False):
def get_tag(
self, key=None, category=None, obj=None, tagtype=None, global_search=False
):
"""
Return Tag objects by key, by category, by object (it is
stored on) or with a combination of those criteria.
@ -201,9 +216,9 @@ class TypedObjectManager(idmapper.manager.SharedMemoryManager):
if category:
query.append(("tag__db_category", category))
return Tag.objects.filter(
pk__in=self.model.db_tags.through.objects.filter(**dict(query)).values_list(
"tag_id", flat=True
)
pk__in=self.model.db_tags.through.objects.filter(
**dict(query)
).values_list("tag_id", flat=True)
)
def get_permission(self, key=None, category=None, obj=None):
@ -271,8 +286,8 @@ class TypedObjectManager(idmapper.manager.SharedMemoryManager):
global _Tag
if not _Tag:
from evennia.typeclasses.models import Tag as _Tag
match = kwargs.get('match', 'all').lower().strip()
match = kwargs.get("match", "all").lower().strip()
keys = make_iter(key) if key else []
categories = make_iter(category) if category else []
@ -281,7 +296,9 @@ class TypedObjectManager(idmapper.manager.SharedMemoryManager):
dbmodel = self.model.__dbclass__.__name__.lower()
query = (
self.filter(db_tags__db_tagtype__iexact=tagtype, db_tags__db_model__iexact=dbmodel)
self.filter(
db_tags__db_tagtype__iexact=tagtype, db_tags__db_model__iexact=dbmodel
)
.distinct()
.order_by("id")
)
@ -308,17 +325,19 @@ class TypedObjectManager(idmapper.manager.SharedMemoryManager):
clauses = Q()
uniq_categories = sorted(set(categories))
for category in uniq_categories:
clauses |= Q(db_category__iexact=category,)
clauses |= Q(db_category__iexact=category)
tags = _Tag.objects.filter(clauses)
query = query.filter(db_tags__in=tags).annotate(matches=Count('db_tags__pk', filter=Q(db_tags__in=tags), distinct=True))
query = query.filter(db_tags__in=tags).annotate(
matches=Count("db_tags__pk", filter=Q(db_tags__in=tags), distinct=True)
)
# Default ALL: Match all of the tags and optionally more
if match == 'all':
if match == "all":
query = query.filter(matches__gte=tags.count())
# ANY: Match any single tag, ordered by weight
elif match == 'any':
query = query.order_by('-matches')
elif match == "any":
query = query.order_by("-matches")
return query
@ -376,7 +395,9 @@ class TypedObjectManager(idmapper.manager.SharedMemoryManager):
# try to get old tag
dbmodel = self.model.__dbclass__.__name__.lower()
tag = self.get_tag(key=key, category=category, tagtype=tagtype, global_search=True)
tag = self.get_tag(
key=key, category=category, tagtype=tagtype, global_search=True
)
if tag and data is not None:
# get tag from list returned by get_tag
tag = tag[0]
@ -390,7 +411,9 @@ class TypedObjectManager(idmapper.manager.SharedMemoryManager):
from evennia.typeclasses.models import Tag as _Tag
tag = _Tag.objects.create(
db_key=key.strip().lower() if key is not None else None,
db_category=category.strip().lower() if category and key is not None else None,
db_category=category.strip().lower()
if category and key is not None
else None,
db_data=data,
db_model=dbmodel,
db_tagtype=tagtype.strip().lower() if tagtype is not None else None,
@ -491,10 +514,14 @@ class TypedObjectManager(idmapper.manager.SharedMemoryManager):
dbtotals = {}
typeclass_paths = set(self.values_list("db_typeclass_path", flat=True))
for typeclass_path in typeclass_paths:
dbtotals[typeclass_path] = self.filter(db_typeclass_path=typeclass_path).count()
dbtotals[typeclass_path] = self.filter(
db_typeclass_path=typeclass_path
).count()
return dbtotals
def typeclass_search(self, typeclass, include_children=False, include_parents=False):
def typeclass_search(
self, typeclass, include_children=False, include_parents=False
):
"""
Searches through all objects returning those which has a
certain typeclass. If location is set, limit search to objects
@ -769,7 +796,8 @@ class TypeclassManager(TypedObjectManager):
"""
paths = [self.model.path] + [
"%s.%s" % (cls.__module__, cls.__name__) for cls in self._get_subclasses(self.model)
"%s.%s" % (cls.__module__, cls.__name__)
for cls in self._get_subclasses(self.model)
]
kwargs.update({"db_typeclass_path__in": paths})
return super().get(**kwargs)
@ -791,7 +819,8 @@ class TypeclassManager(TypedObjectManager):
"""
# query, including all subclasses
paths = [self.model.path] + [
"%s.%s" % (cls.__module__, cls.__name__) for cls in self._get_subclasses(self.model)
"%s.%s" % (cls.__module__, cls.__name__)
for cls in self._get_subclasses(self.model)
]
kwargs.update({"db_typeclass_path__in": paths})
return super().filter(*args, **kwargs)
@ -806,6 +835,7 @@ class TypeclassManager(TypedObjectManager):
"""
paths = [self.model.path] + [
"%s.%s" % (cls.__module__, cls.__name__) for cls in self._get_subclasses(self.model)
"%s.%s" % (cls.__module__, cls.__name__)
for cls in self._get_subclasses(self.model)
]
return super().all().filter(db_typeclass_path__in=paths)

View file

@ -17,10 +17,16 @@ class Migration(migrations.Migration):
(
"id",
models.AutoField(
verbose_name="ID", serialize=False, auto_created=True, primary_key=True
verbose_name="ID",
serialize=False,
auto_created=True,
primary_key=True,
),
),
("db_key", models.CharField(max_length=255, verbose_name="key", db_index=True)),
(
"db_key",
models.CharField(max_length=255, verbose_name="key", db_index=True),
),
(
"db_value",
evennia.utils.picklefield.PickledObjectField(
@ -81,7 +87,9 @@ class Migration(migrations.Migration):
),
(
"db_date_created",
models.DateTimeField(auto_now_add=True, verbose_name="date_created"),
models.DateTimeField(
auto_now_add=True, verbose_name="date_created"
),
),
],
options={"verbose_name": "Evennia Attribute"},
@ -93,7 +101,10 @@ class Migration(migrations.Migration):
(
"id",
models.AutoField(
verbose_name="ID", serialize=False, auto_created=True, primary_key=True
verbose_name="ID",
serialize=False,
auto_created=True,
primary_key=True,
),
),
(

View file

@ -16,7 +16,10 @@ class Migration(migrations.Migration):
operations = [
migrations.CreateModel(
name="DefaultObject", fields=[], options={"proxy": True}, bases=("objects.objectdb",)
name="DefaultObject",
fields=[],
options={"proxy": True},
bases=("objects.objectdb",),
),
migrations.CreateModel(
name="DefaultAccount",
@ -26,7 +29,10 @@ class Migration(migrations.Migration):
managers=[("objects", evennia.accounts.manager.AccountManager())],
),
migrations.CreateModel(
name="ScriptBase", fields=[], options={"proxy": True}, bases=("scripts.scriptdb",)
name="ScriptBase",
fields=[],
options={"proxy": True},
bases=("scripts.scriptdb",),
),
migrations.CreateModel(
name="DefaultCharacter",
@ -66,6 +72,9 @@ class Migration(migrations.Migration):
bases=("typeclasses.defaultscript",),
),
migrations.CreateModel(
name="Store", fields=[], options={"proxy": True}, bases=("typeclasses.defaultscript",)
name="Store",
fields=[],
options={"proxy": True},
bases=("typeclasses.defaultscript",),
),
]

View file

@ -15,7 +15,12 @@ def update_nicks(apps, schema_editor):
except (TypeError, ValueError):
# old setup, we store it in the new format - old uses its own key
# as regex to keep the old matching (and has no $-type args)
nick.db_value = (nick.db_key, nick.db_strvalue, nick.db_key, nick.db_strvalue)
nick.db_value = (
nick.db_key,
nick.db_strvalue,
nick.db_key,
nick.db_strvalue,
)
nick.save()

View file

@ -100,10 +100,12 @@ class Migration(migrations.Migration):
operations = [
migrations.AlterUniqueTogether(
name="tag", unique_together=set([("db_key", "db_category", "db_tagtype", "db_model")])
name="tag",
unique_together=set([("db_key", "db_category", "db_tagtype", "db_model")]),
),
migrations.AlterIndexTogether(
name="tag", index_together=set([("db_key", "db_category", "db_tagtype", "db_model")])
name="tag",
index_together=set([("db_key", "db_category", "db_tagtype", "db_model")]),
),
migrations.RunPython(update_tags_with_dbmodel),
]

View file

@ -32,12 +32,17 @@ def update_perms_and_locks(apps, schema_editor):
("comms", "ChannelDB"),
]
p_reg = re.compile(
r"(?<=perm\()(\w+)(?=\))|(?<=perm_above\()(\w+)(?=\))", re.IGNORECASE + re.UNICODE
r"(?<=perm\()(\w+)(?=\))|(?<=perm_above\()(\w+)(?=\))",
re.IGNORECASE + re.UNICODE,
)
def _sub(match):
perm = match.group(1)
return perm_map[perm.lower()].capitalize() if (perm and perm.lower() in perm_map) else perm
return (
perm_map[perm.lower()].capitalize()
if (perm and perm.lower() in perm_map)
else perm
)
for app_tuple in apps_models:
TClass = apps.get_model(*app_tuple)

View file

@ -50,7 +50,13 @@ def _case_sensitive_replace(string, old, new):
result.append(new_word[ind + 1 :].lower())
out.append("".join(result))
# if we have more new words than old ones, just add them verbatim
out.extend([new_word for ind, new_word in enumerate(new_words) if ind >= len(old_words)])
out.extend(
[
new_word
for ind, new_word in enumerate(new_words)
if ind >= len(old_words)
]
)
return " ".join(out)
if string is None:
@ -70,22 +76,46 @@ def update_typeclasses(apps, schema_editor):
Tags = apps.get_model("typeclasses", "Tag")
for obj in ObjectDB.objects.all():
obj.db_typeclass_path = _case_sensitive_replace(obj.db_typeclass_path, "player", "account")
obj.db_cmdset_storage = _case_sensitive_replace(obj.db_cmdset_storage, "player", "account")
obj.db_lock_storage = _case_sensitive_replace(obj.db_lock_storage, "player", "account")
obj.save(update_fields=["db_typeclass_path", "db_cmdset_storage", "db_lock_storage"])
obj.db_typeclass_path = _case_sensitive_replace(
obj.db_typeclass_path, "player", "account"
)
obj.db_cmdset_storage = _case_sensitive_replace(
obj.db_cmdset_storage, "player", "account"
)
obj.db_lock_storage = _case_sensitive_replace(
obj.db_lock_storage, "player", "account"
)
obj.save(
update_fields=["db_typeclass_path", "db_cmdset_storage", "db_lock_storage"]
)
for obj in AccountDB.objects.all():
obj.db_typeclass_path = _case_sensitive_replace(obj.db_typeclass_path, "player", "account")
obj.db_cmdset_storage = _case_sensitive_replace(obj.db_cmdset_storage, "player", "account")
obj.db_lock_storage = _case_sensitive_replace(obj.db_lock_storage, "player", "account")
obj.save(update_fields=["db_typeclass_path", "db_cmdset_storage", "db_lock_storage"])
obj.db_typeclass_path = _case_sensitive_replace(
obj.db_typeclass_path, "player", "account"
)
obj.db_cmdset_storage = _case_sensitive_replace(
obj.db_cmdset_storage, "player", "account"
)
obj.db_lock_storage = _case_sensitive_replace(
obj.db_lock_storage, "player", "account"
)
obj.save(
update_fields=["db_typeclass_path", "db_cmdset_storage", "db_lock_storage"]
)
for obj in ScriptDB.objects.all():
obj.db_typeclass_path = _case_sensitive_replace(obj.db_typeclass_path, "player", "account")
obj.db_lock_storage = _case_sensitive_replace(obj.db_lock_storage, "player", "account")
obj.db_typeclass_path = _case_sensitive_replace(
obj.db_typeclass_path, "player", "account"
)
obj.db_lock_storage = _case_sensitive_replace(
obj.db_lock_storage, "player", "account"
)
obj.save(update_fields=["db_typeclass_path", "db_lock_storage"])
for obj in ChannelDB.objects.all():
obj.db_typeclass_path = _case_sensitive_replace(obj.db_typeclass_path, "player", "account")
obj.db_lock_storage = _case_sensitive_replace(obj.db_lock_storage, "player", "account")
obj.db_typeclass_path = _case_sensitive_replace(
obj.db_typeclass_path, "player", "account"
)
obj.db_lock_storage = _case_sensitive_replace(
obj.db_lock_storage, "player", "account"
)
obj.save(update_fields=["db_typeclass_path", "db_lock_storage"])
for obj in Attributes.objects.filter(db_model="playerdb"):
obj.db_model = "accountdb"

View file

@ -28,9 +28,13 @@ def _drop_table(db_cursor, table_name):
db_cursor.execute("DROP TABLE {table};".format(table=table_name))
db_cursor.execute("SET FOREIGN_KEY_CHECKS=1;")
elif _ENGINE == "postgresql_psycopg2":
db_cursor.execute("ALTER TABLE {table} DISABLE TRIGGER ALL;".format(table=table_name))
db_cursor.execute(
"ALTER TABLE {table} DISABLE TRIGGER ALL;".format(table=table_name)
)
db_cursor.execute("DROP TABLE {table};".format(table=table_name))
db_cursor.execute("ALTER TABLE {table} ENABLE TRIGGER ALL;".format(table=table_name))
db_cursor.execute(
"ALTER TABLE {table} ENABLE TRIGGER ALL;".format(table=table_name)
)
else: # sqlite3, other databases
db_cursor.execute("DROP TABLE {table};".format(table=table_name))

View file

@ -5,14 +5,19 @@ from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('typeclasses', '0012_attrs_to_picklev4_may_be_slow'),
]
dependencies = [("typeclasses", "0012_attrs_to_picklev4_may_be_slow")]
operations = [
migrations.AlterField(
model_name='tag',
name='db_tagtype',
field=models.CharField(blank=True, db_index=True, help_text='overall type of Tag', max_length=16, null=True, verbose_name='tagtype'),
),
model_name="tag",
name="db_tagtype",
field=models.CharField(
blank=True,
db_index=True,
help_text="overall type of Tag",
max_length=16,
null=True,
verbose_name="tagtype",
),
)
]

View file

@ -36,7 +36,11 @@ from django.urls import reverse
from django.utils.encoding import smart_str
from django.utils.text import slugify
from evennia.typeclasses.attributes import Attribute, AttributeHandler, NAttributeHandler
from evennia.typeclasses.attributes import (
Attribute,
AttributeHandler,
NAttributeHandler,
)
from evennia.typeclasses.tags import Tag, TagHandler, AliasHandler, PermissionHandler
from evennia.utils.idmapper.models import SharedMemoryModel, SharedMemoryModelBase
@ -194,7 +198,9 @@ class TypedObject(SharedMemoryModel):
db_index=True,
)
# Creation date. This is not changed once the object is created.
db_date_created = models.DateTimeField("creation date", editable=False, auto_now_add=True)
db_date_created = models.DateTimeField(
"creation date", editable=False, auto_now_add=True
)
# Lock storage
db_lock_storage = models.TextField(
"locks",
@ -249,7 +255,10 @@ class TypedObject(SharedMemoryModel):
log_trace()
self.__dbclass__ = self._meta.concrete_model or self.__class__
else:
self.db_typeclass_path = "%s.%s" % (self.__module__, self.__class__.__name__)
self.db_typeclass_path = "%s.%s" % (
self.__module__,
self.__class__.__name__,
)
# important to put this at the end since _meta is based on the set __class__
try:
self.__dbclass__ = self._meta.concrete_model or self.__class__
@ -364,7 +373,9 @@ class TypedObject(SharedMemoryModel):
self.db_key = value
self.save(update_fields=["db_key"])
self.at_rename(oldname, value)
SIGNAL_TYPED_OBJECT_POST_RENAME.send(sender=self, old_key=oldname, new_key=value)
SIGNAL_TYPED_OBJECT_POST_RENAME.send(
sender=self, old_key=oldname, new_key=value
)
#
#
@ -492,7 +503,8 @@ class TypedObject(SharedMemoryModel):
else:
# check parent chain
return any(
hasattr(cls, "path") and cls.path in typeclass for cls in self.__class__.mro()
hasattr(cls, "path") and cls.path in typeclass
for cls in self.__class__.mro()
)
def swap_typeclass(
@ -541,7 +553,9 @@ class TypedObject(SharedMemoryModel):
if not callable(new_typeclass):
# this is an actual class object - build the path
new_typeclass = class_from_module(new_typeclass, defaultpaths=settings.TYPECLASS_PATHS)
new_typeclass = class_from_module(
new_typeclass, defaultpaths=settings.TYPECLASS_PATHS
)
# if we get to this point, the class is ok.
@ -584,7 +598,12 @@ class TypedObject(SharedMemoryModel):
#
def access(
self, accessing_obj, access_type="read", default=False, no_superuser_bypass=False, **kwargs
self,
accessing_obj,
access_type="read",
default=False,
no_superuser_bypass=False,
**kwargs
):
"""
Determines if another object has permission to access this one.
@ -731,7 +750,9 @@ class TypedObject(SharedMemoryModel):
try:
return self._ndb_holder
except AttributeError:
self._ndb_holder = DbHolder(self, "nattrhandler", manager_name="nattributes")
self._ndb_holder = DbHolder(
self, "nattrhandler", manager_name="nattributes"
)
return self._ndb_holder
# @db.setter
@ -825,7 +846,8 @@ class TypedObject(SharedMemoryModel):
"""
content_type = ContentType.objects.get_for_model(self.__class__)
return reverse(
"admin:%s_%s_change" % (content_type.app_label, content_type.model), args=(self.id,)
"admin:%s_%s_change" % (content_type.app_label, content_type.model),
args=(self.id,),
)
@classmethod

View file

@ -63,11 +63,20 @@ class Tag(models.Model):
)
# this is "objectdb" etc. Required behind the scenes
db_model = models.CharField(
"model", max_length=32, null=True, help_text="database model to Tag", db_index=True
"model",
max_length=32,
null=True,
help_text="database model to Tag",
db_index=True,
)
# this is None, alias or permission
db_tagtype = models.CharField(
"tagtype", max_length=16, null=True, blank=True, help_text="overall type of Tag", db_index=True
"tagtype",
max_length=16,
null=True,
blank=True,
help_text="overall type of Tag",
db_index=True,
)
class Meta(object):
@ -82,7 +91,10 @@ class Tag(models.Model):
def __str__(self):
return str(
"<Tag: %s%s>"
% (self.db_key, "(category:%s)" % self.db_category if self.db_category else "")
% (
self.db_key,
"(category:%s)" % self.db_category if self.db_category else "",
)
)
@ -121,7 +133,8 @@ class TagHandler(object):
def _fullcache(self):
"Cache all tags of this object"
if not _TYPECLASS_AGGRESSIVE_CACHE: return
if not _TYPECLASS_AGGRESSIVE_CACHE:
return
query = {
"%s__id" % self._model: self._objid,
"tag__db_model": self._model,
@ -129,7 +142,9 @@ class TagHandler(object):
}
tags = [
conn.tag
for conn in getattr(self.obj, self._m2m_fieldname).through.objects.filter(**query)
for conn in getattr(self.obj, self._m2m_fieldname).through.objects.filter(
**query
)
]
self._cache = dict(
(
@ -186,7 +201,9 @@ class TagHandler(object):
"tag__db_key__iexact": key.lower(),
"tag__db_category__iexact": category.lower() if category else None,
}
conn = getattr(self.obj, self._m2m_fieldname).through.objects.filter(**query)
conn = getattr(self.obj, self._m2m_fieldname).through.objects.filter(
**query
)
if conn:
tag = conn[0].tag
if _TYPECLASS_AGGRESSIVE_CACHE:
@ -209,9 +226,9 @@ class TagHandler(object):
}
tags = [
conn.tag
for conn in getattr(self.obj, self._m2m_fieldname).through.objects.filter(
**query
)
for conn in getattr(
self.obj, self._m2m_fieldname
).through.objects.filter(**query)
]
if _TYPECLASS_AGGRESSIVE_CACHE:
for tag in tags:
@ -232,10 +249,14 @@ class TagHandler(object):
tag_obj (tag): The newly saved tag
"""
if not _TYPECLASS_AGGRESSIVE_CACHE: return
if not _TYPECLASS_AGGRESSIVE_CACHE:
return
if not key: # don't allow an empty key in cache
return
key, category = key.strip().lower(), category.strip().lower() if category else category
key, category = (
key.strip().lower(),
category.strip().lower() if category else category,
)
cachekey = "%s-%s" % (key, category)
catkey = "-%s" % category
self._cache[cachekey] = tag_obj
@ -252,7 +273,10 @@ class TagHandler(object):
category (str or None): A cleaned category name
"""
key, category = key.strip().lower(), category.strip().lower() if category else category
key, category = (
key.strip().lower(),
category.strip().lower() if category else category,
)
catkey = "-%s" % category
if key:
cachekey = "%s-%s" % (key, category)
@ -308,7 +332,14 @@ class TagHandler(object):
getattr(self.obj, self._m2m_fieldname).add(tagobj)
self._setcache(tagstr, category, tagobj)
def get(self, key=None, default=None, category=None, return_tagobj=False, return_list=False):
def get(
self,
key=None,
default=None,
category=None,
return_tagobj=False,
return_list=False,
):
"""
Get the tag for the given key, category or combination of the two.
@ -373,7 +404,10 @@ class TagHandler(object):
# that when no objects reference the tag anymore (but how to check)?
# For now, tags are never deleted, only their connection to objects.
tagobj = getattr(self.obj, self._m2m_fieldname).filter(
db_key=tagstr, db_category=category, db_model=self._model, db_tagtype=self._tagtype
db_key=tagstr,
db_category=category,
db_model=self._model,
db_tagtype=self._tagtype,
)
if tagobj:
getattr(self.obj, self._m2m_fieldname).remove(tagobj[0])

View file

@ -19,15 +19,15 @@ class TestAttributes(EvenniaTest):
self.assertEqual(self.obj1.attributes.get(key), value)
self.obj1.db.testattr = value
self.assertEqual(self.obj1.db.testattr, value)
@override_settings(TYPECLASS_AGGRESSIVE_CACHE=False)
@patch('evennia.typeclasses.attributes._TYPECLASS_AGGRESSIVE_CACHE', False)
@patch("evennia.typeclasses.attributes._TYPECLASS_AGGRESSIVE_CACHE", False)
def test_attrhandler_nocache(self):
key = "testattr"
value = "test attr value "
self.obj1.attributes.add(key, value)
self.assertFalse(self.obj1.attributes._cache)
self.assertEqual(self.obj1.attributes.get(key), value)
self.obj1.db.testattr = value
self.assertEqual(self.obj1.db.testattr, value)
@ -58,12 +58,16 @@ class TestTypedObjectManager(EvenniaTest):
self.obj2.tags.add("tag4")
self.obj2.tags.add("tag2c")
self.assertEqual(self._manager("get_by_tag", "tag1"), [self.obj1])
self.assertEqual(set(self._manager("get_by_tag", "tag2")), set([self.obj1, self.obj2]))
self.assertEqual(
set(self._manager("get_by_tag", "tag2")), set([self.obj1, self.obj2])
)
self.assertEqual(self._manager("get_by_tag", "tag2a"), [self.obj2])
self.assertEqual(self._manager("get_by_tag", "tag3 with spaces"), [self.obj2])
self.assertEqual(self._manager("get_by_tag", ["tag2a", "tag2b"]), [self.obj2])
self.assertEqual(self._manager("get_by_tag", ["tag2a", "tag1"]), [])
self.assertEqual(self._manager("get_by_tag", ["tag2a", "tag4", "tag2c"]), [self.obj2])
self.assertEqual(
self._manager("get_by_tag", ["tag2a", "tag4", "tag2c"]), [self.obj2]
)
def test_get_by_tag_and_category(self):
self.obj1.tags.add("tag5", "category1")
@ -76,22 +80,33 @@ class TestTypedObjectManager(EvenniaTest):
self.obj2.tags.add("tag6", "category3")
self.obj2.tags.add("tag7", "category1")
self.obj2.tags.add("tag7", "category5")
self.assertEqual(self._manager("get_by_tag", "tag5", "category1"), [self.obj1, self.obj2])
self.assertEqual(
self._manager("get_by_tag", "tag5", "category1"), [self.obj1, self.obj2]
)
self.assertEqual(self._manager("get_by_tag", "tag6", "category1"), [])
self.assertEqual(self._manager("get_by_tag", "tag6", "category3"), [self.obj1, self.obj2])
self.assertEqual(
self._manager("get_by_tag", "tag6", "category3"), [self.obj1, self.obj2]
)
self.assertEqual(
self._manager("get_by_tag", ["tag5", "tag6"], ["category1", "category3"]),
[self.obj1, self.obj2],
)
self.assertEqual(
self._manager("get_by_tag", ["tag5", "tag7"], "category1"), [self.obj1, self.obj2]
self._manager("get_by_tag", ["tag5", "tag7"], "category1"),
[self.obj1, self.obj2],
)
self.assertEqual(
self._manager("get_by_tag", category="category1"), [self.obj1, self.obj2]
)
self.assertEqual(self._manager("get_by_tag", category="category1"), [self.obj1, self.obj2])
self.assertEqual(self._manager("get_by_tag", category="category2"), [self.obj2])
self.assertEqual(
self._manager("get_by_tag", category=["category1", "category3"]), [self.obj1, self.obj2]
self._manager("get_by_tag", category=["category1", "category3"]),
[self.obj1, self.obj2],
)
self.assertEqual(
self._manager("get_by_tag", category=["category1", "category2"]), [self.obj2]
self._manager("get_by_tag", category=["category1", "category2"]),
[self.obj2],
)
self.assertEqual(
self._manager("get_by_tag", category=["category5", "category4"]), []
)
self.assertEqual(self._manager("get_by_tag", category=["category5", "category4"]), [])