Resolve django 1.11 migration errors.

This commit is contained in:
Griatch 2017-06-17 22:15:00 +02:00
commit 0ff1718437
54 changed files with 6444 additions and 574 deletions

View file

@ -49,6 +49,7 @@ import re
from django.conf import settings
from evennia import Command, CmdSet
from evennia.utils import is_iter, fill, dedent, logger, justify, to_str
from evennia.utils.ansi import raw
from evennia.commands import cmdhandler
# we use cmdhandler instead of evennia.syscmdkeys to
@ -274,7 +275,7 @@ class CmdEditorBase(Command):
lstart, lend = cline, cline + 1
linerange = False
if arglist and ':' in arglist[0]:
if arglist and arglist[0].count(':') == 1:
part1, part2 = arglist[0].split(':')
if part1 and part1.isdigit():
lstart = min(max(0, int(part1)) - 1, nlines)
@ -377,9 +378,9 @@ class CmdLineInput(CmdEditorBase):
indent = "off"
self.caller.msg("|b%02i|||n (|g%s|n) %s" % (
cline, indent, line))
cline, indent, raw(line)))
else:
self.caller.msg("|b%02i|||n %s" % (cline, self.args))
self.caller.msg("|b%02i|||n %s" % (cline, raw(self.args)))
class CmdEditorGroup(CmdEditorBase):
@ -425,7 +426,7 @@ class CmdEditorGroup(CmdEditorBase):
editor.display_buffer(linenums=False, options={"raw": True})
elif cmd == ":::":
# Insert single colon alone on a line
editor.update_buffer(editor.buffer + "\n:")
editor.update_buffer([":"] if lstart == 0 else linebuffer + [":"])
if echo_mode:
caller.msg("Single ':' added to buffer.")
elif cmd == ":h":
@ -932,9 +933,9 @@ class EvEditor(object):
footer = "|n" + sep * 10 +\
"[l:%02i w:%03i c:%04i]" % (nlines, nwords, nchars) + sep * 12 + "(:h for help)" + sep * 28
if linenums:
main = "\n".join("|b%02i|||n %s" % (iline + 1 + offset, line) for iline, line in enumerate(lines))
main = "\n".join("|b%02i|||n %s" % (iline + 1 + offset, raw(line)) for iline, line in enumerate(lines))
else:
main = "\n".join(lines)
main = "\n".join([raw(line) for line in lines])
string = "%s\n%s\n%s" % (header, main, footer)
self._caller.msg(string, options=options)

View file

@ -881,9 +881,11 @@ class CmdGetInput(Command):
caller.ndb._getinput._session = self.session
prompt = caller.ndb._getinput._prompt
args = caller.ndb._getinput._args
kwargs = caller.ndb._getinput._kwargs
result = self.raw_string.strip() # we strip the ending line break caused by sending
ok = not callback(caller, prompt, result)
ok = not callback(caller, prompt, result, *args, **kwargs)
if ok:
# only clear the state if the callback does not return
# anything
@ -917,7 +919,7 @@ class _Prompt(object):
pass
def get_input(caller, prompt, callback, session=None):
def get_input(caller, prompt, callback, session=None, *args, **kwargs):
"""
This is a helper function for easily request input from
the caller.
@ -942,6 +944,13 @@ def get_input(caller, prompt, callback, session=None):
greater than 2. The session is then updated by the
command and is available (for example in callbacks)
through `caller.ndb.getinput._session`.
*args, **kwargs (optional): Extra arguments will be
passed to the fall back function as a list 'args'
and all keyword arguments as a dictionary 'kwargs'.
To utilise *args and **kwargs, a value for the
session argument must be provided (None by default)
and the callback function must take *args and
**kwargs as arguments.
Raises:
RuntimeError: If the given callback is not callable.
@ -961,6 +970,12 @@ def get_input(caller, prompt, callback, session=None):
multisession modes), then it is available in the
callback through `caller.ndb._getinput._session`.
Chaining get_input functions will result in the caller
stacking ever more instances of InputCmdSets. Whilst
they will all be cleared on concluding the get_input
chain, EvMenu should be considered for anything beyond
a single question.
"""
if not callable(callback):
raise RuntimeError("get_input: input callback is not callable.")
@ -968,6 +983,8 @@ def get_input(caller, prompt, callback, session=None):
caller.ndb._getinput._callback = callback
caller.ndb._getinput._prompt = prompt
caller.ndb._getinput._session = session
caller.ndb._getinput._args = args
caller.ndb._getinput._kwargs = kwargs
caller.cmdset.add(InputCmdSet)
caller.msg(prompt, session=session)

View file

@ -25,6 +25,12 @@ class SharedMemoryManager(Manager):
key = key[:-len('__exact')]
if key in ('pk', self.model._meta.pk.attname):
inst = self.model.get_cached_instance(kwargs[items[0]])
try:
# we got the item from cache, but if this is a fk, check it's ours
if getattr(inst, str(self.field).split(".")[-1]) != self.instance:
inst = None
except Exception:
pass
if inst is None:
inst = super(SharedMemoryManager, self).get(*args, **kwargs)
return inst

View file

@ -77,7 +77,7 @@ class SharedMemoryModelBase(ModelBase):
"""
# the dbmodel is either the proxy base or ourselves
dbmodel = cls._meta.proxy_for_model if cls._meta.proxy else cls
dbmodel = cls._meta.concrete_model if cls._meta.proxy else cls
cls.__dbclass__ = dbmodel
if not hasattr(dbmodel, "__instance_cache__"):
# we store __instance_cache__ only on the dbmodel base
@ -572,7 +572,7 @@ def cache_size(mb=True):
if not subclasses:
num = len(submodel.get_all_cached_instances())
numtotal[0] += num
classdict[submodel.__name__] = num
classdict[submodel.__dbclass__.__name__] = num
else:
get_recurse(subclasses)
get_recurse(SharedMemoryModel.__subclasses__())

View file

@ -19,12 +19,14 @@ import os
import time
from datetime import datetime
from traceback import format_exc
from twisted.python import log
from twisted.python import log, logfile
from twisted.internet.threads import deferToThread
_LOGDIR = None
_LOG_ROTATE_SIZE = None
_TIMEZONE = None
_CHANNEL_LOG_NUM_TAIL_LINES = None
def timeformat(when=None):
@ -153,6 +155,58 @@ log_depmsg = log_dep
# Arbitrary file logger
class EvenniaLogFile(logfile.LogFile):
"""
A rotating logfile based off Twisted's LogFile. It overrides
the LogFile's rotate method in order to append some of the last
lines of the previous log to the start of the new log, in order
to preserve a continuous chat history for channel log files.
"""
# we delay import of settings to keep logger module as free
# from django as possible.
global _CHANNEL_LOG_NUM_TAIL_LINES
if _CHANNEL_LOG_NUM_TAIL_LINES is None:
from django.conf import settings
_CHANNEL_LOG_NUM_TAIL_LINES = settings.CHANNEL_LOG_NUM_TAIL_LINES
num_lines_to_append = _CHANNEL_LOG_NUM_TAIL_LINES
def rotate(self):
"""
Rotates our log file and appends some number of lines from
the previous log to the start of the new one.
"""
append_tail = self.num_lines_to_append > 0
if not append_tail:
logfile.LogFile.rotate(self)
return
lines = tail_log_file(self.path, 0, self.num_lines_to_append)
logfile.LogFile.rotate(self)
for line in lines:
self.write(line)
def seek(self, *args, **kwargs):
"""
Convenience method for accessing our _file attribute's seek method,
which is used in tail_log_function.
Args:
*args: Same args as file.seek
**kwargs: Same kwargs as file.seek
"""
return self._file.seek(*args, **kwargs)
def readlines(self, *args, **kwargs):
"""
Convenience method for accessing our _file attribute's readlines method,
which is used in tail_log_function.
Args:
*args: same args as file.readlines
**kwargs: same kwargs as file.readlines
Returns:
lines (list): lines from our _file attribute.
"""
return self._file.readlines(*args, **kwargs)
_LOG_FILE_HANDLES = {} # holds open log handles
@ -162,10 +216,13 @@ def _open_log_file(filename):
handle. Will create a new file in the log dir if one didn't
exist.
"""
global _LOG_FILE_HANDLES, _LOGDIR
# we delay import of settings to keep logger module as free
# from django as possible.
global _LOG_FILE_HANDLES, _LOGDIR, _LOG_ROTATE_SIZE
if not _LOGDIR:
from django.conf import settings
_LOGDIR = settings.LOG_DIR
_LOG_ROTATE_SIZE = settings.CHANNEL_LOG_ROTATE_SIZE
filename = os.path.join(_LOGDIR, filename)
if filename in _LOG_FILE_HANDLES:
@ -173,7 +230,8 @@ def _open_log_file(filename):
return _LOG_FILE_HANDLES[filename]
else:
try:
filehandle = open(filename, "a+") # append mode + reading
filehandle = EvenniaLogFile.fromFullPath(filename, rotateLength=_LOG_ROTATE_SIZE)
# filehandle = open(filename, "a+") # append mode + reading
_LOG_FILE_HANDLES[filename] = filehandle
return filehandle
except IOError:

View file

@ -22,7 +22,7 @@ from os.path import join as osjoin
from importlib import import_module
from inspect import ismodule, trace, getmembers, getmodule
from collections import defaultdict, OrderedDict
from twisted.internet import threads, reactor
from twisted.internet import threads, reactor, task
from django.conf import settings
from django.utils import timezone
from django.utils.translation import ugettext as _
@ -940,7 +940,7 @@ def delay(timedelay, callback, *args, **kwargs):
specified here.
"""
return reactor.callLater(timedelay, callback, *args, **kwargs)
return task.deferLater(reactor, timedelay, callback, *args, **kwargs)
_TYPECLASSMODELS = None