diff --git a/databaseReset.py b/databaseReset.py
index 8ae0f15..0d00bc2 100644
--- a/databaseReset.py
+++ b/databaseReset.py
@@ -20,8 +20,8 @@ troggle application.
"""
print(" - settings on loading databaseReset.py", flush=True)
-os.environ['PYTHONPATH'] = str(settings.PYTHON_PATH)
-os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'settings')
+os.environ["PYTHONPATH"] = str(settings.PYTHON_PATH)
+os.environ.setdefault("DJANGO_SETTINGS_MODULE", "settings")
print(" - settings on loading databaseReset.py")
@@ -31,14 +31,15 @@ print(f" - Memory footprint before loading Django: {resource.getrusage(resource.
try:
django.setup()
except:
- print(" ! Cyclic reference failure. Can occur when the initial db is empty. Fixed now (in UploadFileForm) but easy to reintroduce..")
+ print(
+ " ! Cyclic reference failure. Can occur when the initial db is empty. Fixed now (in UploadFileForm) but easy to reintroduce.."
+ )
raise
print(f" - Memory footprint after loading Django: {resource.getrusage(resource.RUSAGE_SELF)[2] / 1024.0:.3f} MB")
from django.contrib.auth.models import User
from django.core import management
-from django.db import (close_old_connections, connection, connections,
- transaction)
+from django.db import close_old_connections, connection, connections, transaction
from django.http import HttpResponse
from django.urls import reverse
@@ -46,24 +47,32 @@ import troggle.core.models.survex
from troggle.core.models.caves import Cave, Entrance
from troggle.core.models.troggle import DataIssue
from troggle.core.utils import get_process_memory
-from troggle.parsers.imports import (import_caves, import_drawingsfiles,
- import_ents, import_loadpos,
- import_logbook, import_logbooks,
- import_people, import_QMs, import_survex,
- import_surveyscans)
+from troggle.parsers.imports import (
+ import_caves,
+ import_drawingsfiles,
+ import_ents,
+ import_loadpos,
+ import_logbook,
+ import_logbooks,
+ import_people,
+ import_QMs,
+ import_survex,
+ import_surveyscans,
+)
if os.geteuid() == 0:
# This protects the server from having the wrong file permissions written on logs and caches
print("This script should be run as expo not root - quitting")
exit()
-expouser=settings.EXPOUSER
-expouserpass=settings.EXPOUSERPASS
-expouseremail=settings.EXPOUSER_EMAIL
+expouser = settings.EXPOUSER
+expouserpass = settings.EXPOUSERPASS
+expouseremail = settings.EXPOUSER_EMAIL
+
+expoadminuser = settings.EXPOADMINUSER
+expoadminuserpass = settings.EXPOADMINUSERPASS
+expoadminuseremail = settings.EXPOADMINUSER_EMAIL
-expoadminuser=settings.EXPOADMINUSER
-expoadminuserpass=settings.EXPOADMINUSERPASS
-expoadminuseremail=settings.EXPOADMINUSER_EMAIL
def reinit_db():
"""Rebuild database from scratch. Deletes the file first if sqlite is used,
@@ -72,22 +81,26 @@ def reinit_db():
in memory (django python models, not the database), so there is already a full load
of stuff known. Deleting the db file does not clear memory.
"""
- print("Reinitialising db ",end="")
- print(django.db.connections.databases['default']['NAME'])
- currentdbname = settings.DATABASES['default']['NAME']
- if currentdbname == ':memory:':
+ print("Reinitialising db ", end="")
+ print(django.db.connections.databases["default"]["NAME"])
+ currentdbname = settings.DATABASES["default"]["NAME"]
+ if currentdbname == ":memory:":
# closing connections should wipe the in-memory database
django.db.close_old_connections()
for conn in django.db.connections.all():
print(" ! Closing another connection to db...")
conn.close()
- elif django.db.connections.databases['default']['ENGINE'] == 'django.db.backends.sqlite3':
+ elif django.db.connections.databases["default"]["ENGINE"] == "django.db.backends.sqlite3":
if os.path.isfile(currentdbname):
try:
print(" - deleting " + currentdbname)
os.remove(currentdbname)
except OSError:
- print(" ! OSError on removing: " + currentdbname + "\n ! Is the file open in another app? Is the server running?\n")
+ print(
+ " ! OSError on removing: "
+ + currentdbname
+ + "\n ! Is the file open in another app? Is the server running?\n"
+ )
raise
else:
print(" - No database file found: " + currentdbname + " ..continuing, will create it.\n")
@@ -102,102 +115,110 @@ def reinit_db():
cursor.execute(f"USE {currentdbname}")
print(f" - Nuked : {currentdbname}\n")
- print(" - Migrating: " + django.db.connections.databases['default']['NAME'])
+ print(" - Migrating: " + django.db.connections.databases["default"]["NAME"])
- if django.db.connections.databases['default']['ENGINE'] == 'django.db.backends.sqlite3':
- #with transaction.atomic():
- management.call_command('makemigrations','core', interactive=False)
- management.call_command('migrate', interactive=False)
- management.call_command('migrate','core', interactive=False)
+ if django.db.connections.databases["default"]["ENGINE"] == "django.db.backends.sqlite3":
+ # with transaction.atomic():
+ management.call_command("makemigrations", "core", interactive=False)
+ management.call_command("migrate", interactive=False)
+ management.call_command("migrate", "core", interactive=False)
else:
- management.call_command('makemigrations','core', interactive=False)
- management.call_command('migrate', interactive=False)
- management.call_command('migrate','core', interactive=False)
+ management.call_command("makemigrations", "core", interactive=False)
+ management.call_command("migrate", interactive=False)
+ management.call_command("migrate", "core", interactive=False)
-
- print(" - done migration on: " + settings.DATABASES['default']['NAME'])
- print("users in db already: ",len(User.objects.all()))
+ print(" - done migration on: " + settings.DATABASES["default"]["NAME"])
+ print("users in db already: ", len(User.objects.all()))
with transaction.atomic():
try:
- print(" - Setting up expo user on: " + django.db.connections.databases['default']['NAME'])
+ print(" - Setting up expo user on: " + django.db.connections.databases["default"]["NAME"])
print(f" - user: {expouser} ({expouserpass:.5}...) <{expouseremail}> ")
user = User.objects.create_user(expouser, expouseremail, expouserpass)
user.is_staff = False
user.is_superuser = False
user.save()
except:
- print(" ! INTEGRITY ERROR user on: " + settings.DATABASES['default']['NAME'])
- print(django.db.connections.databases['default']['NAME'])
+ print(" ! INTEGRITY ERROR user on: " + settings.DATABASES["default"]["NAME"])
+ print(django.db.connections.databases["default"]["NAME"])
print(" ! You probably have not got a clean db when you thought you had.\n")
print(" ! Also you are probably NOT running an in-memory db now.\n")
- print("users in db: ",len(User.objects.all()))
- print("tables in db: ",len(connection.introspection.table_names()))
- memdumpsql(fn='integrityfail.sql')
- django.db.connections.databases['default']['NAME'] = ':memory:'
- #raise
-
+ print("users in db: ", len(User.objects.all()))
+ print("tables in db: ", len(connection.introspection.table_names()))
+ memdumpsql(fn="integrityfail.sql")
+ django.db.connections.databases["default"]["NAME"] = ":memory:"
+ # raise
+
with transaction.atomic():
try:
- print(" - Setting up expoadmin user on: " + django.db.connections.databases['default']['NAME'])
+ print(" - Setting up expoadmin user on: " + django.db.connections.databases["default"]["NAME"])
print(f" - user: {expoadminuser} ({expoadminuserpass:.5}...) <{expoadminuseremail}> ")
user = User.objects.create_user(expoadminuser, expoadminuseremail, expoadminuserpass)
user.is_staff = True
user.is_superuser = True
user.save()
except:
- print(" ! INTEGRITY ERROR user on: " + settings.DATABASES['default']['NAME'])
- print(django.db.connections.databases['default']['NAME'])
+ print(" ! INTEGRITY ERROR user on: " + settings.DATABASES["default"]["NAME"])
+ print(django.db.connections.databases["default"]["NAME"])
print(" ! You probably have not got a clean db when you thought you had.\n")
print(" ! Also you are probably NOT running an in-memory db now.\n")
- print("users in db: ",len(User.objects.all()))
- print("tables in db: ",len(connection.introspection.table_names()))
- memdumpsql(fn='integrityfail.sql')
- django.db.connections.databases['default']['NAME'] = ':memory:'
- #raise
+ print("users in db: ", len(User.objects.all()))
+ print("tables in db: ", len(connection.introspection.table_names()))
+ memdumpsql(fn="integrityfail.sql")
+ django.db.connections.databases["default"]["NAME"] = ":memory:"
+ # raise
+
def memdumpsql(fn):
- '''Unused option to dump SQL. Aborted attempt to create a cache for loading data
- '''
+ """Unused option to dump SQL. Aborted attempt to create a cache for loading data"""
djconn = django.db.connection
from dump import _iterdump
- with open(fn, 'w') as f:
+
+ with open(fn, "w") as f:
for line in _iterdump(djconn):
f.write(f"{line.encode('utf8')}\n")
return True
-# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
-class JobQueue():
+# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
+
+
+class JobQueue:
"""A list of import operations to run. Always reports profile times
- of the import operations in the same order.
+ of the import operations in the same order.
"""
-
- def __init__(self,run):
- '''Initialises the job queue object with a fixed order for reporting
- options during a run. Imports the timings from previous runs.
- '''
- self.runlabel = run
- self.queue = [] # tuples of (jobname, jobfunction)
- self.results = {}
- self.results_order=[
- "date","runlabel","reinit", "caves", "people",
- "logbooks", "QMs", "scans", "survex",
- "drawings", "test" ]
- for k in self.results_order:
- self.results[k]=[]
- self.tfile = "import_profile.json"
- self.htmlfile = "profile.html" # for HTML results table. Not yet done.
-
- def enq(self,label,func):
- '''Enqueue: Adding elements to queue
- '''
- self.queue.append((label,func))
+ def __init__(self, run):
+ """Initialises the job queue object with a fixed order for reporting
+ options during a run. Imports the timings from previous runs.
+ """
+ self.runlabel = run
+ self.queue = [] # tuples of (jobname, jobfunction)
+ self.results = {}
+ self.results_order = [
+ "date",
+ "runlabel",
+ "reinit",
+ "caves",
+ "people",
+ "logbooks",
+ "QMs",
+ "scans",
+ "survex",
+ "drawings",
+ "test",
+ ]
+ for k in self.results_order:
+ self.results[k] = []
+ self.tfile = "import_profile.json"
+ self.htmlfile = "profile.html" # for HTML results table. Not yet done.
+
+ def enq(self, label, func):
+ """Enqueue: Adding elements to queue"""
+ self.queue.append((label, func))
return True
def loadprofiles(self):
- """Load timings for previous imports for each data import type
- """
+ """Load timings for previous imports for each data import type"""
if os.path.isfile(self.tfile):
try:
f = open(self.tfile, "r")
@@ -209,35 +230,31 @@ class JobQueue():
# Python bug: https://github.com/ShinNoNoir/twitterwebsearch/issues/12
f.close()
for j in self.results_order:
- self.results[j].append(None) # append a placeholder
+ self.results[j].append(None) # append a placeholder
return True
-
+
def dellastprofile(self):
- """trim one set of data from the results
- """
+ """trim one set of data from the results"""
for j in self.results_order:
- self.results[j].pop() # delete last item
+ self.results[j].pop() # delete last item
return True
-
+
def delfirstprofile(self):
- """trim one set of data from the results
- """
+ """trim one set of data from the results"""
for j in self.results_order:
- self.results[j].pop(0) # delete zeroth item
+ self.results[j].pop(0) # delete zeroth item
return True
-
+
def saveprofiles(self):
- """Save timings for the set of imports just completed
- """
- with open(self.tfile, 'w') as f:
- json.dump(self.results, f)
+ """Save timings for the set of imports just completed"""
+ with open(self.tfile, "w") as f:
+ json.dump(self.results, f)
return True
def runqonce(self):
- """Run all the jobs in the queue provided - once
- """
- print("** Running job ", self.runlabel,end=" to ")
- print(django.db.connections.databases['default']['NAME'])
+ """Run all the jobs in the queue provided - once"""
+ print("** Running job ", self.runlabel, end=" to ")
+ print(django.db.connections.databases["default"]["NAME"])
jobstart = time.time()
print(f"-- Initial memory in use {get_process_memory():.3f} MB")
self.results["date"].pop()
@@ -249,98 +266,100 @@ class JobQueue():
start = time.time()
memstart = get_process_memory()
jobname, jobparser = runfunction
- #--------------------
- jobparser() # invokes function passed in the second item in the tuple
- #--------------------
+ # --------------------
+ jobparser() # invokes function passed in the second item in the tuple
+ # --------------------
memend = get_process_memory()
- duration = time.time()-start
- #print(" - MEMORY start:{:.3f} MB end:{:.3f} MB change={:.3f} MB".format(memstart,memend, ))
- print("\n*- Ended \"", jobname, f"\" {duration:.1f} seconds + {memend - memstart:.3f} MB ({memend:.3f} MB)")
+ duration = time.time() - start
+ # print(" - MEMORY start:{:.3f} MB end:{:.3f} MB change={:.3f} MB".format(memstart,memend, ))
+ print(
+ '\n*- Ended "',
+ jobname,
+ f'" {duration:.1f} seconds + {memend - memstart:.3f} MB ({memend:.3f} MB)',
+ )
self.results[jobname].pop() # the null item
self.results[jobname].append(duration)
-
jobend = time.time()
- jobduration = jobend-jobstart
+ jobduration = jobend - jobstart
print(f"** Ended job {self.runlabel} - {jobduration:.1f} seconds total.")
return True
-
def append_placeholders(self):
- '''Ads a dummy timing for each option, to fix off by one error
- '''
+ """Ads a dummy timing for each option, to fix off by one error"""
for j in self.results_order:
- self.results[j].append(None) # append a placeholder
+ self.results[j].append(None) # append a placeholder
- def run_now_django_tests(self,n):
- """Runs the standard django test harness system which is in troggle/core/TESTS/tests.py
- """
- management.call_command('test', verbosity=n)
- django.db.close_old_connections()
+ def run_now_django_tests(self, n):
+ """Runs the standard django test harness system which is in troggle/core/TESTS/tests.py"""
+ management.call_command("test", verbosity=n)
+ django.db.close_old_connections()
def run(self):
- """Initialises profile timings record, initiates relational database, runs the job queue saving the imported data as an SQL image and saves the timing profile data.
- """
+ """Initialises profile timings record, initiates relational database, runs the job queue saving the imported data as an SQL image and saves the timing profile data."""
self.loadprofiles()
- print("-- start ", django.db.connections.databases['default']['ENGINE'], django.db.connections.databases['default']['NAME'])
+ print(
+ "-- start ",
+ django.db.connections.databases["default"]["ENGINE"],
+ django.db.connections.databases["default"]["NAME"],
+ )
self.runqonce()
- if settings.DATABASES['default']['NAME'] ==":memory:":
- memdumpsql('memdump.sql') # saved contents of in-memory db, could be imported later..
+ if settings.DATABASES["default"]["NAME"] == ":memory:":
+ memdumpsql("memdump.sql") # saved contents of in-memory db, could be imported later..
self.saveprofiles()
return True
def showprofile(self):
- """Prints out the time it took to run the jobqueue
- """
+ """Prints out the time it took to run the jobqueue"""
for k in self.results_order:
- if k =="test":
+ if k == "test":
break
- elif k =="date":
- print(" days ago ", end=' ')
+ elif k == "date":
+ print(" days ago ", end=" ")
else:
- print('%10s (s)' % k, end=' ')
- percen=0
- r = self.results[k]
-
+ print("%10s (s)" % k, end=" ")
+ percen = 0
+ r = self.results[k]
+
for i in range(len(r)):
- if k == "runlabel":
+ if k == "runlabel":
if r[i]:
- rp = r[i]
+ rp = r[i]
else:
rp = " - "
- print('%8s' % rp, end=' ')
- elif k =="date":
+ print("%8s" % rp, end=" ")
+ elif k == "date":
# Calculate dates as days before present
if r[i]:
- if i == len(r)-1:
- print(" this", end=' ')
+ if i == len(r) - 1:
+ print(" this", end=" ")
else:
# prints one place to the left of where you expect
- if r[len(r)-1]:
- s = r[i]-r[len(r)-1]
- elif r[len(r)-2]:
- s = r[i]-r[len(r)-2]
+ if r[len(r) - 1]:
+ s = r[i] - r[len(r) - 1]
+ elif r[len(r) - 2]:
+ s = r[i] - r[len(r) - 2]
else:
s = 0
- days = (s)/(24*60*60)
- print(f'{days:8.2f}', end=' ')
- elif r[i]:
- print(f'{r[i]:8.1f}', end=' ')
- if i == len(r)-1 and r[i-1]:
- percen = 100* (r[i] - r[i-1])/r[i-1]
- if abs(percen) >0.1:
- print(f'{percen:8.1f}%', end=' ')
+ days = (s) / (24 * 60 * 60)
+ print(f"{days:8.2f}", end=" ")
+ elif r[i]:
+ print(f"{r[i]:8.1f}", end=" ")
+ if i == len(r) - 1 and r[i - 1]:
+ percen = 100 * (r[i] - r[i - 1]) / r[i - 1]
+ if abs(percen) > 0.1:
+ print(f"{percen:8.1f}%", end=" ")
else:
- print(" - ", end=' ')
+ print(" - ", end=" ")
print("")
print("\n")
return True
def usage():
- '''Prints command line options, can print history of previous runs with timings
- '''
- print("""Usage is 'python databaseReset.py )? # second date
+
+ s = re.match(
+ r"""(?x)(?:\s* )? # second date
\s*(?:\s*)?
\s* )?
\s* )? # second date
+ s2 = re.match(
+ r"""(?x)(?:\s* )? # second date
\s*(?:\s*)?
\s* )?
\s*
\n"
- default_note += f"INSTRUCTIONS: First open 'This survex file' (link above the CaveView panel) to find the date and info. Then "
- default_note += f"
\n\n - (0) look in the cave number index for notes on this cave, "
- default_note += f"
\n\n - (1) search in the survex file for the *ref to find a "
- default_note += f"relevant wallet, e.g.2009#11 and read the notes image files
\n - "
- default_note += f"
\n\n - (2) search in the Expo for that year e.g. 2009 to find a "
- default_note += f"relevant logbook entry, remember that the date may have been recorded incorrectly, "
- default_note += f"so check for trips i.e. logbook entries involving the same people as were listed in the survex file, "
- default_note += f"and you should also check the scanned copy of the logbook (linked from each logbook entry page) "
- default_note += f"just in case a vital trip was not transcribed, then
\n - "
- default_note += f"click on 'Edit this cave' and copy the information you find in the survex file and the logbook"
- default_note += f"and delete all the text in the 'Notes' section - which is the text you are reading now."
- default_note += f"
\n\n - Only two fields on this form are essential. "
+ default_note = f"_Survex file found in loser repo but no description in expoweb
\n"
+ default_note += f"INSTRUCTIONS: First open 'This survex file' (link above the CaveView panel) to find the date and info. Then "
+ default_note += f'
\n\n - (0) look in the cave number index for notes on this cave, '
+ default_note += f"
\n\n - (1) search in the survex file for the *ref to find a "
+ default_note += f"relevant wallet, e.g.2009#11 and read the notes image files
\n - "
+ default_note += (
+ f"
\n\n - (2) search in the Expo for that year e.g. 2009 to find a "
+ )
+ default_note += f"relevant logbook entry, remember that the date may have been recorded incorrectly, "
+ default_note += (
+ f"so check for trips i.e. logbook entries involving the same people as were listed in the survex file, "
+ )
+ default_note += (
+ f"and you should also check the scanned copy of the logbook (linked from each logbook entry page) "
+ )
+ default_note += f"just in case a vital trip was not transcribed, then
\n - "
+ default_note += (
+ f"click on 'Edit this cave' and copy the information you find in the survex file and the logbook"
+ )
+ default_note += f"and delete all the text in the 'Notes' section - which is the text you are reading now."
+ default_note += f"
\n\n - Only two fields on this form are essential. "
default_note += f"Documentation of all the fields on 'Edit this cave' form is in handbook/survey/caveentryfields"
- default_note += f"
\n\n - "
- default_note += f"You will also need to create a new entrance from the 'Edit this cave' page. Ignore the existing dummy one, it will evaporate on the next full import."
- default_note += f"
\n\n - "
- default_note += f"When you Submit it will create a new file in expoweb/cave_data/ "
- default_note += f"
\n\n - Now you can edit the entrance info: click on Edit below for the dummy entrance. "
+ default_note += f"
\n\n - "
+ default_note += f"You will also need to create a new entrance from the 'Edit this cave' page. Ignore the existing dummy one, it will evaporate on the next full import."
+ default_note += f"
\n\n - "
+ default_note += f"When you Submit it will create a new file in expoweb/cave_data/ "
+ default_note += (
+ f"
\n\n - Now you can edit the entrance info: click on Edit below for the dummy entrance. "
+ )
default_note += f"and then Submit to save it (if you forget to do this, a dummy entrance will be created for your new cave description)."
- default_note += f"
\n\n - Finally, you need to find a nerd to edit the file 'expoweb/cave_data/pending.txt' "
- default_note += f"to remove the line
{slug}
as it is no longer 'pending' but 'done. Well Done."
+ default_note += f"
\n\n - Finally, you need to find a nerd to edit the file 'expoweb/cave_data/pending.txt' "
+ default_note += (
+ f"to remove the line
{slug}
as it is no longer 'pending' but 'done. Well Done."
+ )
survex_file = get_survex_file(k)
-
+
cave = Cave(
- unofficial_number = k,
- underground_description = "Pending cave write-up - creating as empty object. No XML file available yet.",
- survex_file = survex_file,
- url = url,
- notes = default_note)
+ unofficial_number=k,
+ underground_description="Pending cave write-up - creating as empty object. No XML file available yet.",
+ survex_file=survex_file,
+ url=url,
+ notes=default_note,
+ )
if cave:
- cave.save() # must save to have id before foreign keys work. This is also a ManyToMany key.
+ cave.save() # must save to have id before foreign keys work. This is also a ManyToMany key.
cave.area.add(area)
cave.save()
message = f" ! {k:18} {cave.underground_description} url: {url}"
- DataIssue.objects.create(parser='caves', message=message, url=url)
+ DataIssue.objects.create(parser="caves", message=message, url=url)
print(message)
-
- try: # Now create a cave slug ID
- cs = CaveSlug.objects.update_or_create(cave = cave,
- slug = slug, primary = False)
+
+ try: # Now create a cave slug ID
+ cs = CaveSlug.objects.update_or_create(cave=cave, slug=slug, primary=False)
except:
message = f" ! {k:11s} PENDING cave SLUG create failure"
- DataIssue.objects.create(parser='caves', message=message)
+ DataIssue.objects.create(parser="caves", message=message)
print(message)
else:
- message = f' ! {k:11s} PENDING cave create failure'
- DataIssue.objects.create(parser='caves', message=message)
+ message = f" ! {k:11s} PENDING cave create failure"
+ DataIssue.objects.create(parser="caves", message=message)
print(message)
try:
ent = dummy_entrance(k, slug, msg="PENDING")
- ceinsts = CaveAndEntrance.objects.update_or_create(cave = cave, entrance_letter = "", entrance = ent)
+ ceinsts = CaveAndEntrance.objects.update_or_create(cave=cave, entrance_letter="", entrance=ent)
for ceinst in ceinsts:
if str(ceinst) == str(cave): # magic runes... why is the next value a Bool?
ceinst.cave = cave
@@ -196,15 +207,14 @@ def do_pending_cave(k, url, area):
break
except:
message = f" ! {k:11s} PENDING entrance + cave UNION create failure '{cave}' [{ent}]"
- DataIssue.objects.create(parser='caves', message=message)
+ DataIssue.objects.create(parser="caves", message=message)
print(message)
-
def readentrance(filename):
- '''Reads an enrance description from the .html file
+ """Reads an enrance description from the .html file
Convoluted. Sorry.This is as I inherited it and I haven't fiddled with it. Needs rewriting
- '''
+ """
global entrances_xslug
global caves_xslug
global areas_xslug
@@ -213,181 +223,214 @@ def readentrance(filename):
with open(os.path.join(ENTRANCEDESCRIPTIONS, filename)) as f:
contents = f.read()
context = filename
- #print("Reading file ENTRANCE {} / {}".format(ENTRANCEDESCRIPTIONS, filename))
- entrancecontentslist = getXML(contents, "entrance", maxItems = 1, context = context)
+ # print("Reading file ENTRANCE {} / {}".format(ENTRANCEDESCRIPTIONS, filename))
+ entrancecontentslist = getXML(contents, "entrance", maxItems=1, context=context)
if len(entrancecontentslist) != 1:
message = f'! BAD ENTRANCE at "{filename}"'
- DataIssue.objects.create(parser='caves', message=message)
+ DataIssue.objects.create(parser="caves", message=message)
print(message)
else:
entrancecontents = entrancecontentslist[0]
- non_public = getXML(entrancecontents, "non_public", maxItems = 1, context = context)
- name = getXML(entrancecontents, "name", maxItems = 1, context = context)
- slugs = getXML(entrancecontents, "slug", context = context)
- entrance_description = getXML(entrancecontents, "entrance_description", maxItems = 1, context = context)
- explorers = getXML(entrancecontents, "explorers", maxItems = 1, context = context)
- map_description = getXML(entrancecontents, "map_description", maxItems = 1, context = context)
- location_description = getXML(entrancecontents, "location_description", maxItems = 1, context = context)
- lastvisit = getXML(entrancecontents, "last visit date", maxItems = 1, minItems = 0, context = context)
- approach = getXML(entrancecontents, "approach", maxItems = 1, context = context)
- underground_description = getXML(entrancecontents, "underground_description", maxItems = 1, context = context)
- photo = getXML(entrancecontents, "photo", maxItems = 1, context = context)
- marking = getXML(entrancecontents, "marking", maxItems = 1, context = context)
- marking_comment = getXML(entrancecontents, "marking_comment", maxItems = 1, context = context)
- findability = getXML(entrancecontents, "findability", maxItems = 1, context = context)
- findability_description = getXML(entrancecontents, "findability_description", maxItems = 1, context = context)
- alt = getXML(entrancecontents, "alt", maxItems = 1, context = context)
- northing = getXML(entrancecontents, "northing", maxItems = 1, context = context)
- easting = getXML(entrancecontents, "easting", maxItems = 1, context = context)
- tag_station = getXML(entrancecontents, "tag_station", maxItems = 1, context = context)
- exact_station = getXML(entrancecontents, "exact_station", maxItems = 1, context = context)
- other_station = getXML(entrancecontents, "other_station", maxItems = 1, context = context)
- other_description = getXML(entrancecontents, "other_description", maxItems = 1, context = context)
- bearings = getXML(entrancecontents, "bearings", maxItems = 1, context = context)
- url = getXML(entrancecontents, "url", maxItems = 1, context = context)
- #if len(non_public) == 1 and len(slugs) >= 1 and len(name) >= 1 and len(entrance_description) == 1 and len(explorers) == 1 and len(map_description) == 1 and len(location_description) == 1 and len(lastvisit) == 1 and len(approach) == 1 and len(underground_description) == 1 and len(marking) == 1 and len(marking_comment) == 1 and len(findability) == 1 and len(findability_description) == 1 and len(alt) == 1 and len(northing) == 1 and len(easting) == 1 and len(tag_station) == 1 and len(exact_station) == 1 and len(other_station) == 1 and len(other_description) == 1 and len(bearings) == 1 and len(url) == 1:
- e, state = Entrance.objects.update_or_create(name = name[0],
- non_public = {"True": True, "False": False, "true": True, "false": False,}[non_public[0]],
- entrance_description = entrance_description[0],
- explorers = explorers[0],
- map_description = map_description[0],
- location_description = location_description[0],
- lastvisit = lastvisit[0],
- approach = approach[0],
- underground_description = underground_description[0],
- photo = photo[0],
- marking = marking[0],
- marking_comment = marking_comment[0],
- findability = findability[0],
- findability_description = findability_description[0],
- alt = alt[0],
- northing = northing[0],
- easting = easting[0],
- tag_station = tag_station[0],
- exact_station = exact_station[0],
- other_station = other_station[0],
- other_description = other_description[0],
- bearings = bearings[0],
- url = url[0],
- filename = filename,
- cached_primary_slug = slugs[0])
+ non_public = getXML(entrancecontents, "non_public", maxItems=1, context=context)
+ name = getXML(entrancecontents, "name", maxItems=1, context=context)
+ slugs = getXML(entrancecontents, "slug", context=context)
+ entrance_description = getXML(entrancecontents, "entrance_description", maxItems=1, context=context)
+ explorers = getXML(entrancecontents, "explorers", maxItems=1, context=context)
+ map_description = getXML(entrancecontents, "map_description", maxItems=1, context=context)
+ location_description = getXML(entrancecontents, "location_description", maxItems=1, context=context)
+ lastvisit = getXML(entrancecontents, "last visit date", maxItems=1, minItems=0, context=context)
+ approach = getXML(entrancecontents, "approach", maxItems=1, context=context)
+ underground_description = getXML(entrancecontents, "underground_description", maxItems=1, context=context)
+ photo = getXML(entrancecontents, "photo", maxItems=1, context=context)
+ marking = getXML(entrancecontents, "marking", maxItems=1, context=context)
+ marking_comment = getXML(entrancecontents, "marking_comment", maxItems=1, context=context)
+ findability = getXML(entrancecontents, "findability", maxItems=1, context=context)
+ findability_description = getXML(entrancecontents, "findability_description", maxItems=1, context=context)
+ alt = getXML(entrancecontents, "alt", maxItems=1, context=context)
+ northing = getXML(entrancecontents, "northing", maxItems=1, context=context)
+ easting = getXML(entrancecontents, "easting", maxItems=1, context=context)
+ tag_station = getXML(entrancecontents, "tag_station", maxItems=1, context=context)
+ exact_station = getXML(entrancecontents, "exact_station", maxItems=1, context=context)
+ other_station = getXML(entrancecontents, "other_station", maxItems=1, context=context)
+ other_description = getXML(entrancecontents, "other_description", maxItems=1, context=context)
+ bearings = getXML(entrancecontents, "bearings", maxItems=1, context=context)
+ url = getXML(entrancecontents, "url", maxItems=1, context=context)
+ # if len(non_public) == 1 and len(slugs) >= 1 and len(name) >= 1 and len(entrance_description) == 1 and len(explorers) == 1 and len(map_description) == 1 and len(location_description) == 1 and len(lastvisit) == 1 and len(approach) == 1 and len(underground_description) == 1 and len(marking) == 1 and len(marking_comment) == 1 and len(findability) == 1 and len(findability_description) == 1 and len(alt) == 1 and len(northing) == 1 and len(easting) == 1 and len(tag_station) == 1 and len(exact_station) == 1 and len(other_station) == 1 and len(other_description) == 1 and len(bearings) == 1 and len(url) == 1:
+ e, state = Entrance.objects.update_or_create(
+ name=name[0],
+ non_public={
+ "True": True,
+ "False": False,
+ "true": True,
+ "false": False,
+ }[non_public[0]],
+ entrance_description=entrance_description[0],
+ explorers=explorers[0],
+ map_description=map_description[0],
+ location_description=location_description[0],
+ lastvisit=lastvisit[0],
+ approach=approach[0],
+ underground_description=underground_description[0],
+ photo=photo[0],
+ marking=marking[0],
+ marking_comment=marking_comment[0],
+ findability=findability[0],
+ findability_description=findability_description[0],
+ alt=alt[0],
+ northing=northing[0],
+ easting=easting[0],
+ tag_station=tag_station[0],
+ exact_station=exact_station[0],
+ other_station=other_station[0],
+ other_description=other_description[0],
+ bearings=bearings[0],
+ url=url[0],
+ filename=filename,
+ cached_primary_slug=slugs[0],
+ )
primary = True
for slug in slugs:
- #print("entrance slug:{} filename:{}".format(slug, filename))
+ # print("entrance slug:{} filename:{}".format(slug, filename))
try:
- cs = EntranceSlug.objects.update_or_create(entrance = e,
- slug = slug,
- primary = primary)
+ cs = EntranceSlug.objects.update_or_create(entrance=e, slug=slug, primary=primary)
except:
# need to cope with duplicates
message = f" ! FAILED to get precisely one ENTRANCE when updating using: cave_entrance/{filename}"
- DataIssue.objects.create(parser='caves', message=message, url=f'/cave/{slug}/edit/')
- kents = EntranceSlug.objects.all().filter(entrance = e,
- slug = slug,
- primary = primary)
+ DataIssue.objects.create(parser="caves", message=message, url=f"/cave/{slug}/edit/")
+ kents = EntranceSlug.objects.all().filter(entrance=e, slug=slug, primary=primary)
for k in kents:
- message = " ! - DUPLICATE in db. entrance:"+ str(k.entrance) + ", slug:" + str(k.slug())
- DataIssue.objects.create(parser='caves', message=message, url=f'/cave/{slug}/edit/')
+ message = " ! - DUPLICATE in db. entrance:" + str(k.entrance) + ", slug:" + str(k.slug())
+ DataIssue.objects.create(parser="caves", message=message, url=f"/cave/{slug}/edit/")
print(message)
for k in kents:
if k.slug() != None:
- print(" ! - OVERWRITING this one: slug:"+ str(k.slug()))
+ print(" ! - OVERWRITING this one: slug:" + str(k.slug()))
k.notes = "DUPLICATE entrance found on import. Please fix\n" + k.notes
c = k
primary = False
# else: # more than one item in long list. But this is not an error, and the max and min have been checked by getXML
- # slug = Path(filename).stem
- # message = f' ! ABORT loading this entrance. in "{filename}"'
- # DataIssue.objects.create(parser='caves', message=message, url=f'/cave/{slug}/edit/')
- # print(message)
+ # slug = Path(filename).stem
+ # message = f' ! ABORT loading this entrance. in "{filename}"'
+ # DataIssue.objects.create(parser='caves', message=message, url=f'/cave/{slug}/edit/')
+ # print(message)
+
def readcave(filename):
- '''Reads an enrance description from the .html file
+ """Reads an enrance description from the .html file
Convoluted. Sorry.This is as I inherited it and I haven't fiddled with it. Needs rewriting
Assumes any area it hasn't seen before is a subarea of 1623
- '''
+ """
global entrances_xslug
global caves_xslug
global areas_xslug
-
+
# Note: these are HTML files in the EXPOWEB repo, not from the loser repo.
with open(os.path.join(CAVEDESCRIPTIONS, filename)) as f:
contents = f.read()
context = filename
- cavecontentslist = getXML(contents, "cave", maxItems = 1, context = context)
+ cavecontentslist = getXML(contents, "cave", maxItems=1, context=context)
if len(cavecontentslist) != 1:
message = f'! BAD CAVE at "{filename}"'
- DataIssue.objects.create(parser='caves', message=message)
+ DataIssue.objects.create(parser="caves", message=message)
print(message)
else:
cavecontents = cavecontentslist[0]
- non_public = getXML(cavecontents, "non_public", maxItems = 1, context = context)
- slugs = getXML(cavecontents, "caveslug", maxItems = 1, context = context)
- official_name = getXML(cavecontents, "official_name", maxItems = 1, context = context)
- areas = getXML(cavecontents, "area", context = context)
- kataster_code = getXML(cavecontents, "kataster_code", maxItems = 1, context = context)
- kataster_number = getXML(cavecontents, "kataster_number", maxItems = 1, context = context)
- unofficial_number = getXML(cavecontents, "unofficial_number", maxItems = 1, context = context)
- explorers = getXML(cavecontents, "explorers", maxItems = 1, context = context)
- underground_description = getXML(cavecontents, "underground_description", maxItems = 1, context = context)
- equipment = getXML(cavecontents, "equipment", maxItems = 1, context = context)
- references = getXML(cavecontents, "references", maxItems = 1, context = context)
- survey = getXML(cavecontents, "survey", maxItems = 1, context = context)
- kataster_status = getXML(cavecontents, "kataster_status", maxItems = 1, context = context)
- underground_centre_line = getXML(cavecontents, "underground_centre_line", maxItems = 1, context = context)
- notes = getXML(cavecontents, "notes", maxItems = 1, context = context)
- length = getXML(cavecontents, "length", maxItems = 1, context = context)
- depth = getXML(cavecontents, "depth", maxItems = 1, context = context)
- extent = getXML(cavecontents, "extent", maxItems = 1, context = context)
- survex_file = getXML(cavecontents, "survex_file", maxItems = 1, context = context)
- description_file = getXML(cavecontents, "description_file", maxItems = 1, context = context)
- url = getXML(cavecontents, "url", maxItems = 1, context = context)
- entrances = getXML(cavecontents, "entrance", context = context)
-
- if len(non_public) == 1 and len(slugs) >= 1 and len(official_name) == 1 and len(areas) >= 1 and len(kataster_code) == 1 and len(kataster_number) == 1 and len(unofficial_number) == 1 and len(explorers) == 1 and len(underground_description) == 1 and len(equipment) == 1 and len(references) == 1 and len(survey) == 1 and len(kataster_status) == 1 and len(underground_centre_line) == 1 and len(notes) == 1 and len(length) == 1 and len(depth) == 1 and len(extent) == 1 and len(survex_file) == 1 and len(description_file ) == 1 and len(url) == 1:
+ non_public = getXML(cavecontents, "non_public", maxItems=1, context=context)
+ slugs = getXML(cavecontents, "caveslug", maxItems=1, context=context)
+ official_name = getXML(cavecontents, "official_name", maxItems=1, context=context)
+ areas = getXML(cavecontents, "area", context=context)
+ kataster_code = getXML(cavecontents, "kataster_code", maxItems=1, context=context)
+ kataster_number = getXML(cavecontents, "kataster_number", maxItems=1, context=context)
+ unofficial_number = getXML(cavecontents, "unofficial_number", maxItems=1, context=context)
+ explorers = getXML(cavecontents, "explorers", maxItems=1, context=context)
+ underground_description = getXML(cavecontents, "underground_description", maxItems=1, context=context)
+ equipment = getXML(cavecontents, "equipment", maxItems=1, context=context)
+ references = getXML(cavecontents, "references", maxItems=1, context=context)
+ survey = getXML(cavecontents, "survey", maxItems=1, context=context)
+ kataster_status = getXML(cavecontents, "kataster_status", maxItems=1, context=context)
+ underground_centre_line = getXML(cavecontents, "underground_centre_line", maxItems=1, context=context)
+ notes = getXML(cavecontents, "notes", maxItems=1, context=context)
+ length = getXML(cavecontents, "length", maxItems=1, context=context)
+ depth = getXML(cavecontents, "depth", maxItems=1, context=context)
+ extent = getXML(cavecontents, "extent", maxItems=1, context=context)
+ survex_file = getXML(cavecontents, "survex_file", maxItems=1, context=context)
+ description_file = getXML(cavecontents, "description_file", maxItems=1, context=context)
+ url = getXML(cavecontents, "url", maxItems=1, context=context)
+ entrances = getXML(cavecontents, "entrance", context=context)
+
+ if (
+ len(non_public) == 1
+ and len(slugs) >= 1
+ and len(official_name) == 1
+ and len(areas) >= 1
+ and len(kataster_code) == 1
+ and len(kataster_number) == 1
+ and len(unofficial_number) == 1
+ and len(explorers) == 1
+ and len(underground_description) == 1
+ and len(equipment) == 1
+ and len(references) == 1
+ and len(survey) == 1
+ and len(kataster_status) == 1
+ and len(underground_centre_line) == 1
+ and len(notes) == 1
+ and len(length) == 1
+ and len(depth) == 1
+ and len(extent) == 1
+ and len(survex_file) == 1
+ and len(description_file) == 1
+ and len(url) == 1
+ ):
try:
- c, state = Cave.objects.update_or_create(non_public = {"True": True, "False": False, "true": True, "false": False,}[non_public[0]],
- official_name = official_name[0],
- kataster_code = kataster_code[0],
- kataster_number = kataster_number[0],
- unofficial_number = unofficial_number[0],
- explorers = explorers[0],
- underground_description = underground_description[0],
- equipment = equipment[0],
- references = references[0],
- survey = survey[0],
- kataster_status = kataster_status[0],
- underground_centre_line = underground_centre_line[0],
- notes = notes[0],
- length = length[0],
- depth = depth[0],
- extent = extent[0],
- survex_file = survex_file[0],
- description_file = description_file[0],
- url = url[0],
- filename = filename)
+ c, state = Cave.objects.update_or_create(
+ non_public={
+ "True": True,
+ "False": False,
+ "true": True,
+ "false": False,
+ }[non_public[0]],
+ official_name=official_name[0],
+ kataster_code=kataster_code[0],
+ kataster_number=kataster_number[0],
+ unofficial_number=unofficial_number[0],
+ explorers=explorers[0],
+ underground_description=underground_description[0],
+ equipment=equipment[0],
+ references=references[0],
+ survey=survey[0],
+ kataster_status=kataster_status[0],
+ underground_centre_line=underground_centre_line[0],
+ notes=notes[0],
+ length=length[0],
+ depth=depth[0],
+ extent=extent[0],
+ survex_file=survex_file[0],
+ description_file=description_file[0],
+ url=url[0],
+ filename=filename,
+ )
except:
- print(" ! FAILED to get only one CAVE when updating using: "+filename)
+ print(" ! FAILED to get only one CAVE when updating using: " + filename)
kaves = Cave.objects.all().filter(kataster_number=kataster_number[0])
for k in kaves:
- message = " ! - DUPLICATES in db. kataster:"+ str(k.kataster_number) + ", slug:" + str(k.slug())
- DataIssue.objects.create(parser='caves', message=message)
+ message = " ! - DUPLICATES in db. kataster:" + str(k.kataster_number) + ", slug:" + str(k.slug())
+ DataIssue.objects.create(parser="caves", message=message)
print(message)
for k in kaves:
if k.slug() != None:
- print(" ! - OVERWRITING this one: slug:"+ str(k.slug()))
+ print(" ! - OVERWRITING this one: slug:" + str(k.slug()))
k.notes = "DUPLICATE kataster number found on import. Please fix\n" + k.notes
c = k
-
+
for area_slug in areas:
if area_slug in areas_xslug:
newArea = areas_xslug[area_slug]
else:
- area = Area.objects.filter(short_name = area_slug)
+ area = Area.objects.filter(short_name=area_slug)
if area:
newArea = area[0]
else:
- newArea = Area(short_name = area_slug, super = Area.objects.get(short_name = "1623"))
+ newArea = Area(short_name=area_slug, super=Area.objects.get(short_name="1623"))
newArea.save()
areas_xslug[area_slug] = newArea
c.area.add(newArea)
@@ -396,17 +439,15 @@ def readcave(filename):
if slug in caves_xslug:
cs = caves_xslug[slug]
else:
- try: # we want to overwrite a PENDING cave if we are now importing the 1623-xxx.html file for it
- cs = CaveSlug.objects.update_or_create(cave = c,
- slug = slug,
- primary = primary)
+ try: # we want to overwrite a PENDING cave if we are now importing the 1623-xxx.html file for it
+ cs = CaveSlug.objects.update_or_create(cave=c, slug=slug, primary=primary)
caves_xslug[slug] = cs
except Exception as ex:
# This fails to do an update! It just crashes.. to be fixed
message = f" ! Cave update/create failure : {slug}, skipping file cave_data/{context} with exception\nException: {ex.__class__}"
- DataIssue.objects.create(parser='caves', message=message)
+ DataIssue.objects.create(parser="caves", message=message)
print(message)
-
+
primary = False
if not entrances or len(entrances) < 1:
@@ -414,80 +455,87 @@ def readcave(filename):
set_dummy_entrance(slug[5:], slug, c, msg="DUMMY")
else:
for entrance in entrances:
- eslug = getXML(entrance, "entranceslug", maxItems = 1, context = context)[0]
- letter = getXML(entrance, "letter", maxItems = 1, context = context)[0]
- if len(entrances) == 1 and not eslug: # may be empty:
([\s\S]*?)(?=0):
+ if len(endpara) > 0:
endpath = Path(settings.EXPOWEB, "years", year, "endmatter.html")
- with open(endpath,"w") as end:
- end.write(endpara+"\n")
-
+ with open(endpath, "w") as end:
+ end.write(endpara + "\n")
+
tripparas = re.findall(r"
([\s\S]*?)(?=
.*?\s*
", "
", ltriptext).strip()
-
+
triptitle = triptitle.strip()
- entrytuple = (ldate, tripcave, triptitle, ltriptext,
- trippeople, expedition, tu, tripid1)
+ entrytuple = (ldate, tripcave, triptitle, ltriptext, trippeople, expedition, tu, tripid1)
logentries.append(entrytuple)
+
# main parser for 1991 - 2001. simpler because the data has been hacked so much to fit it
def parser_html_01(year, expedition, txt, seq=""):
global logentries
global logdataissues
errorcount = 0
-
+
# extract front material and stash for later use when rebuilding from list of entries
headmatch = re.match(r"(?i)(?s).*
]*>(T/?U.*)', triptext) + mtu = re.search(r"
]*>(T/?U.*)", triptext) if mtu: tu = mtu.group(1) - triptext = triptext[:mtu.start(0)] + triptext[mtu.end():] + triptext = triptext[: mtu.start(0)] + triptext[mtu.end() :] else: tu = "" @@ -475,142 +520,144 @@ def parser_html_01(year, expedition, txt, seq=""): tripcave = triptitles[0].strip() ltriptext = triptext - + mtail = re.search(r'(?:[^<]*|\s|/|-|&|?p>|\((?:same day|\d+)\))*$', ltriptext) if mtail: - ltriptext = ltriptext[:mtail.start(0)] + ltriptext = ltriptext[: mtail.start(0)] ltriptext = re.sub(r"
", "", ltriptext) ltriptext = re.sub(r"\s*?\n\s*", " ", ltriptext) ltriptext = re.sub(r"?u>", "_", ltriptext) ltriptext = re.sub(r"?i>", "''", ltriptext) ltriptext = re.sub(r"?b>", "'''", ltriptext) ltriptext = re.sub(r"", "
", ltriptext).strip()
-
- if ltriptext == "":
- message = " ! - Zero content for logbook entry!: " + tid
- DataIssue.objects.create(parser='logbooks', message=message)
- logdataissues[tid]=message
- print(message)
-
- entrytuple = (ldate, tripcave, triptitle, ltriptext,
- trippeople, expedition, tu, tid)
+ if ltriptext == "":
+ message = " ! - Zero content for logbook entry!: " + tid
+ DataIssue.objects.create(parser="logbooks", message=message)
+ logdataissues[tid] = message
+ print(message)
+
+ entrytuple = (ldate, tripcave, triptitle, ltriptext, trippeople, expedition, tu, tid)
logentries.append(entrytuple)
-
+
except:
message = f" ! - Skipping logentry {year} due to exception in: {tid}"
- DataIssue.objects.create(parser='logbooks', message=message)
- logdataissues[tid]=message
+ DataIssue.objects.create(parser="logbooks", message=message)
+ logdataissues[tid] = message
print(message)
errorcount += 1
raise
- if errorcount >5 :
+ if errorcount > 5:
message = f" !!- TOO MANY ERRORS - aborting at '{tid}' logbook: {year}"
- DataIssue.objects.create(parser='logbooks', message=message)
- logdataissues[tid]=message
+ DataIssue.objects.create(parser="logbooks", message=message)
+ logdataissues[tid] = message
print(message)
return
+
def parser_blog(year, expedition, txt, sq=""):
- '''Parses the format of web pages collected as 'Save As HTML" from the UK Caving blog website.
+ """Parses the format of web pages collected as 'Save As HTML" from the UK Caving blog website.
Note that the entries have dates and authors, but no titles.
See detailed explanation of the complete process:
https://expo.survex.com/handbook/computing/logbooks-parsing.html
https://expo.survex.com/handbook/computing/log-blog-parsing.html
-
+
This uses some of the more obscure capabilities of regular expressions,
see https://docs.python.org/3/library/re.html
-
+
BLOG entries have this structure: