예제 #1
0
    def _getLineConfiguration(self, nLine):

        # if the data directory does not exist, create it
        if not os.path.exists(self.sDirectory):
            os.makedirs(self.sDirectory)

        sFilename = ('route_' + str(nLine) + '_directionsTable.txt')
        sFilename = os.path.join(self.sDirectory, sFilename)

        try:
            bFileExists = os.path.isfile(sFilename)
            bUpdatedToday = (datetime.date.today() == datetime.date.fromtimestamp(os.path.getmtime(sFilename)))

        except OSError:
            bFileExists = False
            bUpdatedToday = False

        # configuration files are only updated once a day
        if bFileExists is False or bUpdatedToday is False:

            output = Line(id=nLine)

            sRoute = '&r=' + str(nLine)
            try:
                urlHandle = urllib.urlopen(self.sUrlNextbus + self.sCommandGetStops
                                           + self.sAgency + sRoute + self.sFlags)
                xml = urlHandle.read()
                urlHandle.close()
                root = etree.fromstring(xml)

            except Exception as e:
                print "Could not load configuration: %s" % e
                return

            lStops = {}

            for elementA in root:
                if elementA.tag == 'route':
                    for elementB in elementA:

                        if elementB.tag == 'stop':
                            stopID = elementB.attrib['tag']

                            lStops[stopID] = Stop(
                                id=elementB.attrib['tag'],
                                name=elementB.attrib['title'],
                                latitude=elementB.attrib['lat'],
                                longitude=elementB.attrib['lon']
                            )

                        if elementB.tag == 'direction':
                            sBusDirection = elementB.attrib['tag']
                            direction = Direction(line=nLine, id=sBusDirection, title=elementB.attrib['title'])

                            for elementC in elementB:
                                direction.addStop(lStops[elementC.attrib['tag']])

                            output.addDirection(direction)

            # Write out direction "variables" table to a file
            fhDirections = open(sFilename, 'wb')
            pickle.dump(output, fhDirections)
            fhDirections.close()

            return output

        # route information is cached, so just restore it
        else:
            fhDirections = open(sFilename, 'rb')
            output = pickle.load(fhDirections)
            fhDirections.close()
            return output