autopep8 everything - how could I ever work like this?

This commit is contained in:
Kumi 2022-04-19 15:01:03 +02:00
parent ffa4b29637
commit 6a8a614b3d
Signed by: kumi
GPG key ID: 5D1CE6AF1805ECA2
13 changed files with 983 additions and 829 deletions

View file

@ -1,7 +1,8 @@
import datetime import datetime
class Connection: class Connection:
def __init__(self, details = False): def __init__(self, details=False):
self.services = [] self.services = []
self.details = details self.details = details
self.via = [] self.via = []
@ -63,8 +64,9 @@ class Connection:
def changes(self): def changes(self):
return max(len([service for service in self.services if service.name != "Walk"]) - 1, 0) if self.details else max(len([service for service in self.services[0].name.split("/") if service != "Walk"]) - 1, 0) return max(len([service for service in self.services if service.name != "Walk"]) - 1, 0) if self.details else max(len([service for service in self.services[0].name.split("/") if service != "Walk"]) - 1, 0)
def xml(self, indent = 0, cid = False, frm = True, to = True, deptime = True, arrtime = True, duration = True, changes = True, services = True, via = True, servicekwargs = {}, stationkwargs = {}): def xml(self, indent=0, cid=False, frm=True, to=True, deptime=True, arrtime=True, duration=True, changes=True, services=True, via=True, servicekwargs={}, stationkwargs={}):
out = " " * indent + "<connection%s>\n" % ("" if cid is False else " id=\"%i\"" % cid) out = " " * indent + \
"<connection%s>\n" % ("" if cid is False else " id=\"%i\"" % cid)
if frm and self.depst(): if frm and self.depst():
out += " " * indent + " <from>\n" out += " " * indent + " <from>\n"
@ -89,18 +91,28 @@ class Connection:
if deptime and self.deptime(): if deptime and self.deptime():
out += " " * indent + " <departure>\n" out += " " * indent + " <departure>\n"
out += " " * indent + " <date>%s</date>\n" % datetime.datetime.strftime(self.deptime(), "%d.%m.%Y") out += " " * indent + \
out += " " * indent + " <time>%s</time>\n" % datetime.datetime.strftime(self.deptime(), "%H:%M") " <date>%s</date>\n" % datetime.datetime.strftime(
self.deptime(), "%d.%m.%Y")
out += " " * indent + \
" <time>%s</time>\n" % datetime.datetime.strftime(
self.deptime(), "%H:%M")
out += " " * indent + " </departure>\n" out += " " * indent + " </departure>\n"
if arrtime and self.arrtime(): if arrtime and self.arrtime():
out += " " * indent + " <arrival>\n" out += " " * indent + " <arrival>\n"
out += " " * indent + " <date>%s</date>\n" % datetime.datetime.strftime(self.arrtime(), "%d.%m.%Y") out += " " * indent + \
out += " " * indent + " <time>%s</time>\n" % datetime.datetime.strftime(self.arrtime(), "%H:%M") " <date>%s</date>\n" % datetime.datetime.strftime(
self.arrtime(), "%d.%m.%Y")
out += " " * indent + \
" <time>%s</time>\n" % datetime.datetime.strftime(
self.arrtime(), "%H:%M")
out += " " * indent + " </arrival>\n" out += " " * indent + " </arrival>\n"
out += (" " * indent + " <duration>%s</duration>\n" % self.durationString()) if duration and self.duration() else "" out += (" " * indent + " <duration>%s</duration>\n" %
out += (" " * indent + " <changes>%i</changes>\n" % self.changes()) if changes and self.changes() else "" self.durationString()) if duration and self.duration() else ""
out += (" " * indent + " <changes>%i</changes>\n" %
self.changes()) if changes and self.changes() else ""
out += " " * indent + " </details>\n" out += " " * indent + " </details>\n"
@ -108,7 +120,8 @@ class Connection:
out += " " * indent + " <services>\n" out += " " * indent + " <services>\n"
for i in range(len(self.services)): for i in range(len(self.services)):
out += self.services[i].xml(indent + 2, i, **servicekwargs) + "\n" out += self.services[i].xml(indent + 2,
i, **servicekwargs) + "\n"
out += " " * indent + " </services>\n" out += " " * indent + " </services>\n"
@ -116,10 +129,11 @@ class Connection:
return out return out
def json(self, indent = 0, cid = False, frm = True, to = True, deptime = True, arrtime = True, duration = True, changes = True, services = True, via = True, servicekwargs = {}, stationkwargs = {}): def json(self, indent=0, cid=False, frm=True, to=True, deptime=True, arrtime=True, duration=True, changes=True, services=True, via=True, servicekwargs={}, stationkwargs={}):
out = " " * indent + "{\n" out = " " * indent + "{\n"
out += (" " * indent + " \"@id\": %i,\n" % cid) if cid is not False else "" out += (" " * indent + " \"@id\": %i,\n" %
cid) if cid is not False else ""
if frm and self.depst(): if frm and self.depst():
out += " " * indent + " \"from\":\n" out += " " * indent + " \"from\":\n"
@ -144,18 +158,28 @@ class Connection:
if deptime and self.deptime(): if deptime and self.deptime():
det += " " * indent + " \"departure\": {\n" det += " " * indent + " \"departure\": {\n"
det += " " * indent + " \"date\": \"%s\",\n" % datetime.datetime.strftime(self.deptime(), "%d.%m.%Y") det += " " * indent + \
det += " " * indent + " \"time\": \"%s\"\n" % datetime.datetime.strftime(self.deptime(), "%H:%M") " \"date\": \"%s\",\n" % datetime.datetime.strftime(
self.deptime(), "%d.%m.%Y")
det += " " * indent + \
" \"time\": \"%s\"\n" % datetime.datetime.strftime(
self.deptime(), "%H:%M")
det += " " * indent + " },\n" det += " " * indent + " },\n"
if arrtime and self.arrtime(): if arrtime and self.arrtime():
det += " " * indent + " \"arrival\": {\n" det += " " * indent + " \"arrival\": {\n"
det += " " * indent + " \"date\": \"%s\",\n" % datetime.datetime.strftime(self.arrtime(), "%d.%m.%Y") det += " " * indent + \
det += " " * indent + " \"time\": \"%s\"\n"% datetime.datetime.strftime(self.arrtime(), "%H:%M") " \"date\": \"%s\",\n" % datetime.datetime.strftime(
self.arrtime(), "%d.%m.%Y")
det += " " * indent + \
" \"time\": \"%s\"\n" % datetime.datetime.strftime(
self.arrtime(), "%H:%M")
det += " " * indent + " },\n" det += " " * indent + " },\n"
det += (" " * indent + " \"duration\": \"%s\",\n" % self.durationString()) if duration and self.duration() else "" det += (" " * indent + " \"duration\": \"%s\",\n" %
det += (" " * indent + " \"changes\": %i,\n" % self.changes()) if changes and self.changes() else "" self.durationString()) if duration and self.duration() else ""
det += (" " * indent + " \"changes\": %i,\n" %
self.changes()) if changes and self.changes() else ""
det = "".join(det.rsplit(",", 1)) det = "".join(det.rsplit(",", 1))
out += det out += det
@ -166,7 +190,8 @@ class Connection:
out += " " * indent + " \"services\": [\n" out += " " * indent + " \"services\": [\n"
for i in range(len(self.services)): for i in range(len(self.services)):
out += self.services[i].json(indent + 2, i, **servicekwargs) + (",\n" if not i == len(self.services) - 1 else "\n") out += self.services[i].json(indent + 2, i, **servicekwargs) + (
",\n" if not i == len(self.services) - 1 else "\n")
out += " " * indent + " ],\n" out += " " * indent + " ],\n"

View file

