mirror of
https://github.com/evennia/evennia.git
synced 2026-03-21 07:16:31 +01:00
PEP8 cleanup of the entire codebase. Unchanged are many cases of too-long lines, partly because of the rewrite they would require but also because splitting many lines up would make the code harder to read. Also the third-party libraries (idmapper, prettytable etc) were not cleaned.
This commit is contained in:
parent
30b7d2a405
commit
1ae17bcbe4
154 changed files with 5613 additions and 4054 deletions
|
|
@ -1,12 +1,13 @@
|
|||
"""
|
||||
Makes it easier to import by grouping all relevant things already at this level.
|
||||
Makes it easier to import by grouping all relevant things already at this
|
||||
level.
|
||||
|
||||
You can henceforth import most things directly from src.scripts
|
||||
Also, the initiated object manager is available as src.scripts.manager.
|
||||
|
||||
"""
|
||||
|
||||
from src.scripts.scripts import *
|
||||
from src.scripts.scripts import *
|
||||
from src.scripts.models import ScriptDB
|
||||
|
||||
manager = ScriptDB.objects
|
||||
|
|
|
|||
|
|
@ -7,14 +7,17 @@ from src.typeclasses.models import Attribute
|
|||
from src.scripts.models import ScriptDB
|
||||
from django.contrib import admin
|
||||
|
||||
|
||||
class AttributeInline(admin.TabularInline):
|
||||
model = Attribute
|
||||
fields = ('db_key', 'db_value')
|
||||
max_num = 1
|
||||
|
||||
|
||||
class ScriptDBAdmin(admin.ModelAdmin):
|
||||
|
||||
list_display = ('id', 'db_key', 'db_typeclass_path', 'db_obj', 'db_interval', 'db_repeats', 'db_persistent')
|
||||
list_display = ('id', 'db_key', 'db_typeclass_path',
|
||||
'db_obj', 'db_interval', 'db_repeats', 'db_persistent')
|
||||
list_display_links = ('id', 'db_key')
|
||||
ordering = ['db_obj', 'db_typeclass_path']
|
||||
search_fields = ['^db_key', 'db_typeclass_path']
|
||||
|
|
@ -25,7 +28,9 @@ class ScriptDBAdmin(admin.ModelAdmin):
|
|||
|
||||
fieldsets = (
|
||||
(None, {
|
||||
'fields':(('db_key', 'db_typeclass_path'), 'db_interval', 'db_repeats', 'db_start_delay', 'db_persistent', 'db_obj')}),
|
||||
'fields': (('db_key', 'db_typeclass_path'), 'db_interval',
|
||||
'db_repeats', 'db_start_delay', 'db_persistent',
|
||||
'db_obj')}),
|
||||
)
|
||||
#inlines = [AttributeInline]
|
||||
|
||||
|
|
|
|||
|
|
@ -10,6 +10,7 @@ __all__ = ("ScriptManager",)
|
|||
|
||||
VALIDATE_ITERATION = 0
|
||||
|
||||
|
||||
class ScriptManager(TypedObjectManager):
|
||||
"""
|
||||
This Scriptmanager implements methods for searching
|
||||
|
|
@ -82,8 +83,8 @@ class ScriptManager(TypedObjectManager):
|
|||
def remove_non_persistent(self, obj=None):
|
||||
"""
|
||||
This cleans up the script database of all non-persistent
|
||||
scripts, or only those on obj. It is called every time the server restarts
|
||||
and
|
||||
scripts, or only those on obj. It is called every time the server
|
||||
restarts.
|
||||
"""
|
||||
if obj:
|
||||
to_stop = self.filter(db_obj=obj, db_persistent=False, db_is_active=True)
|
||||
|
|
@ -211,10 +212,11 @@ class ScriptManager(TypedObjectManager):
|
|||
Make an identical copy of the original_script
|
||||
"""
|
||||
typeclass = original_script.typeclass_path
|
||||
new_key = new_key if new_key!=None else original_script.key
|
||||
new_obj = new_obj if new_obj!=None else original_script.obj
|
||||
new_locks = new_locks if new_locks!=None else original_script.db_lock_storage
|
||||
new_key = new_key if new_key is not None else original_script.key
|
||||
new_obj = new_obj if new_obj is not None else original_script.obj
|
||||
new_locks = new_locks if new_locks is not None else original_script.db_lock_storage
|
||||
|
||||
from src.utils import create
|
||||
new_script = create.create_script(typeclass, key=new_key, obj=new_obj, locks=new_locks, autostart=True)
|
||||
new_script = create.create_script(typeclass, key=new_key, obj=new_obj,
|
||||
locks=new_locks, autostart=True)
|
||||
return new_script
|
||||
|
|
|
|||
|
|
@ -26,10 +26,9 @@ Common examples of uses of Scripts:
|
|||
"""
|
||||
from django.conf import settings
|
||||
from django.db import models
|
||||
from django.db.models.signals import post_init, pre_delete
|
||||
|
||||
from src.typeclasses.models import Attribute, TypedObject, TagHandler, AttributeHandler#, AliasHandler, NickHandler
|
||||
from django.contrib.contenttypes.models import ContentType
|
||||
from src.typeclasses.models import (TypedObject, TagHandler,
|
||||
AttributeHandler)
|
||||
from src.scripts.manager import ScriptManager
|
||||
|
||||
__all__ = ("ScriptDB",)
|
||||
|
|
|
|||
|
|
@ -38,10 +38,13 @@ class ScriptHandler(object):
|
|||
interval = script.interval
|
||||
if script.repeats:
|
||||
repeats = script.repeats
|
||||
try: next_repeat = script.time_until_next_repeat()
|
||||
except: next_repeat = "?"
|
||||
try:
|
||||
next_repeat = script.time_until_next_repeat()
|
||||
except:
|
||||
next_repeat = "?"
|
||||
string += _("\n '%(key)s' (%(next_repeat)s/%(interval)s, %(repeats)s repeats): %(desc)s") % \
|
||||
{"key":script.key, "next_repeat":next_repeat, "interval":interval,"repeats":repeats,"desc":script.desc}
|
||||
{"key": script.key, "next_repeat": next_repeat,
|
||||
"interval": interval, "repeats": repeats, "desc": script.desc}
|
||||
return string.strip()
|
||||
|
||||
def add(self, scriptclass, key=None, autostart=True):
|
||||
|
|
@ -51,10 +54,12 @@ class ScriptHandler(object):
|
|||
scriptclass - either a class object
|
||||
inheriting from Script, an instantiated script object
|
||||
or a python path to such a class object.
|
||||
key - optional identifier for the script (often set in script definition)
|
||||
key - optional identifier for the script (often set in script
|
||||
definition)
|
||||
autostart - start the script upon adding it
|
||||
"""
|
||||
script = create.create_script(scriptclass, key=key, obj=self.obj, autostart=autostart)
|
||||
script = create.create_script(scriptclass, key=key, obj=self.obj,
|
||||
autostart=autostart)
|
||||
if not script:
|
||||
logger.log_errmsg("Script %s could not be created and/or started." % scriptclass)
|
||||
return False
|
||||
|
|
|
|||
|
|
@ -5,30 +5,31 @@ scripts are inheriting from.
|
|||
It also defines a few common scripts.
|
||||
"""
|
||||
|
||||
from sys import getsizeof
|
||||
from time import time
|
||||
from collections import defaultdict
|
||||
from twisted.internet.defer import maybeDeferred
|
||||
from twisted.internet.task import LoopingCall
|
||||
from django.conf import settings
|
||||
from src.server import caches
|
||||
from django.utils.translation import ugettext as _
|
||||
from src.typeclasses.typeclass import TypeClass
|
||||
from src.scripts.models import ScriptDB
|
||||
from src.comms import channelhandler
|
||||
from src.utils import logger, is_pypy
|
||||
from django.utils.translation import ugettext as _
|
||||
from src.utils import logger
|
||||
|
||||
__all__ = ["Script", "DoNothing", "CheckSessions", "ValidateScripts", "ValidateChannelHandler"]
|
||||
__all__ = ["Script", "DoNothing", "CheckSessions",
|
||||
"ValidateScripts", "ValidateChannelHandler"]
|
||||
|
||||
_SESSIONS = None
|
||||
_ATTRIBUTE_CACHE_MAXSIZE = settings.ATTRIBUTE_CACHE_MAXSIZE # attr-cache size in MB.
|
||||
# attr-cache size in MB
|
||||
_ATTRIBUTE_CACHE_MAXSIZE = settings.ATTRIBUTE_CACHE_MAXSIZE
|
||||
|
||||
|
||||
#
|
||||
# Base script, inherit from Script below instead.
|
||||
#
|
||||
class ScriptClass(TypeClass):
|
||||
"""
|
||||
Base class for scripts. Don't inherit from this, inherit from Script instead.
|
||||
Base class for scripts. Don't inherit from this, inherit
|
||||
from the class 'Script' instead.
|
||||
"""
|
||||
# private methods
|
||||
|
||||
|
|
@ -53,7 +54,8 @@ class ScriptClass(TypeClass):
|
|||
else:
|
||||
# starting script anew.
|
||||
#print "_start_task: self.interval:", self.key, self.dbobj.interval
|
||||
self.ndb.twisted_task.start(self.dbobj.interval, now=start_now and not self.start_delay)
|
||||
self.ndb.twisted_task.start(self.dbobj.interval,
|
||||
now=start_now and not self.start_delay)
|
||||
self.ndb.time_last_called = int(time())
|
||||
|
||||
def _stop_task(self):
|
||||
|
|
@ -64,16 +66,19 @@ class ScriptClass(TypeClass):
|
|||
self.ndb.twisted_task.stop()
|
||||
except Exception:
|
||||
logger.log_trace()
|
||||
|
||||
def _step_err_callback(self, e):
|
||||
"callback for runner errors"
|
||||
cname = self.__class__.__name__
|
||||
estring = _("Script %(key)s(#%(dbid)i) of type '%(cname)s': at_repeat() error '%(err)s'.") % \
|
||||
{"key":self.key, "dbid":self.dbid, "cname":cname, "err":e.getErrorMessage()}
|
||||
{"key": self.key, "dbid": self.dbid, "cname": cname,
|
||||
"err": e.getErrorMessage()}
|
||||
try:
|
||||
self.dbobj.db_obj.msg(estring)
|
||||
except Exception:
|
||||
pass
|
||||
logger.log_errmsg(estring)
|
||||
|
||||
def _step_succ_callback(self):
|
||||
"step task runner. No try..except needed due to defer wrap."
|
||||
if not self.is_valid():
|
||||
|
|
@ -82,7 +87,7 @@ class ScriptClass(TypeClass):
|
|||
self.at_repeat()
|
||||
repeats = self.dbobj.db_repeats
|
||||
if repeats <= 0:
|
||||
pass # infinite repeat
|
||||
pass # infinite repeat
|
||||
elif repeats == 1:
|
||||
self.stop()
|
||||
return
|
||||
|
|
@ -92,14 +97,14 @@ class ScriptClass(TypeClass):
|
|||
self.save()
|
||||
|
||||
if self.ndb._paused_time:
|
||||
# this means we were running an unpaused script, for the time remaining
|
||||
# after the pause. Now we start a normal-running timer again.
|
||||
#print "switching to normal run:", self.key
|
||||
# this means we were running an unpaused script, for the
|
||||
# time remaining after the pause. Now we start a normal-running
|
||||
# timer again.
|
||||
# print "switching to normal run:", self.key
|
||||
del self.ndb._paused_time
|
||||
self._stop_task()
|
||||
self._start_task(start_now=False)
|
||||
|
||||
|
||||
def _step_task(self):
|
||||
"step task"
|
||||
try:
|
||||
|
|
@ -109,7 +114,6 @@ class ScriptClass(TypeClass):
|
|||
except Exception:
|
||||
logger.log_trace()
|
||||
|
||||
|
||||
# Public methods
|
||||
|
||||
def time_until_next_repeat(self):
|
||||
|
|
@ -136,7 +140,8 @@ class ScriptClass(TypeClass):
|
|||
force_restart - if True, will always restart the script, regardless
|
||||
of if it has started before.
|
||||
|
||||
returns 0 or 1 to indicated the script has been started or not. Used in counting.
|
||||
returns 0 or 1 to indicated the script has been started or not.
|
||||
Used in counting.
|
||||
"""
|
||||
#print "Script %s (%s) start (active:%s, force:%s) ..." % (self.key, id(self.dbobj),
|
||||
# self.is_active, force_restart)
|
||||
|
|
@ -205,7 +210,7 @@ class ScriptClass(TypeClass):
|
|||
"""
|
||||
#print "pausing", self.key, self.time_until_next_repeat()
|
||||
dt = self.time_until_next_repeat()
|
||||
if dt == None:
|
||||
if dt is None:
|
||||
return
|
||||
self.db._paused_time = dt
|
||||
self._stop_task()
|
||||
|
|
@ -216,7 +221,7 @@ class ScriptClass(TypeClass):
|
|||
"""
|
||||
#print "unpausing", self.key, self.db._paused_time
|
||||
dt = self.db._paused_time
|
||||
if dt == None:
|
||||
if dt is None:
|
||||
return False
|
||||
try:
|
||||
self.dbobj.is_active = True
|
||||
|
|
@ -234,18 +239,23 @@ class ScriptClass(TypeClass):
|
|||
def at_script_creation(self):
|
||||
"placeholder"
|
||||
pass
|
||||
|
||||
def is_valid(self):
|
||||
"placeholder"
|
||||
pass
|
||||
|
||||
def at_start(self):
|
||||
"placeholder."
|
||||
pass
|
||||
|
||||
def at_stop(self):
|
||||
"placeholder"
|
||||
pass
|
||||
|
||||
def at_repeat(self):
|
||||
"placeholder"
|
||||
pass
|
||||
|
||||
def at_init(self):
|
||||
"called when typeclass re-caches. Usually not used for scripts."
|
||||
pass
|
||||
|
|
@ -263,8 +273,9 @@ class Script(ScriptClass):
|
|||
|
||||
def __init__(self, dbobj):
|
||||
"""
|
||||
This is the base TypeClass for all Scripts. Scripts describe events, timers and states in game,
|
||||
they can have a time component or describe a state that changes under certain conditions.
|
||||
This is the base TypeClass for all Scripts. Scripts describe events,
|
||||
timers and states in game, they can have a time component or describe
|
||||
a state that changes under certain conditions.
|
||||
|
||||
Script API:
|
||||
|
||||
|
|
@ -272,57 +283,73 @@ class Script(ScriptClass):
|
|||
|
||||
key (string) - name of object
|
||||
name (string)- same as key
|
||||
aliases (list of strings) - aliases to the object. Will be saved to database as AliasDB entries but returned as strings.
|
||||
aliases (list of strings) - aliases to the object. Will be saved to
|
||||
database as AliasDB entries but returned as strings.
|
||||
dbref (int, read-only) - unique #id-number. Also "id" can be used.
|
||||
dbobj (Object, read-only) - link to database model. dbobj.typeclass points back to this class
|
||||
typeclass (Object, read-only) - this links back to this class as an identified only. Use self.swap_typeclass() to switch.
|
||||
dbobj (Object, read-only) - link to database model. dbobj.typeclass
|
||||
points back to this class
|
||||
typeclass (Object, read-only) - this links back to this class as an
|
||||
identified only. Use self.swap_typeclass() to switch.
|
||||
date_created (string) - time stamp of object creation
|
||||
permissions (list of strings) - list of permission strings
|
||||
|
||||
desc (string) - optional description of script, shown in listings
|
||||
obj (Object) - optional object that this script is connected to and acts on (set automatically by obj.scripts.add())
|
||||
interval (int) - how often script should run, in seconds. <=0 turns off ticker
|
||||
start_delay (bool) - if the script should start repeating right away or wait self.interval seconds
|
||||
repeats (int) - how many times the script should repeat before stopping. <=0 means infinite repeats
|
||||
obj (Object) - optional object that this script is connected to
|
||||
and acts on (set automatically
|
||||
by obj.scripts.add())
|
||||
interval (int) - how often script should run, in seconds.
|
||||
<=0 turns off ticker
|
||||
start_delay (bool) - if the script should start repeating right
|
||||
away or wait self.interval seconds
|
||||
repeats (int) - how many times the script should repeat before
|
||||
stopping. <=0 means infinite repeats
|
||||
persistent (bool) - if script should survive a server shutdown or not
|
||||
is_active (bool) - if script is currently running
|
||||
|
||||
* Handlers
|
||||
|
||||
locks - lock-handler: use locks.add() to add new lock strings
|
||||
db - attribute-handler: store/retrieve database attributes on this self.db.myattr=val, val=self.db.myattr
|
||||
ndb - non-persistent attribute handler: same as db but does not create a database entry when storing data
|
||||
db - attribute-handler: store/retrieve database attributes on this
|
||||
self.db.myattr=val, val=self.db.myattr
|
||||
ndb - non-persistent attribute handler: same as db but does not
|
||||
create a database entry when storing data
|
||||
|
||||
* Helper methods
|
||||
|
||||
start() - start script (this usually happens automatically at creation and obj.script.add() etc)
|
||||
start() - start script (this usually happens automatically at creation
|
||||
and obj.script.add() etc)
|
||||
stop() - stop script, and delete it
|
||||
pause() - put the script on hold, until unpause() is called. If script is persistent, the pause state will survive a shutdown.
|
||||
unpause() - restart a previously paused script. The script will continue as if it was never paused.
|
||||
time_until_next_repeat() - if a timed script (interval>0), returns time until next tick
|
||||
pause() - put the script on hold, until unpause() is called. If script
|
||||
is persistent, the pause state will survive a shutdown.
|
||||
unpause() - restart a previously paused script. The script will
|
||||
continue as if it was never paused.
|
||||
time_until_next_repeat() - if a timed script (interval>0), returns
|
||||
time until next tick
|
||||
|
||||
* Hook methods
|
||||
|
||||
at_script_creation() - called only once, when an object of this
|
||||
class is first created.
|
||||
is_valid() - is called to check if the script is valid to be running
|
||||
at the current time. If is_valid() returns False, the running
|
||||
script is stopped and removed from the game. You can use this
|
||||
to check state changes (i.e. an script tracking some combat
|
||||
stats at regular intervals is only valid to run while there is
|
||||
actual combat going on).
|
||||
at_start() - Called every time the script is started, which for persistent
|
||||
scripts is at least once every server start. Note that this is
|
||||
unaffected by self.delay_start, which only delays the first call
|
||||
to at_repeat().
|
||||
at_repeat() - Called every self.interval seconds. It will be called immediately
|
||||
upon launch unless self.delay_start is True, which will delay
|
||||
the first call of this method by self.interval seconds. If
|
||||
self.interval<=0, this method will never be called.
|
||||
at_stop() - Called as the script object is stopped and is about to be removed from
|
||||
the game, e.g. because is_valid() returned False.
|
||||
at_server_reload() - Called when server reloads. Can be used to save temporary
|
||||
variables you want should survive a reload.
|
||||
at the current time. If is_valid() returns False, the
|
||||
running script is stopped and removed from the game. You
|
||||
can use this to check state changes (i.e. an script
|
||||
tracking some combat stats at regular intervals is only
|
||||
valid to run while there is actual combat going on).
|
||||
at_start() - Called every time the script is started, which for
|
||||
persistent scripts is at least once every server start.
|
||||
Note that this is unaffected by self.delay_start, which
|
||||
only delays the first call to at_repeat().
|
||||
at_repeat() - Called every self.interval seconds. It will be called
|
||||
immediately upon launch unless self.delay_start is True,
|
||||
which will delay the first call of this method by
|
||||
self.interval seconds. If self.interval<=0, this method
|
||||
will never be called.
|
||||
at_stop() - Called as the script object is stopped and is about to
|
||||
be removed from the game, e.g. because is_valid()
|
||||
returned False or self.stop() was called manually.
|
||||
at_server_reload() - Called when server reloads. Can be used to save
|
||||
temporary variables you want should survive a reload.
|
||||
at_server_shutdown() - called at a full server shutdown.
|
||||
|
||||
|
||||
|
|
@ -335,7 +362,7 @@ class Script(ScriptClass):
|
|||
"""
|
||||
self.key = "<unnamed>"
|
||||
self.desc = ""
|
||||
self.interval = 0 # infinite
|
||||
self.interval = 0 # infinite
|
||||
self.start_delay = False
|
||||
self.repeats = 0 # infinite
|
||||
self.persistent = False
|
||||
|
|
@ -372,29 +399,29 @@ class Script(ScriptClass):
|
|||
|
||||
def at_server_reload(self):
|
||||
"""
|
||||
This hook is called whenever the server is shutting down for restart/reboot.
|
||||
If you want to, for example, save non-persistent properties across a restart,
|
||||
this is the place to do it.
|
||||
This hook is called whenever the server is shutting down for
|
||||
restart/reboot. If you want to, for example, save non-persistent
|
||||
properties across a restart, this is the place to do it.
|
||||
"""
|
||||
pass
|
||||
|
||||
def at_server_shutdown(self):
|
||||
"""
|
||||
This hook is called whenever the server is shutting down fully (i.e. not for
|
||||
a restart).
|
||||
This hook is called whenever the server is shutting down fully
|
||||
(i.e. not for a restart).
|
||||
"""
|
||||
pass
|
||||
|
||||
|
||||
|
||||
# Some useful default Script types used by Evennia.
|
||||
|
||||
class DoNothing(Script):
|
||||
"An script that does nothing. Used as default fallback."
|
||||
def at_script_creation(self):
|
||||
"Setup the script"
|
||||
self.key = "sys_do_nothing"
|
||||
self.desc = _("This is an empty placeholder script.")
|
||||
"Setup the script"
|
||||
self.key = "sys_do_nothing"
|
||||
self.desc = _("This is an empty placeholder script.")
|
||||
|
||||
|
||||
class Store(Script):
|
||||
"Simple storage script"
|
||||
|
|
@ -403,6 +430,7 @@ class Store(Script):
|
|||
self.key = "sys_storage"
|
||||
self.desc = _("This is a generic storage container.")
|
||||
|
||||
|
||||
class CheckSessions(Script):
|
||||
"Check sessions regularly."
|
||||
def at_script_creation(self):
|
||||
|
|
@ -421,13 +449,14 @@ class CheckSessions(Script):
|
|||
#print "ValidateSessions run"
|
||||
_SESSIONS.validate_sessions()
|
||||
|
||||
|
||||
class ValidateScripts(Script):
|
||||
"Check script validation regularly"
|
||||
def at_script_creation(self):
|
||||
"Setup the script"
|
||||
self.key = "sys_scripts_validate"
|
||||
self.desc = _("Validates all scripts regularly.")
|
||||
self.interval = 3600 # validate every hour.
|
||||
self.interval = 3600 # validate every hour.
|
||||
self.persistent = True
|
||||
|
||||
def at_repeat(self):
|
||||
|
|
@ -435,13 +464,14 @@ class ValidateScripts(Script):
|
|||
#print "ValidateScripts run."
|
||||
ScriptDB.objects.validate()
|
||||
|
||||
|
||||
class ValidateChannelHandler(Script):
|
||||
"Update the channelhandler to make sure it's in sync."
|
||||
def at_script_creation(self):
|
||||
"Setup the script"
|
||||
self.key = "sys_channels_validate"
|
||||
self.desc = _("Updates the channel handler")
|
||||
self.interval = 3700 # validate a little later than ValidateScripts
|
||||
self.interval = 3700 # validate a little later than ValidateScripts
|
||||
self.persistent = True
|
||||
|
||||
def at_repeat(self):
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue