Refactor code to remove alerts as per lgtm and #1176.

This commit is contained in:
Griatch 2017-01-29 19:02:00 +01:00
parent dcde526f6d
commit 74eebfed6d
54 changed files with 226 additions and 264 deletions

View file

@ -19,8 +19,8 @@ from __future__ import print_function
# imports needed on both server and portal side
import os
from time import time
from collections import defaultdict
import time
from collections import defaultdict, namedtuple
from itertools import count
from cStringIO import StringIO
try:
@ -33,9 +33,7 @@ from twisted.internet.defer import Deferred
from evennia.utils import logger
from evennia.utils.utils import to_str, variable_from_module
class DummySession(object):
sessid = 0
DUMMYSESSION = DummySession()
DUMMYSESSION = namedtuple('DummySession', ['sessid'])(0)
# communication bits
# (chr(9) and chr(10) are \t and \n, so skipping them)
@ -350,7 +348,7 @@ class AMPProtocol(amp.AMP):
"""
self.send_batch_counter = 0
self.send_reset_time = time()
self.send_reset_time = time.time()
self.send_mode = True
self.send_task = None

View file

@ -161,13 +161,13 @@ ERROR_SETTINGS = \
1) You are not running this command from your game directory.
Change directory to your game directory and try again (or
create a new game directory using evennia --init <dirname>)
2) The settings file contains a syntax error. If you see a
2) The ettings file contains a syntax error. If you see a
traceback above, review it, resolve the problem and try again.
3) Django is not correctly installed. This usually shows as
errors mentioning 'DJANGO_SETTINGS_MODULE'. If you run a
virtual machine, it might be worth to restart it to see if
this resolves the issue.
""".format(settingsfile=SETTINGFILE, settingspath=SETTINGS_PATH)
""".format(settingspath=SETTINGS_PATH)
ERROR_INITSETTINGS = \
"""
@ -402,7 +402,6 @@ def evennia_version():
"""
version = "Unknown"
try:
import evennia
version = evennia.__version__
except ImportError:
# even if evennia is not found, we should not crash here.
@ -594,7 +593,6 @@ def check_database():
tables = [tableinfo.name for tableinfo in tables]
if tables and u'players_playerdb' in tables:
# database exists and seems set up. Initialize evennia.
import evennia
evennia._init()
# Try to get Player#1
from evennia.players.models import PlayerDB
@ -668,6 +666,7 @@ def get_pid(pidfile):
with open(pidfile, 'r') as f:
pid = f.read()
return pid
return None
def del_pid(pidfile):
@ -684,7 +683,7 @@ def del_pid(pidfile):
os.remove(pidfile)
def kill(pidfile, signal=SIG, succmsg="", errmsg="",
def kill(pidfile, killsignal=SIG, succmsg="", errmsg="",
restart_file=SERVER_RESTART, restart=False):
"""
Send a kill signal to a process based on PID. A customized
@ -693,7 +692,7 @@ def kill(pidfile, signal=SIG, succmsg="", errmsg="",
Args:
pidfile (str): The path of the pidfile to get the PID from.
signal (int, optional): Signal identifier.
killsignal (int, optional): Signal identifier for signal to send.
succmsg (str, optional): Message to log on success.
errmsg (str, optional): Message to log on failure.
restart_file (str, optional): Restart file location.
@ -728,7 +727,7 @@ def kill(pidfile, signal=SIG, succmsg="", errmsg="",
else:
# Linux can send the SIGINT signal directly
# to the specified PID.
os.kill(int(pid), signal)
os.kill(int(pid), killsignal)
except OSError:
print("Process %(pid)s cannot be stopped. "\
@ -751,10 +750,8 @@ def show_version_info(about=False):
version_info (str): A complete version info string.
"""
import os
import sys
import twisted
import django
return VERSION_INFO.format(
version=EVENNIA_VERSION, about=ABOUT_INFO if about else "",

View file

@ -56,28 +56,28 @@ def text(session, *args, **kwargs):
#from evennia.server.profiling.timetrace import timetrace
#text = timetrace(text, "ServerSession.data_in")
text = args[0] if args else None
txt = args[0] if args else None
#explicitly check for None since text can be an empty string, which is
#also valid
if text is None:
if txt is None:
return
# this is treated as a command input
# handle the 'idle' command
if text.strip() in _IDLE_COMMAND:
if txt.strip() in _IDLE_COMMAND:
session.update_session_counters(idle=True)
return
if session.player:
# nick replacement
puppet = session.puppet
if puppet:
text = puppet.nicks.nickreplace(text,
txt = puppet.nicks.nickreplace(txt,
categories=("inputline", "channel"), include_player=True)
else:
text = session.player.nicks.nickreplace(text,
txt = session.player.nicks.nickreplace(txt,
categories=("inputline", "channel"), include_player=False)
kwargs.pop("options", None)
cmdhandler(session, text, callertype="session", session=session, **kwargs)
cmdhandler(session, txt, callertype="session", session=session, **kwargs)
session.update_session_counters()
@ -92,20 +92,20 @@ def bot_data_in(session, *args, **kwargs):
"""
text = args[0] if args else None
txt = args[0] if args else None
# Explicitly check for None since text can be an empty string, which is
# also valid
if text is None:
if txt is None:
return
# this is treated as a command input
# handle the 'idle' command
if text.strip() in _IDLE_COMMAND:
if txt.strip() in _IDLE_COMMAND:
session.update_session_counters(idle=True)
return
kwargs.pop("options", None)
# Trigger the execute_cmd method of the corresponding bot.
session.player.execute_cmd(text=text, session=session)
session.player.execute_cmd(text=txt, session=session)
session.update_session_counters()

View file

@ -49,4 +49,4 @@ class ServerConfigManager(models.Manager):
if not conf:
return default
return conf[0].value
return None

View file

@ -70,7 +70,6 @@ class Mssp(object):
"""
self.protocol.handshake_done()
pass
def do_mssp(self, option):
"""

View file

@ -350,7 +350,6 @@ for plugin_module in PORTAL_SERVICES_PLUGIN_MODULES:
print('-' * 50) # end of terminal output
if os.name == 'nt':
factory.noisy = False
# Windows only: Set PID file manually
with open(PORTAL_PIDFILE, 'w') as f:
f.write(str(os.getpid()))

View file

@ -4,8 +4,8 @@ Sessionhandler for portal sessions
from __future__ import print_function
from __future__ import division
from time import time
from collections import deque
import time
from collections import deque, namedtuple
from twisted.internet import reactor
from django.conf import settings
from evennia.server.sessionhandler import SessionHandler, PCONN, PDISCONN, \
@ -26,9 +26,7 @@ _ERROR_MAX_CHAR = settings.MAX_CHAR_LIMIT_WARNING
_CONNECTION_QUEUE = deque()
class DummySession(object):
sessid = 0
DUMMYSESSION = DummySession()
DUMMYSESSION = namedtuple('DummySession', ['sessid'])(0)
#------------------------------------------------------------
# Portal-SessionHandler class
@ -53,13 +51,13 @@ class PortalSessionHandler(SessionHandler):
super(PortalSessionHandler, self).__init__(*args, **kwargs)
self.portal = None
self.latest_sessid = 0
self.uptime = time()
self.uptime = time.time()
self.connection_time = 0
self.connection_last = time()
self.connection_last = self.uptime
self.connection_task = None
self.command_counter = 0
self.command_counter_reset = time()
self.command_counter_reset = self.uptime
self.command_overflow = False
def at_server_connection(self):
@ -68,7 +66,7 @@ class PortalSessionHandler(SessionHandler):
At this point, the AMP connection is already established.
"""
self.connection_time = time()
self.connection_time = time.time()
def connect(self, session):
"""
@ -98,7 +96,7 @@ class PortalSessionHandler(SessionHandler):
session.data_out(text=[["%s DoS protection is active. You are queued to connect in %g seconds ..." % (
settings.SERVERNAME,
len(_CONNECTION_QUEUE)*_MIN_TIME_BETWEEN_CONNECTS)],{}])
now = time()
now = time.time()
if (now - self.connection_last < _MIN_TIME_BETWEEN_CONNECTS) or not self.portal.amp_protocol:
if not session or not self.connection_task:
self.connection_task = reactor.callLater(_MIN_TIME_BETWEEN_CONNECTS, self.connect, None)
@ -257,7 +255,7 @@ class PortalSessionHandler(SessionHandler):
for session in self.values():
session.disconnect(reason)
del session
self = {}
self.clear()
def server_logged_in(self, session, data):
"""
@ -366,7 +364,7 @@ class PortalSessionHandler(SessionHandler):
# if there is a problem to send, we continue
pass
if session:
now = time()
now = time.time()
if self.command_counter > _MAX_COMMAND_RATE:
# data throttle (anti DoS measure)
dT = now - self.command_counter_reset

View file

@ -10,13 +10,13 @@ import sys
try:
import OpenSSL
from twisted.internet import ssl as twisted_ssl
except ImportError as err:
except ImportError as error:
errstr = """
{err}
SSL requires the PyOpenSSL library:
pip install pyopenssl
"""
raise ImportError(errstr.format(err=err))
raise ImportError(errstr.format(err=error))
from django.conf import settings
from evennia.server.portal.telnet import TelnetProtocol

View file

@ -184,7 +184,6 @@ class TelnetOOB(object):
msdp_args += "{msdp_array_open}" \
"{msdp_args}" \
"{msdp_array_close}".format(
msdp_var=MSDP_VAR,
msdp_array_open=MSDP_ARRAY_OPEN,
msdp_array_close=MSDP_ARRAY_CLOSE,
msdp_args= "".join("%s%s" % (

View file

@ -18,8 +18,8 @@ http://localhost:8000/webclient.)
"""
import json
import re
import time
from time import time
from twisted.web import server, resource
from twisted.internet.task import LoopingCall
from django.utils.functional import Promise
@ -83,7 +83,7 @@ class WebClient(resource.Resource):
"""
Callback for checking the connection is still alive.
"""
now = time()
now = time.time()
to_remove = []
keep_alives = ((csessid, remove) for csessid, (t, remove)
in self.last_alive.iteritems() if now - t > _KEEPALIVE)
@ -170,7 +170,7 @@ class WebClient(resource.Resource):
sess.sessionhandler.connect(sess)
self.last_alive[csessid] = (time(), False)
self.last_alive[csessid] = (time.time(), False)
if not self.keep_alive:
# the keepalive is not running; start it.
self.keep_alive = LoopingCall(self._keepalive)
@ -184,7 +184,7 @@ class WebClient(resource.Resource):
client is replying to the keepalive.
"""
csessid = request.args.get('csessid')[0]
self.last_alive[csessid] = (time(), False)
self.last_alive[csessid] = (time.time(), False)
return '""'
def mode_input(self, request):
@ -198,7 +198,7 @@ class WebClient(resource.Resource):
"""
csessid = request.args.get('csessid')[0]
self.last_alive[csessid] = (time(), False)
self.last_alive[csessid] = (time.time(), False)
sess = self.sessionhandler.sessions_from_csessid(csessid)
if sess:
sess = sess[0]
@ -218,7 +218,7 @@ class WebClient(resource.Resource):
"""
csessid = request.args.get('csessid')[0]
self.last_alive[csessid] = (time(), False)
self.last_alive[csessid] = (time.time(), False)
dataentries = self.databuffer.get(csessid, [])
if dataentries:
@ -244,7 +244,6 @@ class WebClient(resource.Resource):
sess.sessionhandler.disconnect(sess)
except IndexError:
self.client_disconnect(csessid)
pass
return '""'
def render_POST(self, request):

View file

@ -2,7 +2,7 @@
Trace a message through the messaging system
"""
from __future__ import print_function
from time import time
import time
def timetrace(message, idstring, tracemessage="TEST_MESSAGE", final=False):
"""
@ -24,11 +24,11 @@ def timetrace(message, idstring, tracemessage="TEST_MESSAGE", final=False):
prefix, tlast, t0 = message.split(None, 2)
tlast, t0 = float(tlast), float(t0)
except (IndexError, ValueError):
t0 = time()
t0 = time.time()
tlast = t0
t1 = t0
else:
t1 = time()
t1 = time.time()
# print to log (important!)
print("** timetrace (%s): dT=%fs, total=%fs." % (idstring, t1-tlast, t1-t0))

View file

@ -8,10 +8,9 @@ are stored on the Portal side)
"""
from builtins import object
import re
import weakref
import importlib
from time import time
import time
from django.utils import timezone
from django.conf import settings
from evennia.comms.models import ChannelDB
@ -218,7 +217,7 @@ class ServerSession(Session):
self.uid = self.player.id
self.uname = self.player.username
self.logged_in = True
self.conn_time = time()
self.conn_time = time.time()
self.puid = None
self.puppet = None
self.cmdset_storage = settings.CMDSET_SESSION
@ -332,7 +331,7 @@ class ServerSession(Session):
"""
# Idle time used for timeout calcs.
self.cmd_last = time()
self.cmd_last = time.time()
# Store the timestamp of the user's last command.
if not idle:
@ -508,7 +507,7 @@ class ServerSession(Session):
"""
string = "Cannot assign directly to ndb object! "
string = "Use ndb.attr=value instead."
string += "Use ndb.attr=value instead."
raise Exception(string)
#@ndb.deleter

View file

@ -12,10 +12,10 @@ There are two similar but separate stores of sessions:
handle network communication but holds no game info.
"""
import time
from builtins import object
from future.utils import listvalues
from time import time
from django.conf import settings
from evennia.commands.cmdhandler import CMD_LOGINSTART
from evennia.utils.logger import log_trace
@ -89,7 +89,10 @@ def delayed_import():
if not _ScriptDB:
from evennia.scripts.models import ScriptDB as _ScriptDB
# including once to avoid warnings in Python syntax checkers
_ServerSession, _PlayerDB, _ServerConfig, _ScriptDB
assert(_ServerSession)
assert(_PlayerDB)
assert(_ServerConfig)
assert(_ScriptDB)
#-----------------------------------------------------------
@ -565,7 +568,7 @@ class ServerSessionHandler(SessionHandler):
see if any are dead or idle.
"""
tcurr = time()
tcurr = time.time()
reason = _("Idle timeout exceeded, disconnecting.")
for session in (session for session in self.values()
if session.logged_in and _IDLE_TIMEOUT > 0