@ -1,7 +1,8 @@
import requests import requests
class HTTPClient(requests.Session): class HTTPClient(requests.Session):
def __init__(self, *args, **kwargs): def __init__(self, *args, **kwargs):
requests.Session.__init__(self, *args, **kwargs) requests.Session.__init__(self, *args, **kwargs)
self.headers = {"User-Agent": "oebb_py/git (+https://kumig.it/kumitterer/oebb_py)"} self.headers = {
"User-Agent": "oebb_py/git (+https://kumig.it/kumitterer/oebb_py)"}

View file

@ -3,14 +3,17 @@ try:
except ImportError: except ImportError:
from cgi import parse_qs from cgi import parse_qs
class IllegalMethodException(BaseException): class IllegalMethodException(BaseException):
pass pass
class InvalidArgumentException(BaseException): class InvalidArgumentException(BaseException):
pass pass
class Request: class Request:
def __init__(self, env = None): def __init__(self, env=None):
if env: if env:
self.fromEnv(env) self.fromEnv(env)
@ -49,9 +52,9 @@ class Request:
self.cfrm = split[0].encode("latin-1").decode("utf-8") self.cfrm = split[0].encode("latin-1").decode("utf-8")
try: try:
self.rtype = "conn" if self.conn else "val" if self.val else self.args["type"][0].lower() self.rtype = "conn" if self.conn else "val" if self.val else self.args["type"][0].lower(
)
except: except:
output = "<h1>400 Bad Request</h1>\n" output = "<h1>400 Bad Request</h1>\n"
output += "A request type must be provided." output += "A request type must be provided."
raise InvalidArgumentException(output) raise InvalidArgumentException(output)

View file

@ -1,7 +1,8 @@
import datetime import datetime
class Service: class Service:
def __init__(self, name, depst, deptime, arrst, arrtime, dest = None, deppf = None, currdep = None, arrpf = None, curarr = None): def __init__(self, name, depst, deptime, arrst, arrtime, dest=None, deppf=None, currdep=None, arrpf=None, curarr=None):
self.name = name self.name = name
self.dest = dest self.dest = dest
self.depst = depst self.depst = depst
@ -16,10 +17,12 @@ class Service:
def duration(self): def duration(self):
return self.arrtime - self.deptime return self.arrtime - self.deptime
def xml(self, indent = 0, iid = False, name = True, depst = True, deptime = True, arrst = True, arrtime = True, deppf = True, currdep = True, arrpf = True, curarr = True, duration = True, dest = True, stationkwargs = {}): def xml(self, indent=0, iid=False, name=True, depst=True, deptime=True, arrst=True, arrtime=True, deppf=True, currdep=True, arrpf=True, curarr=True, duration=True, dest=True, stationkwargs={}):
out = " " * indent + "<service%s>\n" % ("" if iid is False else " id=\"%i\"" % iid) out = " " * indent + \
"<service%s>\n" % ("" if iid is False else " id=\"%i\"" % iid)
out += (" " * indent + " <name>%s</name>\n" % self.name) if name else "" out += (" " * indent + " <name>%s</name>\n" %
self.name) if name else ""
if dest and self.dest: if dest and self.dest:
out += " " * indent + " <destination>\n" out += " " * indent + " <destination>\n"
@ -29,28 +32,42 @@ class Service:
if depst or deptime or deppf or currdep: if depst or deptime or deppf or currdep:
out += " " * indent + " <departure>\n" out += " " * indent + " <departure>\n"
out += (self.depst.xml(indent + 2, **stationkwargs) + "\n") if depst else "" out += (self.depst.xml(indent + 2, **stationkwargs) +
"\n") if depst else ""
if deptime: if deptime:
out += " " * indent + " <date>%s</date>\n" % datetime.datetime.strftime(self.deptime, "%d.%m.%Y") out += " " * indent + \
out += " " * indent + " <time>%s</time>\n" % datetime.datetime.strftime(self.deptime, "%H:%M") " <date>%s</date>\n" % datetime.datetime.strftime(
self.deptime, "%d.%m.%Y")
out += " " * indent + \
" <time>%s</time>\n" % datetime.datetime.strftime(
self.deptime, "%H:%M")
out += (" " * indent + " <current>%s</current>\n" % self.currdep) if currdep and self.currdep else "" out += (" " * indent + " <current>%s</current>\n" %
out += (" " * indent + " <platform>%s</platform>\n" % self.deppf) if deppf and self.deppf else "" self.currdep) if currdep and self.currdep else ""
out += (" " * indent + " <platform>%s</platform>\n" %
self.deppf) if deppf and self.deppf else ""
out += " " * indent + " </departure>\n" out += " " * indent + " </departure>\n"
if arrst or arrtime or arrpf or curarr: if arrst or arrtime or arrpf or curarr:
out += " " * indent + " <arrival>\n" out += " " * indent + " <arrival>\n"
out += (self.arrst.xml(indent + 2, **stationkwargs) + "\n") if arrst else "" out += (self.arrst.xml(indent + 2, **stationkwargs) +
"\n") if arrst else ""
if arrtime: if arrtime:
out += " " * indent + " <date>%s</date>\n" % datetime.datetime.strftime(self.arrtime, "%d.%m.%Y") out += " " * indent + \
out += " " * indent + " <time>%s</time>\n" % datetime.datetime.strftime(self.arrtime, "%H:%M") " <date>%s</date>\n" % datetime.datetime.strftime(
self.arrtime, "%d.%m.%Y")
out += " " * indent + \
" <time>%s</time>\n" % datetime.datetime.strftime(
self.arrtime, "%H:%M")
out += (" " * indent + " <current>%s</current>\n" % self.curarr) if curarr and self.curarr else "" out += (" " * indent + " <current>%s</current>\n" %
out += (" " * indent + " <platform>%s</platform>\n" % self.arrpf) if arrpf and self.arrpf else "" self.curarr) if curarr and self.curarr else ""
out += (" " * indent + " <platform>%s</platform>\n" %
self.arrpf) if arrpf and self.arrpf else ""
out += " " * indent + " </arrival>\n" out += " " * indent + " </arrival>\n"
@ -58,11 +75,13 @@ class Service:
return out return out
def json(self, indent = 0, iid = False, name = True, depst = True, deptime = True, arrst = True, arrtime = True, deppf = True, currdep = True, arrpf = True, curarr = True, duration = True, dest = True, stationkwargs = {}): def json(self, indent=0, iid=False, name=True, depst=True, deptime=True, arrst=True, arrtime=True, deppf=True, currdep=True, arrpf=True, curarr=True, duration=True, dest=True, stationkwargs={}):
out = " " * indent + "{\n" out = " " * indent + "{\n"
out += (" " * indent + " \"@id\": %i,\n" % iid) if iid is not False else "" out += (" " * indent + " \"@id\": %i,\n" %
out += (" " * indent + " \"name\": \"%s\",\n" % self.name) if name else "" iid) if iid is not False else ""
out += (" " * indent + " \"name\": \"%s\",\n" %
self.name) if name else ""
if dest and self.dest: if dest and self.dest:
out += " " * indent + " \"destination\":\n" out += " " * indent + " \"destination\":\n"
@ -76,11 +95,17 @@ class Service:
dep += self.depst.json(indent + 3, **stationkwargs) + ",\n" dep += self.depst.json(indent + 3, **stationkwargs) + ",\n"
if deptime: if deptime:
dep += " " * indent + " \"date\": \"%s\",\n" % datetime.datetime.strftime(self.deptime, "%d.%m.%Y") dep += " " * indent + \
dep += " " * indent + " \"time\": \"%s\",\n" % datetime.datetime.strftime(self.deptime, "%H:%M") " \"date\": \"%s\",\n" % datetime.datetime.strftime(
self.deptime, "%d.%m.%Y")
dep += " " * indent + \
" \"time\": \"%s\",\n" % datetime.datetime.strftime(
self.deptime, "%H:%M")
dep += (" " * indent + " \"current\": \"%s\",\n" % self.currdep) if currdep and self.currdep else "" dep += (" " * indent + " \"current\": \"%s\",\n" %
dep += (" " * indent + " \"platform\": \"%s\",\n" % self.deppf) if deppf and self.deppf else "" self.currdep) if currdep and self.currdep else ""
dep += (" " * indent + " \"platform\": \"%s\",\n" %
self.deppf) if deppf and self.deppf else ""
dep = "".join(dep.rsplit(",", 1)) dep = "".join(dep.rsplit(",", 1))
out += dep + " " * indent + " },\n" out += dep + " " * indent + " },\n"
@ -93,11 +118,17 @@ class Service:
arr += self.arrst.json(indent + 3, **stationkwargs) + ",\n" arr += self.arrst.json(indent + 3, **stationkwargs) + ",\n"
if arrtime: if arrtime:
arr += " " * indent + " \"date\": \"%s\",\n" % datetime.datetime.strftime(self.arrtime, "%d.%m.%Y") arr += " " * indent + \
arr += " " * indent + " \"time\": \"%s\",\n" % datetime.datetime.strftime(self.arrtime, "%H:%M") " \"date\": \"%s\",\n" % datetime.datetime.strftime(
self.arrtime, "%d.%m.%Y")
arr += " " * indent + \
" \"time\": \"%s\",\n" % datetime.datetime.strftime(
self.arrtime, "%H:%M")
arr += (" " * indent + " \"current\": \"%s\",\n" % self.curarr) if curarr and self.curarr else "" arr += (" " * indent + " \"current\": \"%s\",\n" %
arr += (" " * indent + " \"platform\": \"%s\",\n" % self.arrpf) if arrpf and self.arrpf else "" self.curarr) if curarr and self.curarr else ""
arr += (" " * indent + " \"platform\": \"%s\",\n" %
self.arrpf) if arrpf and self.arrpf else ""
arr = "".join(arr.rsplit(",", 1)) arr = "".join(arr.rsplit(",", 1))
out += arr + " " * indent + " },\n" out += arr + " " * indent + " },\n"
@ -107,4 +138,3 @@ class Service:
out = "".join(out.rsplit(",", 1)) out = "".join(out.rsplit(",", 1))
return out return out

View file

@ -1,5 +1,5 @@
class Station: class Station:
def __init__(self, name, sttype, extid = None, xcoord = None, ycoord = None, prodclass = None): def __init__(self, name, sttype, extid=None, xcoord=None, ycoord=None, prodclass=None):
self.name = name self.name = name
self.sttype = sttype self.sttype = sttype
self.extid = extid self.extid = extid
@ -20,13 +20,17 @@ class Station:
def lon(self): def lon(self):
return self.xcoord return self.xcoord
def json(self, indent = 0, name = True, extid = True, sttype = False, coords = False, prodclass = False, distance = False, services = False, servicekwargs = {}): def json(self, indent=0, name=True, extid=True, sttype=False, coords=False, prodclass=False, distance=False, services=False, servicekwargs={}):
out = " " * indent + "{\n" out = " " * indent + "{\n"
out += (" " * indent + " \"name\": \"%s\",\n" % self.name) if name else "" out += (" " * indent + " \"name\": \"%s\",\n" %
out += (" " * indent + " \"id\": \"%s\",\n" % self.useId()) if extid else "" self.name) if name else ""
out += (" " * indent + " \"distance\": %i,\n" % int(self.distance)) if distance else "" out += (" " * indent + " \"id\": \"%s\",\n" %
out += (" " * indent + " \"type\": \"%s\",\n" % self.sttype) if sttype else "" self.useId()) if extid else ""
out += (" " * indent + " \"distance\": %i,\n" %
int(self.distance)) if distance else ""
out += (" " * indent + " \"type\": \"%s\",\n" %
self.sttype) if sttype else ""
if coords and self.xcoord: if coords and self.xcoord:
out += " " * indent + " \"coords\": {\n" out += " " * indent + " \"coords\": {\n"
@ -38,11 +42,13 @@ class Station:
out += " " * indent + " \"services\": [\n" out += " " * indent + " \"services\": [\n"
for i in range(len(self.services)): for i in range(len(self.services)):
out += self.services[i].json(indent + 2, i, **servicekwargs) + (",\n" if not i == len(self.services) - 1 else "\n") out += self.services[i].json(indent + 2, i, **servicekwargs) + (
",\n" if not i == len(self.services) - 1 else "\n")
out += " " * indent + " ]," out += " " * indent + " ],"
out += (" " * indent + " \"prodclass\": \"%s\",\n" % self.prodclass) if prodclass else "" out += (" " * indent + " \"prodclass\": \"%s\",\n" %
self.prodclass) if prodclass else ""
out = "".join(out.rsplit(",", 1)) out = "".join(out.rsplit(",", 1))
@ -50,13 +56,17 @@ class Station:
return out return out
def xml(self, indent = 0, name = True, extid = True, sttype = False, coords = False, prodclass = False, distance = False, services = False, servicekwargs = {}): def xml(self, indent=0, name=True, extid=True, sttype=False, coords=False, prodclass=False, distance=False, services=False, servicekwargs={}):
out = " " * indent + "<station>\n" out = " " * indent + "<station>\n"
out += (" " * indent + " <name>%s</name>\n" % self.name) if name else "" out += (" " * indent + " <name>%s</name>\n" %
out += (" " * indent + " <id>%s</id>\n" % self.useId()) if extid else "" self.name) if name else ""
out += (" " * indent + " <distance>%i</distance>\n" % int(self.distance)) if distance else "" out += (" " * indent + " <id>%s</id>\n" %
out += (" " * indent + " <type>%s</type>\n" % self.sttype) if sttype else "" self.useId()) if extid else ""
out += (" " * indent + " <distance>%i</distance>\n" %
int(self.distance)) if distance else ""
out += (" " * indent + " <type>%s</type>\n" %
self.sttype) if sttype else ""
if coords and self.xcoord: if coords and self.xcoord:
out += " " * indent + " <coords>\n" out += " " * indent + " <coords>\n"
@ -68,13 +78,14 @@ class Station:
out += " " * indent + " <services>\n" out += " " * indent + " <services>\n"
for i in range(len(self.services)): for i in range(len(self.services)):
out += self.services[i].xml(indent + 2, i, **servicekwargs) + "\n" out += self.services[i].xml(indent + 2,
i, **servicekwargs) + "\n"
out += " " * indent + " </services>\n" out += " " * indent + " </services>\n"
out += (" " * indent + " <prodclass>%s</prodclass>\n" % self.prodclass) if prodclass else "" out += (" " * indent + " <prodclass>%s</prodclass>\n" %
self.prodclass) if prodclass else ""
out += " " * indent + "</station>" out += " " * indent + "</station>"
return out return out

View file

@ -1,5 +1,6 @@
import workers.val import workers.val
class Train: class Train:
def __init__(self, name, tid, dest, xcoord, ycoord, prodclass): def __init__(self, name, tid, dest, xcoord, ycoord, prodclass):
self.name = name self.name = name
@ -18,15 +19,16 @@ class Train:
def destStation(self): def destStation(self):
return list(workers.val.validateName(self.name))[0] return list(workers.val.validateName(self.name))[0]
def json(self, indent = 0, name = True, tid = True, dest = True, coords = True, prodclass = False, stationkwargs = {}): def json(self, indent=0, name=True, tid=True, dest=True, coords=True, prodclass=False, stationkwargs={}):
out = " " * indent + "{\n" out = " " * indent + "{\n"
out += (" " * indent + " \"name\": \"%s\",\n" % self.name) if name else "" out += (" " * indent + " \"name\": \"%s\",\n" %
self.name) if name else ""
out += (" " * indent + " \"id\": \"%s\",\n" % self.tid) if tid else "" out += (" " * indent + " \"id\": \"%s\",\n" % self.tid) if tid else ""
if dest: if dest:
# out += " " * indent + " \"destination\":\n" # out += " " * indent + " \"destination\":\n"
# out += self.dest.json(indent + 2, **stationkwargs) + "\n" # out += self.dest.json(indent + 2, **stationkwargs) + "\n"
out += " " * indent + " \"destination\": \"%s\",\n" % self.dest out += " " * indent + " \"destination\": \"%s\",\n" % self.dest
if coords: if coords:
@ -35,7 +37,8 @@ class Train:
out += " " * indent + " \"lat\": %f\n" % self.ycoord out += " " * indent + " \"lat\": %f\n" % self.ycoord
out += " " * indent + " },\n" out += " " * indent + " },\n"
out += (" " * indent + " \"prodclass\": \"%s\",\n" % self.prodclass) if prodclass else "" out += (" " * indent + " \"prodclass\": \"%s\",\n" %
self.prodclass) if prodclass else ""
out = "".join(out.rsplit(",", 1)) out = "".join(out.rsplit(",", 1))
@ -43,16 +46,17 @@ class Train:
return out return out
def xml(self, indent = 0, name = True, tid = True, dest = True, coords = True, prodclass = False, stationkwargs = {}): def xml(self, indent=0, name=True, tid=True, dest=True, coords=True, prodclass=False, stationkwargs={}):
out = " " * indent + "<train>\n" out = " " * indent + "<train>\n"
out += (" " * indent + " <name>%s</name>\n" % self.name) if name else "" out += (" " * indent + " <name>%s</name>\n" %
self.name) if name else ""
out += (" " * indent + " <id>%s</id>\n" % self.tid) if tid else "" out += (" " * indent + " <id>%s</id>\n" % self.tid) if tid else ""
if dest: if dest:
# out += " " * indent + " <destination>\n" # out += " " * indent + " <destination>\n"
# out += self.dest.xml(indent + 2, **stationkwargs) + "\n" # out += self.dest.xml(indent + 2, **stationkwargs) + "\n"
# out += " " * indent + " </destination>\n" # out += " " * indent + " </destination>\n"
out += " " * indent + " <destination>%s</destination>\n" % self.dest out += " " * indent + " <destination>%s</destination>\n" % self.dest
if coords: if coords:
@ -61,9 +65,9 @@ class Train:
out += " " * indent + " <lat>%f</lat>\n" % self.ycoord out += " " * indent + " <lat>%f</lat>\n" % self.ycoord
out += " " * indent + " </coords>\n" out += " " * indent + " </coords>\n"
out += (" " * indent + " <prodclass>%s</prodclass>\n" % self.prodclass) if prodclass else "" out += (" " * indent + " <prodclass>%s</prodclass>\n" %
self.prodclass) if prodclass else ""
out += " " * indent + "</train>" out += " " * indent + "</train>"
return out return out

45
main.py
View file

@ -24,10 +24,13 @@ XML = "text/xml; charset=UTF-8"
DOCSTR = ' Check out the <a href="https://kumig.it/kumitterer/oebb_py#request">documentation</a> for usage instructions.' DOCSTR = ' Check out the <a href="https://kumig.it/kumitterer/oebb_py#request">documentation</a> for usage instructions.'
def doConn(req): def doConn(req):
try: try:
getfrm = req.cfrm if "cfrm" in dir(req) and req.cfrm else req.args["from"][0] if "from" in req.args else None getfrm = req.cfrm if "cfrm" in dir(
getto = req.cto if "cto" in dir(req) and req.cto else req.args["to"][0] if "to" in req.args else None req) and req.cfrm else req.args["from"][0] if "from" in req.args else None
getto = req.cto if "cto" in dir(
req) and req.cto else req.args["to"][0] if "to" in req.args else None
try: try:
frm = html.unescape(getfrm.encode("latin-1").decode("utf-8")) frm = html.unescape(getfrm.encode("latin-1").decode("utf-8"))
@ -39,16 +42,18 @@ def doConn(req):
if not frm or not to: if not frm or not to:
raise ValueError() raise ValueError()
except Exception: except Exception:
content = "<h1>400 Bad Request</h1>\n" content = "<h1>400 Bad Request</h1>\n"
content += "\"from\"and \"to\" values are required for this type of request." content += "\"from\"and \"to\" values are required for this type of request."
return Response(HTTP400, HTML, content) return Response(HTTP400, HTML, content)
count = req.args["count"][0] if "count" in req.args and req.args["count"] else 6 count = req.args["count"][0] if "count" in req.args and req.args["count"] else 6
date = req.args["date"][0] if "date" in req.args and req.args["date"] else datetime.datetime.strftime(datetime.datetime.now(pytz.timezone("Europe/Vienna")),"%d.%m.%Y") date = req.args["date"][0] if "date" in req.args and req.args["date"] else datetime.datetime.strftime(
time = req.args["time"][0] if "time" in req.args and req.args["time"] else datetime.datetime.strftime(datetime.datetime.now(pytz.timezone("Europe/Vienna")),"%H:%M") datetime.datetime.now(pytz.timezone("Europe/Vienna")), "%d.%m.%Y")
mode = True if "mode" in req.args and req.args["mode"] and req.args["mode"][0].lower() == "arr" else False time = req.args["time"][0] if "time" in req.args and req.args["time"] else datetime.datetime.strftime(
datetime.datetime.now(pytz.timezone("Europe/Vienna")), "%H:%M")
mode = True if "mode" in req.args and req.args["mode"] and req.args["mode"][0].lower(
) == "arr" else False
details = True if "details" in req.args else False details = True if "details" in req.args else False
try: try:
@ -61,7 +66,8 @@ def doConn(req):
return Response(HTTP400, HTML, content) return Response(HTTP400, HTML, content)
try: try:
outtime = datetime.datetime.strptime("%s %s" % (date, time), "%d.%m.%Y %H:%M") outtime = datetime.datetime.strptime(
"%s %s" % (date, time), "%d.%m.%Y %H:%M")
except: except:
content = "<h1>400 Bad Request</h1>\n" content = "<h1>400 Bad Request</h1>\n"
content += "The \"date\" value must be in DD.MM.YYYY format, the \"time\" value must be in HH:MM format." content += "The \"date\" value must be in DD.MM.YYYY format, the \"time\" value must be in HH:MM format."
@ -75,7 +81,8 @@ def doConn(req):
return Response(HTTP400, HTML, content) return Response(HTTP400, HTML, content)
try: try:
content = workers.conn.worker(frm, to, count, outtime, mode, details, req.json, via) content = workers.conn.worker(
frm, to, count, outtime, mode, details, req.json, via)
except Exception as e: except Exception as e:
content = "<h1>500 Internal Server Error</h1>\n" content = "<h1>500 Internal Server Error</h1>\n"
if "debug" in req.args: if "debug" in req.args:
@ -84,10 +91,12 @@ def doConn(req):
return Response(HTTP200, JSON if req.json else XML, content) return Response(HTTP200, JSON if req.json else XML, content)
def doVal(req): def doVal(req):
try: try:
try: try:
name = (req.cfrm or req.args["name"][0]).encode("latin-1").decode("utf-8") name = (req.cfrm or req.args["name"][0]).encode(
"latin-1").decode("utf-8")
except UnicodeDecodeError: except UnicodeDecodeError:
name = req.cfrm or req.args["name"][0] name = req.cfrm or req.args["name"][0]
@ -110,6 +119,7 @@ def doVal(req):
return Response(HTTP200, JSON if req.json else XML, content) return Response(HTTP200, JSON if req.json else XML, content)
def doNearby(req): def doNearby(req):
try: try:
lat = float(req.args["lat"][0].replace(",", ".")) lat = float(req.args["lat"][0].replace(",", "."))
@ -145,6 +155,7 @@ def doNearby(req):
return Response(HTTP200, JSON if req.json else XML, content) return Response(HTTP200, JSON if req.json else XML, content)
def doRadar(req): def doRadar(req):
trains = req.args["train"] if "train" in req.args else None trains = req.args["train"] if "train" in req.args else None
@ -158,6 +169,7 @@ def doRadar(req):
return Response(HTTP200, JSON if req.json else XML, content) return Response(HTTP200, JSON if req.json else XML, content)
def doDepArr(req): def doDepArr(req):
try: try:
name = req.args["name"][0] name = req.args["name"][0]
@ -172,8 +184,10 @@ def doDepArr(req):
return Response(HTTP400, HTML, content) return Response(HTTP400, HTML, content)
count = req.args["count"][0] if "count" in req.args and req.args["count"] else 30 count = req.args["count"][0] if "count" in req.args and req.args["count"] else 30
date = req.args["date"][0] if "date" in req.args and req.args["date"] else datetime.datetime.strftime(datetime.datetime.now(pytz.timezone("Europe/Vienna")),"%d.%m.%Y") date = req.args["date"][0] if "date" in req.args and req.args["date"] else datetime.datetime.strftime(
time = req.args["time"][0] if "time" in req.args and req.args["time"] else datetime.datetime.strftime(datetime.datetime.now(pytz.timezone("Europe/Vienna")),"%H:%M") datetime.datetime.now(pytz.timezone("Europe/Vienna")), "%d.%m.%Y")
time = req.args["time"][0] if "time" in req.args and req.args["time"] else datetime.datetime.strftime(
datetime.datetime.now(pytz.timezone("Europe/Vienna")), "%H:%M")
mode = True if req.rtype[:3] == "arr" else False mode = True if req.rtype[:3] == "arr" else False
details = True details = True
@ -185,14 +199,16 @@ def doDepArr(req):
return Response(HTTP400, HTML, content) return Response(HTTP400, HTML, content)
try: try:
outtime = datetime.datetime.strptime("%s %s" % (date, time), "%d.%m.%Y %H:%M") outtime = datetime.datetime.strptime(
"%s %s" % (date, time), "%d.%m.%Y %H:%M")
except: except:
content = "<h1>400 Bad Request</h1>\n" content = "<h1>400 Bad Request</h1>\n"
content += "The \"date\" value must be in DD.MM.YYYY format, the \"time\" value must be in HH:MM format." content += "The \"date\" value must be in DD.MM.YYYY format, the \"time\" value must be in HH:MM format."
return Response(HTTP400, HTML, content) return Response(HTTP400, HTML, content)
try: try:
content = workers.deparr.worker(name, count, outtime, mode, details, req.json) content = workers.deparr.worker(
name, count, outtime, mode, details, req.json)
except Exception as e: except Exception as e:
content = "<h1>500 Internal Server Error</h1>\n" content = "<h1>500 Internal Server Error</h1>\n"
if "debug" in req.args: if "debug" in req.args:
@ -201,11 +217,13 @@ def doDepArr(req):
return Response(HTTP200, JSON if req.json else XML, content) return Response(HTTP200, JSON if req.json else XML, content)
def doNot(req): def doNot(req):
content = "<h1>400 Bad Request</h1>" content = "<h1>400 Bad Request</h1>"
content += "The request type you submitted is invalid." content += "The request type you submitted is invalid."
return Response(HTTP400, HTML, content) return Response(HTTP400, HTML, content)
def application(env, re): def application(env, re):
try: try:
req = Request(env) req = Request(env)
@ -231,4 +249,3 @@ def application(env, re):
re(res.status, [("Content-Type", res.ctype)]) re(res.status, [("Content-Type", res.ctype)])
yield res.content.encode() yield res.content.encode()
return return

