py2to3 automatic conversion. Woot!

This commit is contained in:
Ryan Holmes
2017-06-12 16:12:45 -04:00
parent ad535ccc78
commit 828b18d0fd
147 changed files with 1017 additions and 783 deletions

View File

@@ -32,7 +32,7 @@ class Attribute(object):
@staticmethod
def getAttributeInfo(identity):
if isinstance(identity, (int, basestring)):
if isinstance(identity, (int, str)):
info = eos.db.getAttributeInfo(identity, eager=("icon", "unit"))
elif isinstance(identity, (int, float)):
id_ = int(identity)

View File

@@ -95,7 +95,7 @@ class CharacterImportThread(threading.Thread):
)
char = sCharacter.new(name + " (EVEMon)")
sCharacter.apiUpdateCharSheet(char.ID, skills, securitystatus)
except Exception, e:
except Exception as e:
pyfalog.error("Exception on character import:")
pyfalog.error(e)
continue
@@ -147,18 +147,18 @@ class Character(object):
self.all5()
def exportText(self):
data = u"Pyfa exported plan for \"" + self.skillReqsDict['charname'] + "\"\n"
data += u"=" * 79 + u"\n"
data += u"\n"
item = u""
data = "Pyfa exported plan for \"" + self.skillReqsDict['charname'] + "\"\n"
data += "=" * 79 + "\n"
data += "\n"
item = ""
try:
for s in self.skillReqsDict['skills']:
if item == "" or not item == s["item"]:
item = s["item"]
data += u"-" * 79 + "\n"
data += u"Skills required for {}:\n".format(item)
data += u"{}{}: {}\n".format(" " * s["indent"], s["skill"], int(s["level"]))
data += u"-" * 79 + "\n"
data += "-" * 79 + "\n"
data += "Skills required for {}:\n".format(item)
data += "{}{}: {}\n".format(" " * s["indent"], s["skill"], int(s["level"]))
data += "-" * 79 + "\n"
except Exception:
pass
@@ -365,7 +365,7 @@ class Character(object):
api = EVEAPIConnection()
auth = api.auth(keyID=userID, vCode=apiKey)
apiResult = auth.account.Characters()
charList = map(lambda c: unicode(c.name), apiResult.characters)
charList = [str(c.name) for c in apiResult.characters]
char.chars = json.dumps(charList)
return charList
@@ -392,7 +392,7 @@ class Character(object):
if ifHigher and level < skill.level:
return
if isinstance(level, basestring) or level > 5 or level < 0:
if isinstance(level, str) or level > 5 or level < 0:
skill.setLevel(None, persist)
else:
skill.setLevel(level, persist)
@@ -456,7 +456,7 @@ class Character(object):
return reqs
def _checkRequirements(self, fit, char, subThing, reqs):
for req, level in subThing.requiredSkills.iteritems():
for req, level in subThing.requiredSkills.items():
name = req.name
ID = req.ID
info = reqs.get(name)

View File

@@ -94,7 +94,7 @@ class DamagePattern(object):
def exportPatterns(self):
patterns = self.getDamagePatternList()
for i in xrange(len(patterns) - 1, -1, -1):
for i in range(len(patterns) - 1, -1, -1):
if patterns[i].name in ("Uniform", "Selected Ammo"):
del patterns[i]

View File

