Skip to content

Instantly share code, notes, and snippets.

@mitya57
Created November 16, 2012 14:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mitya57/4087719 to your computer and use it in GitHub Desktop.
Save mitya57/4087719 to your computer and use it in GitHub Desktop.
Main script for the routes website
#!/usr/bin/python3
# Author: Dmitry Shachnev, 2012
import sys
import time
import os.path
R_NUMBER = 'Номер маршрута'
R_DIRECTIONS = 'Маршрут'
R_WAY = 'Трасса'
R_COMPANY = 'Фирма-перевозчик'
R_LASTUPDATE = 'Последнее обновление'
def parse_data_file(filename, single=False):
f = open(filename)
blocks = {}
currentblock = None
for line in f:
line = line.rstrip()
if currentblock:
if line.startswith(' ') or ': ' not in line:
blocks[currentblock][currenttag] += (' ' + line)
elif line:
currenttag, value = line.split(': ')
blocks[currentblock][currenttag] = value
else:
currentblock = None
else:
currentblock = line
blocks[currentblock] = {}
f.close()
return blocks[currentblock] if single else blocks
def save_database(db, filename):
f = open(filename, 'w')
firstblock = True
for block, data in db.items():
if not firstblock:
print('', file=f)
print(block, file=f)
for tag, value in data.items():
print('%s: %s' % (tag, value), file=f)
firstblock = False
f.close()
def add_to_database(routedata, database):
'Reads route data from the given file and adds it to the database'
routedata[R_LASTUPDATE] = time.strftime('%Y-%m-%d', time.localtime())
database[routedata[R_NUMBER]] = routedata
def add_to_shortindex(routedata, indexdb):
indexdb[routedata[R_NUMBER]] = {
R_DIRECTIONS: routedata[R_DIRECTIONS]
}
def main():
if len(sys.argv) < 2:
return print('Please specify a file!')
routedata = parse_data_file(sys.argv[1], single=True)
routesdb = {}
add_to_database(routedata, routesdb)
save_database(routesdb, os.path.join('routes', routedata[R_NUMBER]))
companyfn = os.path.join('companies', routedata[R_COMPANY])
companydb = parse_data_file(companyfn) if os.path.exists(companyfn) else {}
add_to_shortindex(routedata, companydb)
save_database(companydb, companyfn)
for place in routedata[R_WAY].split(', '):
placefn = os.path.join('places', place)
placedb = parse_data_file(placefn) if os.path.exists(placefn) else {}
add_to_shortindex(routedata, placedb)
save_database(placedb, placefn)
print('Route %s added successfully.' % routedata[R_NUMBER])
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment