Make scripts/objects lists use EvMore. Change EvMore to not justify by default.

This commit is contained in:
Griatch 2020-01-11 15:49:12 +01:00
parent b5aee2c41e
commit 69d85bd184
221 changed files with 2190 additions and 6810 deletions

View file

@ -126,9 +126,7 @@ 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):
@ -144,9 +142,7 @@ 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
@ -181,14 +177,9 @@ 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,
)
attr_value = PickledFormField(
label="Value", help_text="Value to pickle/save", required=False
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_type = forms.CharField(
label="Type",
help_text='Internal use. Either unset (normal Attribute) or "nick"',
@ -203,13 +194,7 @@ 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):
"""
@ -257,9 +242,7 @@ 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
@ -337,9 +320,7 @@ 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,10 +70,7 @@ 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",
@ -107,9 +104,7 @@ 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()
@ -209,9 +204,7 @@ 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
@ -253,9 +246,7 @@ 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(
(
@ -320,15 +311,11 @@ 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:
@ -347,26 +334,20 @@ 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:
@ -637,15 +618,11 @@ 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)
@ -720,9 +697,7 @@ 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
@ -735,9 +710,7 @@ 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()
@ -778,8 +751,7 @@ 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]
@ -806,9 +778,7 @@ 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
@ -887,20 +857,14 @@ 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
@ -996,17 +960,10 @@ 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):
"""
@ -1022,9 +979,7 @@ 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.
@ -1058,9 +1013,7 @@ 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
}
@ -1072,9 +1025,7 @@ 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
@ -1165,9 +1116,5 @@ 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,13 +30,7 @@ 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
@ -79,9 +73,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):
@ -107,9 +101,7 @@ 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.
@ -135,10 +127,7 @@ 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:
@ -164,15 +153,11 @@ 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.
@ -216,9 +201,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):
@ -300,9 +285,7 @@ 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")
)
@ -400,9 +383,7 @@ 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]
@ -416,9 +397,7 @@ 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,
@ -519,14 +498,10 @@ 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
@ -801,8 +776,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)
]
kwargs.update({"db_typeclass_path__in": paths})
return super().get(**kwargs)
@ -824,8 +798,7 @@ 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)
@ -840,7 +813,6 @@ 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,16 +17,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
),
),
(
"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(
@ -87,9 +81,7 @@ 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"},
@ -101,10 +93,7 @@ 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,10 +16,7 @@ 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",
@ -29,10 +26,7 @@ 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",
@ -72,9 +66,6 @@ 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,12 +15,7 @@ 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,12 +100,10 @@ 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,17 +32,12 @@ 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,13 +50,7 @@ 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:
@ -76,46 +70,22 @@ 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,13 +28,9 @@ 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

@ -36,11 +36,7 @@ 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
@ -198,9 +194,7 @@ 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",
@ -255,10 +249,7 @@ 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__
@ -373,9 +364,7 @@ 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)
#
#
@ -503,8 +492,7 @@ 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(
@ -553,9 +541,7 @@ 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.
@ -598,12 +584,7 @@ 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.
@ -750,9 +731,7 @@ 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
@ -846,8 +825,7 @@ 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,7 @@ 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(
@ -91,10 +87,7 @@ 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 "")
)
@ -142,9 +135,7 @@ 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(
(
@ -201,9 +192,7 @@ 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:
@ -226,9 +215,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:
@ -253,10 +242,7 @@ class TagHandler(object):
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
@ -273,10 +259,7 @@ 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)
@ -332,14 +315,7 @@ 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.
@ -404,10 +380,7 @@ 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

@ -58,16 +58,12 @@ 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")
@ -83,39 +79,24 @@ class TestTypedObjectManager(EvenniaTest):
self.obj1.tags.add("tag8", "category6")
self.obj2.tags.add("tag9", "category6")
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.assertEqual(
self._manager("get_by_tag", category="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="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.obj1, self.obj2],
)
self.assertEqual(
self._manager("get_by_tag", category=["category5", "category4"]), []
)
self.assertEqual(
self._manager("get_by_tag", category="category1"), [self.obj1, self.obj2]
)
self.assertEqual(
self._manager("get_by_tag", category="category6"), [self.obj1, self.obj2]
self._manager("get_by_tag", category=["category1", "category2"]), [self.obj1, self.obj2]
)
self.assertEqual(self._manager("get_by_tag", category=["category5", "category4"]), [])
self.assertEqual(self._manager("get_by_tag", category="category1"), [self.obj1, self.obj2])
self.assertEqual(self._manager("get_by_tag", category="category6"), [self.obj1, self.obj2])