@@ -159,7 +159,7 @@
# -----------------------------------------------------------------------------
import urlparse
import urllib.parse
import copy
from xml.parsers import expat
@@ -200,7 +200,7 @@ class Error(Exception):
self.args = (message.rstrip("."),)
def __unicode__(self):
return u'%s [code=%s]' % (self.args[0], self.code)
return '%s [code=%s]' % (self.args[0], self.code)
class RequestError(Error):
@@ -255,7 +255,7 @@ def EVEAPIConnection(url="api.eveonline.com", cacheHandler=None, proxy=None, pro
if not url.startswith("http"):
url = "https://" + url
p = urlparse.urlparse(url, "https")
p = urllib.parse.urlparse(url, "https")
if p.path and p.path[-1] == "/":
p.path = p.path[:-1]
ctx = _RootContext(None, p.path, {}, {})
@@ -279,7 +279,7 @@ def _ParseXML(response, fromContext, storeFunc):
if fromContext and isinstance(response, Element):
obj = response
elif type(response) in (str, unicode):
elif type(response) in (str, str):
obj = _Parser().Parse(response, False)
elif hasattr(response, "read"):
obj = _Parser().Parse(response, True)
@@ -349,7 +349,7 @@ class _Context(object):
def __call__(self, **kw):
if kw:
# specified keywords override contextual ones
for k, v in self.parameters.iteritems():
for k, v in self.parameters.items():
if k not in kw:
kw[k] = v
else:
@@ -383,7 +383,7 @@ class _RootContext(_Context):
def __call__(self, path, **kw):
# convert list type arguments to something the API likes
for k, v in kw.iteritems():
for k, v in kw.items():
if isinstance(v, _listtypes):
kw[k] = ','.join(map(str, list(v)))
@@ -567,7 +567,7 @@ class _Parser(object):
# the row data contains more attributes than were defined.
self.container._cols = attributes[0::2]
self.container.append(
[_castfunc(attributes[i], attributes[i + 1]) for i in xrange(0, len(attributes), 2)]
[_castfunc(attributes[i], attributes[i + 1]) for i in range(0, len(attributes), 2)]
)
# </hack>
@@ -658,7 +658,7 @@ class _Parser(object):
e = Element()
e._name = this._name
setattr(self.container, this._name, e)
for i in xrange(0, len(attributes), 2):
for i in range(0, len(attributes), 2):
setattr(e, attributes[i], attributes[i + 1])
else:
# tag of the form: <tag />, treat as empty string.
@@ -671,7 +671,7 @@ class _Parser(object):
# multiples of some tag or attribute. Code below handles this case.
elif isinstance(sibling, Rowset):
# its doppelganger is a rowset, append this as a row to that.
row = [_castfunc(attributes[i], attributes[i + 1]) for i in xrange(0, len(attributes), 2)]
row = [_castfunc(attributes[i], attributes[i + 1]) for i in range(0, len(attributes), 2)]
row.extend([getattr(this, col) for col in attributes2])
sibling.append(row)
elif isinstance(sibling, Element):
@@ -680,13 +680,13 @@ class _Parser(object):
# into a Rowset, adding the sibling element and this one.
rs = Rowset()
rs.__catch = rs._name = this._name
row = [_castfunc(attributes[i], attributes[i + 1]) for i in xrange(0, len(attributes), 2)] + \
row = [_castfunc(attributes[i], attributes[i + 1]) for i in range(0, len(attributes), 2)] + \
[getattr(this, col) for col in attributes2]
rs.append(row)
row = [getattr(sibling, attributes[i]) for i in xrange(0, len(attributes), 2)] + \
row = [getattr(sibling, attributes[i]) for i in range(0, len(attributes), 2)] + \
[getattr(sibling, col) for col in attributes2]
rs.append(row)
rs._cols = [attributes[i] for i in xrange(0, len(attributes), 2)] + [col for col in attributes2]
rs._cols = [attributes[i] for i in range(0, len(attributes), 2)] + [col for col in attributes2]
setattr(self.container, this._name, rs)
else:
# something else must have set this attribute already.
@@ -694,7 +694,7 @@ class _Parser(object):
pass
# Now fix up the attributes and be done with it.
for i in xrange(0, len(attributes), 2):
for i in range(0, len(attributes), 2):
this.__dict__[attributes[i]] = _castfunc(attributes[i], attributes[i + 1])
return
@@ -719,7 +719,7 @@ class Element(object):
return "<Element '%s'>" % self._name
_fmt = u"%s:%s".__mod__
_fmt = "%s:%s".__mod__
class Row(object):
@@ -734,7 +734,7 @@ class Row(object):
self._cols = cols or []
self._row = row or []
def __nonzero__(self):
def __bool__(self):
return True
def __ne__(self, other):
@@ -770,7 +770,7 @@ class Row(object):
return self._row[self._cols.index(this)]
def __str__(self):
return "Row(" + ','.join(map(_fmt, zip(self._cols, self._row))) + ")"
return "Row(" + ','.join(map(_fmt, list(zip(self._cols, self._row)))) + ")"
class Rowset(object):
@@ -829,7 +829,7 @@ class Rowset(object):
for line in self._rows:
yield line[i]
else:
i = map(self._cols.index, columns)
i = list(map(self._cols.index, columns))
if options.get("row", False):
for line in self._rows:
yield line, [line[x] for x in i]
@@ -857,7 +857,7 @@ class Rowset(object):
self._rows += other._rows
raise TypeError("rowset instance expected")
def __nonzero__(self):
def __bool__(self):
return not not self._rows
def __len__(self):

View File

@@ -141,7 +141,7 @@ class Fit(object):
except ValueError:
ship = es_Citadel(eos.db.getItem(shipID))
fit = FitType(ship)
fit.name = name if name is not None else u"New %s" % fit.ship.item.name
fit.name = name if name is not None else "New %s" % fit.ship.item.name
fit.damagePattern = self.pattern
fit.targetResists = self.targetResists
fit.character = self.character
@@ -177,11 +177,11 @@ class Fit(object):
# it will be refreshed first during the projected loop and throw an
# error during the command loop
refreshFits = set()
for projection in fit.projectedOnto.values():
for projection in list(fit.projectedOnto.values()):
if projection.victim_fit != fit and projection.victim_fit in eos.db.saveddata_session: # GH issue #359
refreshFits.add(projection.victim_fit)
for booster in fit.boostedOnto.values():
for booster in list(fit.boostedOnto.values()):
if booster.boosted_fit != fit and booster.boosted_fit in eos.db.saveddata_session: # GH issue #359
refreshFits.add(booster.boosted_fit)
@@ -779,7 +779,7 @@ class Fit(object):
total = fit.getNumSlots(fighter.slot)
standardAttackActive = False
for ability in fighter.abilities:
if ability.effect.isImplemented and ability.effect.handlerName == u'fighterabilityattackm':
if ability.effect.isImplemented and ability.effect.handlerName == 'fighterabilityattackm':
# Activate "standard attack" if available
ability.active = True
standardAttackActive = True
@@ -787,8 +787,8 @@ class Fit(object):
# Activate all other abilities (Neut, Web, etc) except propmods if no standard attack is active
if ability.effect.isImplemented and \
standardAttackActive is False and \
ability.effect.handlerName != u'fighterabilitymicrowarpdrive' and \
ability.effect.handlerName != u'fighterabilityevasivemaneuvers':
ability.effect.handlerName != 'fighterabilitymicrowarpdrive' and \
ability.effect.handlerName != 'fighterabilityevasivemaneuvers':
ability.active = True
if used >= total:
@@ -1194,7 +1194,7 @@ class Fit(object):
def recalc(self, fit):
start_time = time()
pyfalog.info(u"=" * 10 + u"recalc: {0}" + u"=" * 10, fit.name)
pyfalog.info("=" * 10 + "recalc: {0}" + "=" * 10, fit.name)
if fit.factorReload is not self.serviceFittingOptions["useGlobalForceReload"]:
fit.factorReload = self.serviceFittingOptions["useGlobalForceReload"]
fit.clear()

View File

@@ -20,7 +20,7 @@
import re
import threading
from logbook import Logger
import Queue
import queue
# noinspection PyPackageRequirements
import wx
@@ -53,7 +53,7 @@ class ShipBrowserWorkerThread(threading.Thread):
self.name = "ShipBrowser"
def run(self):
self.queue = Queue.Queue()
self.queue = queue.Queue()
self.cache = {}
# Wait for full market initialization (otherwise there's high risky
# this thread will attempt to init Market which is already being inited)
@@ -261,7 +261,7 @@ class Market(object):
}
# Parent type name: set(item names)
self.ITEMS_FORCEDMETAGROUP_R = {}
for item, value in self.ITEMS_FORCEDMETAGROUP.items():
for item, value in list(self.ITEMS_FORCEDMETAGROUP.items()):
parent = value[1]
if parent not in self.ITEMS_FORCEDMETAGROUP_R:
self.ITEMS_FORCEDMETAGROUP_R[parent] = set()
@@ -372,7 +372,7 @@ class Market(object):
def __makeRevDict(orig):
"""Creates reverse dictionary"""
rev = {}
for item, value in orig.items():
for item, value in list(orig.items()):
if value not in rev:
rev[value] = set()
rev[value].add(item)
@@ -386,7 +386,7 @@ class Market(object):
item = identity
elif isinstance(identity, int):
item = eos.db.getItem(identity, *args, **kwargs)
elif isinstance(identity, basestring):
elif isinstance(identity, str):
# We normally lookup with string when we are using import/export
# features. Check against overrides
identity = conversions.all.get(identity, identity)
@@ -407,7 +407,7 @@ class Market(object):
"""Get group by its ID or name"""
if isinstance(identity, types_Group):
return identity
elif isinstance(identity, (int, float, basestring)):
elif isinstance(identity, (int, float, str)):
if isinstance(identity, float):
identity = int(identity)
# Check custom groups
@@ -426,7 +426,7 @@ class Market(object):
"""Get category by its ID or name"""
if isinstance(identity, types_Category):
category = identity
elif isinstance(identity, (int, basestring)):
elif isinstance(identity, (int, str)):
category = eos.db.getCategory(identity, *args, **kwargs)
elif isinstance(identity, float):
id_ = int(identity)
@@ -440,7 +440,7 @@ class Market(object):
"""Get meta group by its ID or name"""
if isinstance(identity, types_MetaGroup):
metaGroup = identity
elif isinstance(identity, (int, basestring)):
elif isinstance(identity, (int, str)):
metaGroup = eos.db.getMetaGroup(identity, *args, **kwargs)
elif isinstance(identity, float):
id_ = int(identity)
@@ -606,7 +606,7 @@ class Market(object):
def getGroupsByCategory(self, cat):
"""Get groups from given category"""
groups = set(filter(lambda grp: self.getPublicityByGroup(grp), cat.groups))
groups = set([grp for grp in cat.groups if self.getPublicityByGroup(grp)])
return groups
@@ -626,7 +626,7 @@ class Market(object):
if hasattr(group, 'addItems'):
groupItems.update(group.addItems)
items = set(
filter(lambda item: self.getPublicityByItem(item) and self.getGroupByItem(item) == group, groupItems))
[item for item in groupItems if self.getPublicityByItem(item) and self.getGroupByItem(item) == group])
return items
def getItemsByMarketGroup(self, mg, vars_=True):
@@ -656,7 +656,7 @@ class Market(object):
else:
result = baseitms
# Get rid of unpublished items
result = set(filter(lambda item_: self.getPublicityByItem(item_), result))
result = set([item_ for item_ in result if self.getPublicityByItem(item_)])
return result
def marketGroupHasTypesCheck(self, mg):
@@ -783,11 +783,11 @@ class Market(object):
@staticmethod
def directAttrRequest(items, attribs):
try:
itemIDs = tuple(map(lambda i: i.ID, items))
itemIDs = tuple([i.ID for i in items])
except TypeError:
itemIDs = (items.ID,)
try:
attrIDs = tuple(map(lambda i: i.ID, attribs))
attrIDs = tuple([i.ID for i in attribs])
except TypeError:
attrIDs = (attribs.ID,)
info = {}
@@ -803,7 +803,7 @@ class Market(object):
def filterItemsByMeta(self, items, metas):
"""Filter items by meta lvl"""
filtered = set(filter(lambda item: self.getMetaGroupIdByItem(item) in metas, items))
filtered = set([item for item in items if self.getMetaGroupIdByItem(item) in metas])
return filtered
def getSystemWideEffects(self):

View File

@@ -18,8 +18,8 @@
# =============================================================================
import urllib2
import urllib
import urllib.request, urllib.error, urllib.parse
import urllib.request, urllib.parse, urllib.error
import socket
from logbook import Logger
@@ -33,24 +33,24 @@ timeout = 3
socket.setdefaulttimeout(timeout)
class Error(StandardError):
class Error(Exception):
def __init__(self, msg=None):
self.message = msg
class RequestError(StandardError):
class RequestError(Exception):
pass
class AuthenticationError(StandardError):
class AuthenticationError(Exception):
pass
class ServerError(StandardError):
class ServerError(Exception):
pass
class TimeoutError(StandardError):
class TimeoutError(Exception):
pass
@@ -94,29 +94,29 @@ class Network(object):
# proxy_auth is a tuple of (login, password) or None
if proxy_auth is not None:
# add login:password@ in front of proxy address
proxy_handler = urllib2.ProxyHandler({
proxy_handler = urllib.request.ProxyHandler({
'https': '{0}:{1}@{2}:{3}'.format(
proxy_auth[0], proxy_auth[1], proxy[0], proxy[1])
})
else:
# build proxy handler with no login/pass info
proxy_handler = urllib2.ProxyHandler({'https': "{0}:{1}".format(proxy[0], proxy[1])})
opener = urllib2.build_opener(proxy_handler)
urllib2.install_opener(opener)
proxy_handler = urllib.request.ProxyHandler({'https': "{0}:{1}".format(proxy[0], proxy[1])})
opener = urllib.request.build_opener(proxy_handler)
urllib.request.install_opener(opener)
else:
# This is a bug fix, explicitly disable possibly previously installed
# opener with proxy, by urllib2.install_opener() a few lines above in code.
# Now this explicitly disables proxy handler, "uninstalling" opener.
# This is used in case when user had proxy enabled, so proxy_handler was already
# installed globally, and then user had disabled the proxy, so we should clear that opener
urllib2.install_opener(None)
urllib.request.install_opener(None)
# another option could be installing a default opener:
# urllib2.install_opener(urllib2.build_opener())
request = urllib2.Request(url, headers=headers, data=urllib.urlencode(data) if data else None)
request = urllib.request.Request(url, headers=headers, data=urllib.parse.urlencode(data) if data else None)
try:
return urllib2.urlopen(request)
except urllib2.HTTPError as error:
return urllib.request.urlopen(request)
except urllib.error.HTTPError as error:
pyfalog.warning("HTTPError:")
pyfalog.warning(error)
if error.code == 404:
@@ -125,7 +125,7 @@ class Network(object):
raise AuthenticationError()
elif error.code >= 500:
raise ServerError()
except urllib2.URLError as error:
except urllib.error.URLError as error:
pyfalog.warning("Timed out or other URL error:")
pyfalog.warning(error)
if "timed out" in error.reason:

View File

@@ -169,9 +169,7 @@ class UserCancelException(Exception):
pass
class IPortUser:
__metaclass__ = ABCMeta
class IPortUser(metaclass=ABCMeta):
ID_PULSE = 1
# Pulse the progress bar
@@ -316,7 +314,7 @@ class Port(object):
for page in attempt_codecs:
try:
pyfalog.info("Attempting to decode file {0} using {1} page.", path, page)
srcString = unicode(srcString, page)
srcString = str(srcString, page)
codec_found = page
pyfalog.info("File {0} decoded using {1} page.", path, page)
except UnicodeDecodeError:
@@ -325,7 +323,7 @@ class Port(object):
break
else:
pyfalog.info("Unicode BOM detected in {0}, using {1} page.", path, codec_found)
srcString = unicode(srcString[len(savebom):], codec_found)
srcString = str(srcString[len(savebom):], codec_found)
else:
# nasty hack to detect other transparent utf-16 loading
@@ -453,7 +451,7 @@ class Port(object):
item['type']['name'] = ''
fit['items'].append(item)
for chargeID, amount in charges.items():
for chargeID, amount in list(charges.items()):
item = nested_dict()
item['flag'] = INV_FLAG_CARGOBAY
item['quantity'] = amount
@@ -588,7 +586,7 @@ class Port(object):
def importDna(string):
sMkt = Market.getInstance()
ids = map(int, re.findall(r'\d+', string))
ids = list(map(int, re.findall(r'\d+', string)))
for id_ in ids:
try:
try:
@@ -642,7 +640,7 @@ class Port(object):
c.amount = int(amount)
f.cargo.append(c)
else:
for i in xrange(int(amount)):
for i in range(int(amount)):
try:
m = Module(item)
except:
@@ -834,7 +832,7 @@ class Port(object):
# If client didn't take care of encoding file contents into Unicode,
# do it using fallback encoding ourselves
if isinstance(contents, str):
contents = unicode(contents, locale.getpreferredencoding())
contents = str(contents, locale.getpreferredencoding())
fits = [] # List for fits
fitIndices = [] # List for starting line numbers for each fit
@@ -1114,7 +1112,7 @@ class Port(object):
also, it's OK to arrange modules randomly?
"""
offineSuffix = " /OFFLINE"
export = u"[%s, %s]\n" % (fit.ship.item.name, fit.name)
export = "[%s, %s]\n" % (fit.ship.item.name, fit.name)
stuff = {}
sFit = svcFit.getInstance()
for module in fit.modules:
@@ -1324,7 +1322,7 @@ class Port(object):
charges[cargo.item.name] = 0
charges[cargo.item.name] += cargo.amount
for name, qty in charges.items():
for name, qty in list(charges.items()):
hardware = doc.createElement("hardware")
hardware.setAttribute("qty", "%d" % qty)
hardware.setAttribute("slot", "cargo")

View File

@@ -20,7 +20,7 @@
import time
import threading
import Queue
import queue
from xml.dom import minidom
from logbook import Logger
@@ -134,7 +134,7 @@ class Price(object):
except TimeoutError:
# Timeout error deserves special treatment
pyfalog.warning("Price fetch timout")
for typeID in priceMap.keys():
for typeID in list(priceMap.keys()):
priceobj = priceMap[typeID]
priceobj.time = time.time() + TIMEOUT
priceobj.failed = True
@@ -146,7 +146,7 @@ class Price(object):
pass
# if we get to this point, then we've got an error. Set to REREQUEST delay
for typeID in priceMap.keys():
for typeID in list(priceMap.keys()):
priceobj = priceMap[typeID]
priceobj.time = time.time() + REREQUEST
priceobj.failed = True
@@ -215,7 +215,7 @@ class PriceWorkerThread(threading.Thread):
def __init__(self):
threading.Thread.__init__(self)
self.name = "PriceWorker"
self.queue = Queue.Queue()
self.queue = queue.Queue()
self.wait = {}
pyfalog.debug("Initialize PriceWorkerThread.")

View File

@@ -7,8 +7,8 @@ if PY3: # pragma: no cover
text_type = str
binary_type = bytes
else: # pragma: no cover
string_types = basestring,
text_type = unicode
string_types = str,
text_type = str
binary_type = str

View File

@@ -12,13 +12,13 @@ import config
from service.pycrest.compat import bytes_, text_
from service.pycrest.errors import APIException
from urlparse import urlparse, urlunparse, parse_qsl
from urllib.parse import urlparse, urlunparse, parse_qsl
try:
import pickle
except ImportError: # pragma: no cover
# noinspection PyPep8Naming
import cPickle as pickle
import pickle as pickle
pyfalog = Logger(__name__)
cache_re = re.compile(r'max-age=([0-9]+)')
@@ -136,7 +136,7 @@ class APIConnection(object):
prms[key] = params[key]
# check cache
key = (resource, frozenset(self._session.headers.items()), frozenset(prms.items()))
key = (resource, frozenset(list(self._session.headers.items())), frozenset(list(prms.items())))
cached = self.cache.get(key)
if cached and cached['cached_until'] > time.time():
pyfalog.debug('Cache hit for resource {0} (params={1})', resource, prms)
@@ -280,7 +280,7 @@ class APIObject(object):
def __init__(self, parent, connection):
self._dict = {}
self.connection = connection
for k, v in parent.items():
for k, v in list(parent.items()):
if type(v) is dict:
self._dict[k] = APIObject(v, connection)
elif type(v) is list:

View File

@@ -1,5 +1,5 @@
import BaseHTTPServer
import urlparse
import http.server
import urllib.parse
import socket
import threading
from logbook import Logger
@@ -68,13 +68,13 @@ if (window.location.href.indexOf('step=2') == -1) {{
# https://github.com/fuzzysteve/CREST-Market-Downloader/
class AuthHandler(BaseHTTPServer.BaseHTTPRequestHandler):
class AuthHandler(http.server.BaseHTTPRequestHandler):
def do_GET(self):
if self.path == "/favicon.ico":
return
parsed_path = urlparse.urlparse(self.path)
parts = urlparse.parse_qs(parsed_path.query)
parsed_path = urllib.parse.urlparse(self.path)
parts = urllib.parse.parse_qs(parsed_path.query)
msg = ""
step2 = 'step' in parts
@@ -88,7 +88,7 @@ class AuthHandler(BaseHTTPServer.BaseHTTPRequestHandler):
# For implicit mode, we have to serve up the page which will take the hash and redirect useing a querystring
pyfalog.info("Processing response from EVE Online.")
msg = "Processing response from EVE Online"
except Exception, ex:
except Exception as ex:
pyfalog.error("Error in CREST AuthHandler")
pyfalog.error(ex)
msg = "<h2>Error</h2>\n<p>{}</p>".format(ex.message)
@@ -106,9 +106,9 @@ class AuthHandler(BaseHTTPServer.BaseHTTPRequestHandler):
# http://code.activestate.com/recipes/425210-simple-stoppable-server-using-socket-timeout/
class StoppableHTTPServer(BaseHTTPServer.HTTPServer):
class StoppableHTTPServer(http.server.HTTPServer):
def server_bind(self):
BaseHTTPServer.HTTPServer.server_bind(self)
http.server.HTTPServer.server_bind(self)
self.settings = CRESTSettings.getInstance()
# Allow listening for x seconds
@@ -156,5 +156,5 @@ class StoppableHTTPServer(BaseHTTPServer.HTTPServer):
if __name__ == "__main__":
httpd = StoppableHTTPServer(('', 6461), AuthHandler)
t = threading.Thread(target=httpd.serve)
raw_input("Press <RETURN> to stop server\n")
input("Press <RETURN> to stop server\n")
httpd.stop()

View File

@@ -17,9 +17,9 @@
# along with pyfa. If not, see <http://www.gnu.org/licenses/>.
# =============================================================================
import cPickle
import pickle
import os.path
import urllib2
import urllib.request, urllib.error, urllib.parse
import config
import eos.config
@@ -91,7 +91,7 @@ class SettingsProvider(object):
else:
try:
with open(canonical_path, "rb") as f:
info = cPickle.load(f)
info = pickle.load(f)
for item in defaults:
if item not in info:
info[item] = defaults[item]
@@ -103,7 +103,7 @@ class SettingsProvider(object):
return settings_obj
def saveAll(self):
for settings in self.settings.itervalues():
for settings in self.settings.values():
settings.save()
@@ -124,7 +124,7 @@ class Settings(object):
return
# NOTE: with + open -> file handle auto close
with open(self.location, "wb") as f:
cPickle.dump(self.info, f, cPickle.HIGHEST_PROTOCOL)
pickle.dump(self.info, f, pickle.HIGHEST_PROTOCOL)
def __getitem__(self, k):
try:
@@ -140,22 +140,22 @@ class Settings(object):
return self.info.__iter__()
def iterkeys(self):
return self.info.iterkeys()
return iter(self.info.keys())
def itervalues(self):
return self.info.itervalues()
return iter(self.info.values())
def iteritems(self):
return self.info.iteritems()
return iter(self.info.items())
def keys(self):
return self.info.keys()
return list(self.info.keys())
def values(self):
return self.info.values()
return list(self.info.values())
def items(self):
return self.info.items()
return list(self.info.items())
class NetworkSettings(object):
@@ -235,7 +235,7 @@ class NetworkSettings(object):
def autodetect():
proxy = None
proxydict = urllib2.ProxyHandler().proxies
proxydict = urllib.request.ProxyHandler().proxies
validPrefixes = ("http", "https")