View file

@ -3,7 +3,8 @@ import math
import workers.val import workers.val
from classes.httpclient import HTTPClient from classes.httpclient import HTTPClient
def getOSM(lat, lon, distance = 1000):
def getOSM(lat, lon, distance=1000):
query = """[out:json]; query = """[out:json];
( (
node node
@ -28,20 +29,24 @@ out;
return res.nodes return res.nodes
def cDistance(lat1, lon1, lat2, lon2): def cDistance(lat1, lon1, lat2, lon2):
lat1, lon1, lat2, lon2 = map(math.radians, [lat1, lon1, lat2, lon2]) lat1, lon1, lat2, lon2 = map(math.radians, [lat1, lon1, lat2, lon2])
dila = lat2 - lat1 dila = lat2 - lat1
dilo = lon2 - lon1 dilo = lon2 - lon1
diff = 2 * math.asin(math.sqrt(math.sin(dila/2) ** 2 + math.cos(lat1) * math.cos(lat2) * math.sin(dilo/2) ** 2)) diff = 2 * math.asin(math.sqrt(math.sin(dila/2) ** 2 +
math.cos(lat1) * math.cos(lat2) * math.sin(dilo/2) ** 2))
dis = diff * 6371000 dis = diff * 6371000
return dis return dis
def getStations(nodes, distance = 1000, lat = None, lon = None):
unodes = list(set([node.tags["alt_name"].split(",")[0] if "alt_name" in node.tags and len(node.tags["alt_name"].split(",")[0]) > len(node.tags["name"]) else node.tags["name"] for node in nodes])) def getStations(nodes, distance=1000, lat=None, lon=None):
unodes = list(set([node.tags["alt_name"].split(",")[0] if "alt_name" in node.tags and len(
node.tags["alt_name"].split(",")[0]) > len(node.tags["name"]) else node.tags["name"] for node in nodes]))
for node in unodes: for node in unodes:
for station in workers.val.validateName(node): for station in workers.val.validateName(node):
if lat and lon: if lat and lon:
@ -54,15 +59,18 @@ def getStations(nodes, distance = 1000, lat = None, lon = None):
yield station yield station
break break
def findStations(lat, lon, distance = 1000, validate = True):
stations = list(getStations(getOSM(lat, lon, distance), distance, lat if validate else None, lon if validate else None)) def findStations(lat, lon, distance=1000, validate=True):
stations = list(getStations(getOSM(lat, lon, distance), distance,
lat if validate else None, lon if validate else None))
if validate: if validate:
return sorted(stations, key = lambda station: station.distance) return sorted(stations, key=lambda station: station.distance)
return stations return stations
def worker(lat, lon, distance = 1000, json = False):
def worker(lat, lon, distance=1000, json=False):
outtext = """{ outtext = """{
"stations": [ "stations": [
""" if json else """<?xml version="1.0" encoding="UTF-8"?> """ if json else """<?xml version="1.0" encoding="UTF-8"?>
@ -71,8 +79,10 @@ def worker(lat, lon, distance = 1000, json = False):
for station in findStations(lat, lon, distance): for station in findStations(lat, lon, distance):
outtext += ",\n" if (json and not outtext.strip()[-1] == "[") else "" outtext += ",\n" if (json and not outtext.strip()[-1] == "[") else ""
station.distance = station.distance or int(cDistance(station.lat(), station.lon(), lat, lon)) station.distance = station.distance or int(
outtext += station.json(2, distance = True) if json else station.xml(1, distance = True) cDistance(station.lat(), station.lon(), lat, lon))
outtext += station.json(2,
distance=True) if json else station.xml(1, distance=True)
outtext += "\n" if not json else "" outtext += "\n" if not json else ""
outtext += """ outtext += """

View file

@ -8,30 +8,43 @@ import sys
import workers.val import workers.val
from classes import * from classes import *
def getStation(name): def getStation(name):
return list(workers.val.validateName(name))[0] return list(workers.val.validateName(name))[0]
def getService(sid, lines, q, eq = None):
def getService(sid, lines, q, eq=None):
try: try:
dep = lines[0] dep = lines[0]
arr = lines[1] arr = lines[1]
det = lines[2] det = lines[2]
depst = list(workers.val.validateName(dep.find("td", { "class": "station" }).findAll("a")[0].string))[0] depst = list(workers.val.validateName(
depdate = dep.find("td", { "class": "date" }).string.strip() or None dep.find("td", {"class": "station"}).findAll("a")[0].string))[0]
deptime = dep.find("td", { "class": "timeValue" }).find("span").string.split()[1].strip() depdate = dep.find("td", {"class": "date"}).string.strip() or None
deptime = dep.find("td", {"class": "timeValue"}).find(
"span").string.split()[1].strip()
depprog = dep.find("span", { "class": "prognosis" }).find("span").string.strip() if dep.find("span", { "class": "prognosis" }) and dep.find("span", { "class": "prognosis" }).find("span") else None depprog = dep.find("span", {"class": "prognosis"}).find("span").string.strip() if dep.find(
depplat = dep.find("td", { "class": "platform" }).find("span").string.strip() if dep.find("td", { "class": "platform" }) and dep.find("td", { "class": "platform" }).find("span") else None "span", {"class": "prognosis"}) and dep.find("span", {"class": "prognosis"}).find("span") else None
depplat = dep.find("td", {"class": "platform"}).find("span").string.strip() if dep.find(
"td", {"class": "platform"}) and dep.find("td", {"class": "platform"}).find("span") else None
walk = dep.find("img", { "class": "product" }).get("src") == "/img/vs_oebb/fuss_pic.gif" walk = dep.find("img", {"class": "product"}).get(
name = dep.find("img", { "class": "product" }).get("alt") if not walk else "Walk" "src") == "/img/vs_oebb/fuss_pic.gif"
name = dep.find("img", {"class": "product"}).get(
"alt") if not walk else "Walk"
arrst = list(workers.val.validateName(arr.find("td", { "class": "station" }).findAll("a")[0].string))[0] arrst = list(workers.val.validateName(
arrdate = (arr.find("td", { "class": "date" }).find("span") or arr.find("td", { "class": "date" })).string.strip() or depdate arr.find("td", {"class": "station"}).findAll("a")[0].string))[0]
arrtime = arr.find("td", { "class": "timeValue" }).find("span").string.split()[1].strip() arrdate = (arr.find("td", {"class": "date"}).find("span") or arr.find(
arrprog = (arr.find("span", { "class": "prognosis" }).find("span") or arr.find("span", { "class": "prognosis" })).string.strip() or None "td", {"class": "date"})).string.strip() or depdate
arrplat = (arr.find("td", { "class": "platform" }).find("span") or arr.find("td", { "class": "platform" })).string.strip() or None arrtime = arr.find("td", {"class": "timeValue"}).find(
"span").string.split()[1].strip()
arrprog = (arr.find("span", {"class": "prognosis"}).find("span") or arr.find(
"span", {"class": "prognosis"})).string.strip() or None
arrplat = (arr.find("td", {"class": "platform"}).find("span") or arr.find(
"td", {"class": "platform"})).string.strip() or None
if arrdate and not depdate: if arrdate and not depdate:
arrdts = datetime.datetime.strptime(arrdate, "%d.%m.%Y") arrdts = datetime.datetime.strptime(arrdate, "%d.%m.%Y")
@ -42,12 +55,15 @@ def getService(sid, lines, q, eq = None):
if not (walk or depdate): if not (walk or depdate):
try: try:
purl = dep.find("td", { "class": "product" }).find("a").get("href") purl = dep.find("td", {"class": "product"}).find(
"a").get("href")
psource = HTTPClient().get(purl).text psource = HTTPClient().get(purl).text
zuppa = BeautifulSoup(psource, "html5lib") zuppa = BeautifulSoup(psource, "html5lib")
depdate = zuppa.findAll("div", { "class": "block" })[1].text.strip() depdate = zuppa.findAll("div", {"class": "block"})[
1].text.strip()
arrdate = depdate arrdate = depdate
dest = list(workers.val.validateName(zuppa.findAll("div", { "class": "block" })[2].text.split(":")[1].strip()))[0] dest = list(workers.val.validateName(zuppa.findAll(
"div", {"class": "block"})[2].text.split(":")[1].strip()))[0]
except: except:
pass pass
@ -55,13 +71,16 @@ def getService(sid, lines, q, eq = None):
depdate = "01.01.2000" depdate = "01.01.2000"
arrdate = depdate arrdate = depdate
depts = datetime.datetime.strptime("%s %s" % (depdate, deptime), "%d.%m.%Y %H:%M") depts = datetime.datetime.strptime(
arrts = datetime.datetime.strptime("%s %s" % (arrdate, arrtime), "%d.%m.%Y %H:%M") "%s %s" % (depdate, deptime), "%d.%m.%Y %H:%M")
arrts = datetime.datetime.strptime(
"%s %s" % (arrdate, arrtime), "%d.%m.%Y %H:%M")
depprog = deptime if depprog == "pünktlich" else depprog depprog = deptime if depprog == "pünktlich" else depprog
arrprog = arrtime if arrprog == "pünktlich" else arrprog arrprog = arrtime if arrprog == "pünktlich" else arrprog
svc = Service(name, depst, depts, arrst, arrts, dest, depplat, depprog, arrplat, arrprog) svc = Service(name, depst, depts, arrst, arrts, dest,
depplat, depprog, arrplat, arrprog)
q.put((sid, svc)) q.put((sid, svc))
except Exception as e: except Exception as e:
@ -69,7 +88,8 @@ def getService(sid, lines, q, eq = None):
eq.put(sys.exc_info()) eq.put(sys.exc_info())
raise raise
def getDetails(cid, url, q, via = [], eq = None):
def getDetails(cid, url, q, via=[], eq=None):
try: try:
ssource = HTTPClient().get(url).text ssource = HTTPClient().get(url).text
suppe = BeautifulSoup(ssource, "html5lib") suppe = BeautifulSoup(ssource, "html5lib")
@ -89,12 +109,13 @@ def getDetails(cid, url, q, via = [], eq = None):
for vst in via: for vst in via:
conn.addVia(vst) conn.addVia(vst)
lines = cont.findAll("tr", { "class": "tpDetails" })[1:] lines = cont.findAll("tr", {"class": "tpDetails"})[1:]
threads = [] threads = []
iq = queue.PriorityQueue() iq = queue.PriorityQueue()
for line in range(0, len(lines), 3): for line in range(0, len(lines), 3):
t = threading.Thread(target=getService, args=(line, lines[line:line + 3], iq, eq), daemon = True) t = threading.Thread(target=getService, args=(
line, lines[line:line + 3], iq, eq), daemon=True)
t.start() t.start()
threads += [t] threads += [t]
@ -110,8 +131,12 @@ def getDetails(cid, url, q, via = [], eq = None):
wdate = svc.arrtime wdate = svc.arrtime
elif svc.deptime < wdate: elif svc.deptime < wdate:
ttime0 = datetime.datetime(wdate.year, wdate.month, wdate.day) ttime0 = datetime.datetime(wdate.year, wdate.month, wdate.day)
ttime1 = ttime0 + datetime.timedelta(hours=svc.deptime.hour, minutes=svc.deptime.minute) ttime1 = ttime0 + \
ttime2 = ttime0 + datetime.timedelta(hours=svc.arrtime.hour, minutes=svc.arrtime.minute) datetime.timedelta(hours=svc.deptime.hour,
minutes=svc.deptime.minute)
ttime2 = ttime0 + \
datetime.timedelta(hours=svc.arrtime.hour,
minutes=svc.arrtime.minute)
if ttime1 < wdate: if ttime1 < wdate:
ttime1 += datetime.timedelta(days=1) ttime1 += datetime.timedelta(days=1)
@ -132,14 +157,17 @@ def getDetails(cid, url, q, via = [], eq = None):
eq.put(sys.exc_info()) eq.put(sys.exc_info())
raise raise
def connRequest(frm, to, count = 3, time = datetime.datetime.now(), mode = False, details = False, via = []):
def connRequest(frm, to, count=3, time=datetime.datetime.now(), mode=False, details=False, via=[]):
outdate = datetime.datetime.strftime(time, "%d.%m.%Y") outdate = datetime.datetime.strftime(time, "%d.%m.%Y")
outtime = datetime.datetime.strftime(time, "%H:%M") outtime = datetime.datetime.strftime(time, "%H:%M")
url = "http://fahrplan.oebb.at/bin/query.exe/dn?start=1&S=%s&Z=%s&REQ0JourneyDate=%s&time=%s&REQ0HafasNumCons0=%s%s" % (frm.extid if frm.extid else frm.name, to.extid if to.extid else to.name, outdate, outtime, count, "&timesel=arrive" if mode else "") url = "http://fahrplan.oebb.at/bin/query.exe/dn?start=1&S=%s&Z=%s&REQ0JourneyDate=%s&time=%s&REQ0HafasNumCons0=%s%s" % (
frm.extid if frm.extid else frm.name, to.extid if to.extid else to.name, outdate, outtime, count, "&timesel=arrive" if mode else "")
for i in range(len(via)): for i in range(len(via)):
url += "&REQ0JourneyStops%i.0G=%s&REQ0JourneyStops%i.0A=1" % (i + 1, via[i].extid if via[i].extid else via[i].name, i + 1) url += "&REQ0JourneyStops%i.0G=%s&REQ0JourneyStops%i.0A=1" % (
i + 1, via[i].extid if via[i].extid else via[i].name, i + 1)
source = HTTPClient().get(url).text source = HTTPClient().get(url).text
@ -160,7 +188,8 @@ def connRequest(frm, to, count = 3, time = datetime.datetime.now(), mode = False
q = queue.PriorityQueue() q = queue.PriorityQueue()
for i in range(len(conns)): for i in range(len(conns)):
t = threading.Thread(target=getDetails, args=(i, conns[i], q, via, eq), daemon = True) t = threading.Thread(target=getDetails, args=(
i, conns[i], q, via, eq), daemon=True)
t.start() t.start()
threads += [t] threads += [t]
@ -180,33 +209,37 @@ def connRequest(frm, to, count = 3, time = datetime.datetime.now(), mode = False
if not det: if not det:
break break
stations = det.find("td", { "class": "station" }).findAll("div") stations = det.find("td", {"class": "station"}).findAll("div")
depst = getStation(stations[0].text.strip()) depst = getStation(stations[0].text.strip())
arrst = getStation(stations[-1].text.strip()) arrst = getStation(stations[-1].text.strip())
dates = list(det.find("td", { "class": "date" }).strings) dates = list(det.find("td", {"class": "date"}).strings)
depdate = dates[0] depdate = dates[0]
try: try:
arrdate = dates[1] arrdate = dates[1]
except: except:
arrdate = depdate arrdate = depdate
times = det.find("div", { "class": "planed" }).text times = det.find("div", {"class": "planed"}).text
deptime = times.split()[0] deptime = times.split()[0]
arrtime = times.split()[2] arrtime = times.split()[2]
projections = det.find("div", { "class": "prognosis" }) projections = det.find("div", {"class": "prognosis"})
curdep = None curdep = None
curarr = None curarr = None
depts = datetime.datetime.strptime("%s %s" % (depdate, deptime), "%d.%m.%Y %H:%M") depts = datetime.datetime.strptime(
arrts = datetime.datetime.strptime("%s %s" % (arrdate, arrtime), "%d.%m.%Y %H:%M") "%s %s" % (depdate, deptime), "%d.%m.%Y %H:%M")
arrts = datetime.datetime.strptime(
"%s %s" % (arrdate, arrtime), "%d.%m.%Y %H:%M")
name = "/".join([img.get("title") for img in det.findAll("img", { "class": "product" })]) name = "/".join([img.get("title")
for img in det.findAll("img", {"class": "product"})])
# ticketurl = det.find("td", { "class": "fares" }).find("a").get("href") # ticketurl = det.find("td", { "class": "fares" }).find("a").get("href")
svc = Service(name, depst, depts, arrst, arrts, currdep = curdep, curarr = curarr) svc = Service(name, depst, depts, arrst, arrts,
currdep=curdep, curarr=curarr)
conn = Connection(details) conn = Connection(details)
for vst in via: for vst in via:
@ -216,8 +249,10 @@ def connRequest(frm, to, count = 3, time = datetime.datetime.now(), mode = False
yield conn yield conn
def worker(frm, to, count = 3, time = datetime.datetime.now(pytz.timezone("Europe/Vienna")), mode = False, details = False, json = False, via = None):
conns = list(connRequest(getStation(frm), getStation(to), count, time, mode, details, [getStation(vst) for vst in via] if via else [])) def worker(frm, to, count=3, time=datetime.datetime.now(pytz.timezone("Europe/Vienna")), mode=False, details=False, json=False, via=None):
conns = list(connRequest(getStation(frm), getStation(to), count, time,
mode, details, [getStation(vst) for vst in via] if via else []))
conns = conns[::-1] if mode else conns conns = conns[::-1] if mode else conns
output = """<?xml version="1.0" encoding="UTF-8"?> output = """<?xml version="1.0" encoding="UTF-8"?>
@ -227,7 +262,8 @@ def worker(frm, to, count = 3, time = datetime.datetime.now(pytz.timezone("Europ
""" """
for i in range(len(conns)): for i in range(len(conns)):
output += (conns[i].xml(1, i) + "\n") if not json else (conns[i].json(2, i) + ("\n" if i == len(conns) - 1 else ",\n")) output += (conns[i].xml(1, i) + "\n") if not json else (
conns[i].json(2, i) + ("\n" if i == len(conns) - 1 else ",\n"))
output += "</connections>" if not json else " ]\n}" output += "</connections>" if not json else " ]\n}"

View file

@ -8,17 +8,20 @@ import sys
import workers.val import workers.val
from classes import * from classes import *
def getStation(name): def getStation(name):
return list(workers.val.validateName(name))[0] return list(workers.val.validateName(name))[0]
def getService(sid, url, dtime, q = None, eq = None):
def getService(sid, url, dtime, q=None, eq=None):
try: try:
zuppa = BeautifulSoup(HTTPClient().get(url).text, "html5lib") zuppa = BeautifulSoup(HTTPClient().get(url).text, "html5lib")
name = zuppa.findAll("div", { "class": "block" })[0].text.strip().replace("(Zug-Nr. ", " - ").replace(")", "") name = zuppa.findAll("div", {"class": "block"})[0].text.strip().replace(
ddate = zuppa.findAll("div", { "class": "block" })[1].text.strip() "(Zug-Nr. ", " - ").replace(")", "")
ddate = zuppa.findAll("div", {"class": "block"})[1].text.strip()
table = zuppa.find("table", { "class": "resultTable" }) table = zuppa.find("table", {"class": "resultTable"})
rows = table.findAll("tr")[1:] rows = table.findAll("tr")[1:]
for row in rows: for row in rows:
@ -34,14 +37,17 @@ def getService(sid, url, dtime, q = None, eq = None):
curarr = atime if curarr == "pünktlich" else curarr or None curarr = atime if curarr == "pünktlich" else curarr or None
arrpf = rows[-1].findAll("td")[-1].text.strip() arrpf = rows[-1].findAll("td")[-1].text.strip()
deptime = datetime.datetime.strptime("%s %s" % (ddate, dtime), "%d.%m.%Y %H:%M") deptime = datetime.datetime.strptime(
arrtime = datetime.datetime.strptime("%s %s" % (ddate, atime), "%d.%m.%Y %H:%M") "%s %s" % (ddate, dtime), "%d.%m.%Y %H:%M")
arrtime = datetime.datetime.strptime(
"%s %s" % (ddate, atime), "%d.%m.%Y %H:%M")
if arrtime < deptime: if arrtime < deptime:
arrtime += datetime.timedelta(days = 1) arrtime += datetime.timedelta(days=1)
if q: if q:
q.put((sid, Service(name, depst, deptime, dest, arrtime, dest, deppf, currdep, arrpf, curarr))) q.put((sid, Service(name, depst, deptime, dest,
arrtime, dest, deppf, currdep, arrpf, curarr)))
return q return q
except: except:
@ -49,11 +55,13 @@ def getService(sid, url, dtime, q = None, eq = None):
eq.put(sys.exc_info()) eq.put(sys.exc_info())
raise raise
def daRequest(station, count = 3, time = datetime.datetime.now(), mode = False, details = False):
def daRequest(station, count=3, time=datetime.datetime.now(), mode=False, details=False):
outdate = datetime.datetime.strftime(time, "%d.%m.%Y") outdate = datetime.datetime.strftime(time, "%d.%m.%Y")
outtime = datetime.datetime.strftime(time, "%H:%M") outtime = datetime.datetime.strftime(time, "%H:%M")
url = "http://fahrplan.oebb.at/bin/stboard.exe/dn?input=%s&boardType=%s&time=%s&productsFilter=1111111111111111&dateBegin=%s&dateEnd=&selectDate=&maxJourneys=%i&start=yes&dirInput=&sqView=2" % (station.extid if station.extid else station.name, "arr" if mode else "dep", outtime, outdate, count) url = "http://fahrplan.oebb.at/bin/stboard.exe/dn?input=%s&boardType=%s&time=%s&productsFilter=1111111111111111&dateBegin=%s&dateEnd=&selectDate=&maxJourneys=%i&start=yes&dirInput=&sqView=2" % (
station.extid if station.extid else station.name, "arr" if mode else "dep", outtime, outdate, count)
source = HTTPClient().get(url).text source = HTTPClient().get(url).text
@ -68,14 +76,16 @@ def daRequest(station, count = 3, time = datetime.datetime.now(), mode = False,
for row in table.findAll("tr")[1:-1]: for row in table.findAll("tr")[1:-1]:
if not len(row.findAll("td")) < 4: if not len(row.findAll("td")) < 4:
services += [(row.findAll("a")[0].get("href"), row.findAll("td")[0].text.strip())] services += [(row.findAll("a")[0].get("href"),
row.findAll("td")[0].text.strip())]
threads = [] threads = []
eq = queue.Queue() eq = queue.Queue()
q = queue.PriorityQueue() q = queue.PriorityQueue()
for i in range(len(services)): for i in range(len(services)):
t = threading.Thread(target=getService, args=(i, services[i][0], services[i][1], q, eq), daemon = True) t = threading.Thread(target=getService, args=(
i, services[i][0], services[i][1], q, eq), daemon=True)
t.start() t.start()
threads += [t] threads += [t]
@ -91,13 +101,14 @@ def daRequest(station, count = 3, time = datetime.datetime.now(), mode = False,
return station return station
def worker(station, count = 30, time = datetime.datetime.now(pytz.timezone("Europe/Vienna")), mode = False, details = False, json = False):
def worker(station, count=30, time=datetime.datetime.now(pytz.timezone("Europe/Vienna")), mode=False, details=False, json=False):
station = daRequest(getStation(station), count, time, mode, details) station = daRequest(getStation(station), count, time, mode, details)
if json: if json:
output = station.json(services = True) output = station.json(services=True)
else: else:
output = """<?xml version="1.0" encoding="UTF-8"?>\n""" output = """<?xml version="1.0" encoding="UTF-8"?>\n"""
output += station.xml(services = True) output += station.xml(services=True)
return output return output

View file

@ -2,10 +2,12 @@ import json
import urllib.parse import urllib.parse
from classes import * from classes import *
def getRadar(): def getRadar():
return HTTPClient().get("http://zugradar.oebb.at/bin/query.exe/dny?look_minx=-180000000&look_maxx=180000000&look_miny=-90000000&look_maxy=90000000&tpl=trains2json2&look_json=yes&performLocating=1&look_nv=get_zntrainname|no|attr|81|get_rtonly|yes|zugposmode|2|interval|30000|intervalstep|2000|maxnumberoftrains|500000000000|").text return HTTPClient().get("http://zugradar.oebb.at/bin/query.exe/dny?look_minx=-180000000&look_maxx=180000000&look_miny=-90000000&look_maxy=90000000&tpl=trains2json2&look_json=yes&performLocating=1&look_nv=get_zntrainname|no|attr|81|get_rtonly|yes|zugposmode|2|interval|30000|intervalstep|2000|maxnumberoftrains|500000000000|").text
def getTrains(names = None):
def getTrains(names=None):
trains = json.loads(getRadar())["t"] trains = json.loads(getRadar())["t"]
for train in trains: for train in trains:
name = " ".join(train["n"].split()) name = " ".join(train["n"].split())
@ -24,9 +26,10 @@ def getTrains(names = None):
find = True find = True
if find: if find:
yield Train(name = name, dest = destination, xcoord = xcoord, ycoord = ycoord, prodclass = prodclass, tid = tid) yield Train(name=name, dest=destination, xcoord=xcoord, ycoord=ycoord, prodclass=prodclass, tid=tid)
def worker(trains = None, json = False):
def worker(trains=None, json=False):
outtext = """{ outtext = """{
"trains": [ "trains": [
""" if json else """<?xml version="1.0" encoding="UTF-8"?> """ if json else """<?xml version="1.0" encoding="UTF-8"?>

View file

@ -2,10 +2,13 @@ import json
import urllib.parse import urllib.parse
from classes import * from classes import *
def getValidator(name): def getValidator(name):
data = HTTPClient().get("http://scotty.oebb.at/bin/ajax-getstop.exe/dn?REQ0JourneyStopsS0A=255&REQ0JourneyStopsB=12&S='%s'?&js=true&" % urllib.parse.quote(name.encode("latin-1"))).text data = HTTPClient().get("http://scotty.oebb.at/bin/ajax-getstop.exe/dn?REQ0JourneyStopsS0A=255&REQ0JourneyStopsB=12&S='%s'?&js=true&" %
urllib.parse.quote(name.encode("latin-1"))).text
return "=".join(data.split("=")[1:]).split(";")[0] return "=".join(data.split("=")[1:]).split(";")[0]
def validateName(name): def validateName(name):
stations = json.loads(getValidator(name)) stations = json.loads(getValidator(name))
for station in stations["suggestions"]: for station in stations["suggestions"]:
@ -19,9 +22,10 @@ def validateName(name):
ycoord = station["ycoord"] ycoord = station["ycoord"]
prodclass = station["prodClass"] prodclass = station["prodClass"]
yield Station(name = name, sttype = sttype, extid = extid, xcoord = xcoord, ycoord = ycoord, prodclass = prodclass) yield Station(name=name, sttype=sttype, extid=extid, xcoord=xcoord, ycoord=ycoord, prodclass=prodclass)
def worker(name, json = False):
def worker(name, json=False):
outtext = """{ outtext = """{
"stations": [ "stations": [
""" if json else """<?xml version="1.0" encoding="UTF-8"?> """ if json else """<?xml version="1.0" encoding="UTF-8"?>
@ -38,4 +42,3 @@ def worker(name, json = False):
}""" if json else "</stations>" }""" if json else "</stations>"
return outtext return outtext