[svn] Brief code cleanup.

This commit is contained in:
substantialnoninfringinguser 2009-07-03 05:31:49 +01:00
parent dc19150eba
commit 8446047ab2
17 changed files with 126 additions and 207 deletions

View File

@ -1,8 +0,0 @@
# this is the snippet from http://www.djangosnippets.org/snippets/3/
from django.shortcuts import render_to_response
from django.template import RequestContext
def render_response(req, *args, **kwargs):
kwargs['context_instance'] = RequestContext(req)
return render_to_response(*args, **kwargs)

View File

@ -18,8 +18,8 @@ logging.basicConfig(level=logging.DEBUG,
filename=settings.LOGFILE,
filemode='w')
#This class is for adding fields and methods which all of our models will have.
class TroggleModel(models.Model):
"""This class is for adding fields and methods which all of our models will have."""
new_since_parsing = models.BooleanField(default=False, editable=False)
non_public = models.BooleanField(default=False)
def object_name(self):
@ -29,22 +29,10 @@ class TroggleModel(models.Model):
return urlparse.urljoin(settings.URL_ROOT, "/admin/core/" + self.object_name().lower() + "/" + str(self.pk))
class Meta:
abstract = True
class TroggleImageModel(ImageModel):
new_since_parsing = models.BooleanField(default=False, editable=False)
def object_name(self):
return self._meta.object_name
def get_admin_url(self):
return urlparse.urljoin(settings.URL_ROOT, "/admin/core/" + self.object_name().lower() + "/" + str(self.pk))
class Meta:
abstract = True
abstract = True
class Expedition(TroggleModel):
"""Represents a caving expedition"""
year = models.CharField(max_length=20, unique=True)
name = models.CharField(max_length=100)
date_from = models.DateField(blank=True,null=True)
@ -61,15 +49,16 @@ class Expedition(TroggleModel):
#return settings.URL_ROOT + "/expedition/%s" % self.year
return urlparse.urljoin(settings.URL_ROOT, reverse('expedition',args=[self.year]))
# lose these two functions (inelegant, and we may create a file with the dates that we can load from)
def GuessDateFrom(self):
"""Returns the date of the first logbook entry in the expedition"""
try:
return self.logbookentry_set.order_by('date')[0].date
except IndexError:
pass
def GuessDateTo(self): # returns the date of the last logbook entry in the expedition
def GuessDateTo(self):
"""Returns the date of the last logbook entry in the expedition"""
try:
return self.logbookentry_set.order_by('date')[-1].date
except IndexError:
@ -90,42 +79,27 @@ class Expedition(TroggleModel):
date+=datetime.timedelta(days=1)
return res
class Person(TroggleModel):
"""Represents a person, also used as the profile model"""
first_name = models.CharField(max_length=100)
last_name = models.CharField(max_length=100)
is_vfho = models.BooleanField(help_text="VFHO is the Vereines für Höhlenkunde in Obersteier, a nearby Austrian caving club.")
mug_shot = models.CharField(max_length=100, blank=True,null=True)
mug_shot = models.CharField(max_length=100, blank=True,null=True) #obsolete, remove soon
blurb = models.TextField(blank=True,null=True)
orderref = models.CharField(max_length=200) # for alphabetic
#href = models.CharField(max_length=200)
orderref = models.CharField(max_length=200) # for alphabetic
#the below have been removed and made methods. I'm not sure what the b in bisnotable stands for. - AC 16 Feb
#notability = models.FloatField() # for listing the top 20 people
#bisnotable = models.BooleanField()
user = models.OneToOneField(User, null=True, blank=True)
def get_absolute_url(self):
return urlparse.urljoin(settings.URL_ROOT,reverse('person',kwargs={'first_name':self.first_name,'last_name':self.last_name}))
class Meta:
verbose_name_plural = "People"
class Meta:
verbose_name_plural = "People"
ordering = ('orderref',) # "Wookey" makes too complex for: ('last_name', 'first_name')
def __unicode__(self):
if self.last_name:
return "%s %s" % (self.first_name, self.last_name)
return self.first_name
# Below are no longer needed. Use {{ person.personexpedition_set.all.0.expedition }} for Firstexpedition, and {{ person.personexpedition_set.latest.expedition }} for Lastexpedition
# these ought to be possible by piping through |min in the template, or getting the first of an ordered list
# def Firstexpedition(self):
# return self.personexpedition_set.order_by('expedition')[0]
# def Lastexpedition(self):
# return self.personexpedition_set.order_by('-expedition')[0]
def notability(self):
notability = Decimal(0)
@ -136,18 +110,9 @@ class Person(TroggleModel):
def bisnotable(self):
return self.notability() > Decimal(1)/Decimal(3)
#def Sethref(self):
#if self.last_name:
#self.href = self.first_name.lower() + "_" + self.last_name.lower()
#self.orderref = self.last_name + " " + self.first_name
#else:
# self.href = self.first_name.lower()
#self.orderref = self.first_name
#self.notability = 0.0 # set temporarily
class PersonExpedition(TroggleModel):
""""""
expedition = models.ForeignKey(Expedition)
person = models.ForeignKey(Person)
date_from = models.DateField(blank=True,null=True)
@ -234,8 +199,9 @@ class PersonExpedition(TroggleModel):
return urlparse.urljoin(settings.URL_ROOT, reverse('personexpedition',kwargs={'first_name':self.person.first_name,'last_name':self.person.last_name,'year':self.expedition.year}))
class LogbookEntry(TroggleModel):
"""Represents trips of all kinds. This is the central model of Troggle."""
date = models.DateField()
expedition = models.ForeignKey(Expedition,blank=True,null=True) # yes this is double-
expedition = models.ForeignKey(Expedition,blank=True,null=True)
author = models.ForeignKey(PersonExpedition,blank=True,null=True) # the person who writes it up doesn't have to have been on the trip.
# Re: the above- so this field should be "typist" or something, not "author". - AC 15 jun 09
title = models.CharField(max_length=200)
@ -243,16 +209,9 @@ class LogbookEntry(TroggleModel):
place = models.CharField(max_length=100,blank=True,null=True,help_text="Only use this if you haven't chosen a cave")
text = models.TextField()
slug = models.SlugField(max_length=50)
#href = models.CharField(max_length=100)
#logbookentry_next = models.ForeignKey('LogbookEntry', related_name='pnext', blank=True,null=True)
#logbookentry_prev = models.ForeignKey('LogbookEntry', related_name='pprev', blank=True,null=True)
class Meta:
verbose_name_plural = "Logbook Entries"
# several PersonTrips point in to this object
class Meta:
verbose_name_plural = "Logbook Entries"
ordering = ('-date',)
def get_absolute_url(self):
@ -302,7 +261,6 @@ class PersonTrip(TroggleModel):
except:
return
# def get_persons_previous_trip(self):
#
# move following classes into models_cave
#
@ -574,7 +532,7 @@ class QM(TroggleModel):
return res
photoFileStorage = FileSystemStorage(location=settings.PHOTOS_ROOT, base_url=settings.PHOTOS_URL)
class Photo(TroggleImageModel):
class Photo(ImageModel, TroggleModel):
caption = models.CharField(max_length=1000,blank=True,null=True)
contains_logbookentry = models.ForeignKey(LogbookEntry,blank=True,null=True)
contains_person = models.ManyToManyField(Person,blank=True,null=True)
@ -606,7 +564,7 @@ def get_scan_path(instance, filename):
number="%02d" % instance.survey.wallet_number + str(instance.survey.wallet_letter) #using %02d string formatting because convention was 2009#01
return os.path.join('./',year,year+r'#'+number,instance.contents+str(instance.number_in_wallet)+r'.jpg')
class ScannedImage(TroggleImageModel):
class ScannedImage(ImageModel, TroggleModel):
file = models.ImageField(storage=scansFileStorage, upload_to=get_scan_path)
scanned_by = models.ForeignKey(Person,blank=True, null=True)
scanned_on = models.DateField(null=True)

View File

@ -1,39 +0,0 @@
import re
from django.db.models import Q
# search script from http://www.julienphalip.com/blog/2008/08/16/adding-search-django-site-snap/
def normalize_query(query_string,
findterms=re.compile(r'"([^"]+)"|(\S+)').findall,
normspace=re.compile(r'\s{2,}').sub):
''' Splits the query string in invidual keywords, getting rid of unecessary spaces
and grouping quoted words together.
Example:
>>> normalize_query(' some random words "with quotes " and spaces')
['some', 'random', 'words', 'with quotes', 'and', 'spaces']
'''
return [normspace(' ', (t[0] or t[1]).strip()) for t in findterms(query_string)]
def get_query(query_string, search_fields):
''' Returns a query, that is a combination of Q objects. That combination
aims to search keywords within a model by testing the given search fields.
'''
query = None # Query to search for every search term
terms = normalize_query(query_string)
for term in terms:
or_query = None # Query to search for a given term in each field
for field_name in search_fields:
q = Q(**{"%s__icontains" % field_name: term})
if or_query is None:
or_query = q
else:
or_query = or_query | q
if query is None:
query = or_query
else:
query = query & or_query
return query

View File

@ -4,7 +4,7 @@ import troggle.settings as settings
from django.forms.models import formset_factory
import search
from django.core.urlresolvers import reverse
from troggle.alwaysUseRequestContext import render_response # see views_logbooks for explanation on this.
from utils import render_with_context # see views_logbooks for explanation on this.
from django.http import HttpResponseRedirect
from django.conf import settings
import re, urlparse
@ -21,20 +21,20 @@ def caveindex(request):
caves = Cave.objects.all()
notablecavehrefs = [ "161", "204", "258", "76" ] # could detect notability by trips and notability of people who have been down them
notablecaves = [Cave.objects.get(kataster_number=kataster_number) for kataster_number in notablecavehrefs ]
return render_response(request,'caveindex.html', {'caves': caves, 'notablecaves':notablecaves})
return render_with_context(request,'caveindex.html', {'caves': caves, 'notablecaves':notablecaves})
def cave(request, cave_id='', offical_name=''):
cave=getCave(cave_id)
if cave.non_public and not request.user.is_authenticated():
return render_response(request,'nonpublic.html', {'instance': cave})
return render_with_context(request,'nonpublic.html', {'instance': cave})
else:
return render_response(request,'cave.html', {'cave': cave})
return render_with_context(request,'cave.html', {'cave': cave})
def qm(request,cave_id,qm_id,year,grade=None):
year=int(year)
try:
qm=getCave(cave_id).get_QMs().get(number=qm_id,found_by__date__year=year)
return render_response(request,'qm.html',locals())
return render_with_context(request,'qm.html',locals())
except QM.DoesNotExist:
url=urlparse.urljoin(settings.URL_ROOT, r'/admin/expo/qm/add/'+'?'+ r'number=' + qm_id)
@ -46,7 +46,7 @@ def qm(request,cave_id,qm_id,year,grade=None):
def ent(request, cave_id, ent_letter):
cave = Cave.objects.filter(kataster_number = cave_id)[0]
cave_and_ent = CaveAndEntrance.objects.filter(cave = cave).filter(entrance_letter = ent_letter)[0]
return render_response(request,'entrance.html', {'cave': cave,
return render_with_context(request,'entrance.html', {'cave': cave,
'entrance': cave_and_ent.entrance,
'letter': cave_and_ent.entrance_letter,})
@ -54,7 +54,7 @@ def survexblock(request, survexpath):
survexblock = models.SurvexBlock.objects.get(survexpath=survexpath)
#ftext = survexblock.filecontents()
ftext = survexblock.text
return render_response(request,'survexblock.html', {'survexblock':survexblock, 'ftext':ftext, })
return render_with_context(request,'survexblock.html', {'survexblock':survexblock, 'ftext':ftext, })
def subcave(request, cave_id, subcave):
print subcave
@ -67,7 +67,7 @@ def subcave(request, cave_id, subcave):
if subcaveUrlSegment:
subcave=subcave.children.get(title=subcaveUrlSegment)
print subcave
return render_response(request,'subcave.html', {'subcave': subcave,'cave':cave})
return render_with_context(request,'subcave.html', {'subcave': subcave,'cave':cave})
def caveSearch(request):
query_string = ''
@ -77,13 +77,13 @@ def caveSearch(request):
entry_query = search.get_query(query_string, ['underground_description','official_name',])
found_entries = Cave.objects.filter(entry_query)
return render_response(request,'cavesearch.html',
return render_with_context(request,'cavesearch.html',
{ 'query_string': query_string, 'found_entries': found_entries,})
def surveyindex(request):
surveys=Survey.objects.all()
expeditions=Expedition.objects.order_by("-year")
return render_response(request,'survey.html',locals())
return render_with_context(request,'survey.html',locals())
def survey(request,year,wallet_number):
surveys=Survey.objects.all()
@ -96,4 +96,4 @@ def survey(request,year,wallet_number):
planSketches=current_survey.scannedimage_set.filter(contents='plan')
elevationSketches=current_survey.scannedimage_set.filter(contents='elevation')
return render_response(request,'survey.html', locals())
return render_with_context(request,'survey.html', locals())

View File

@ -5,11 +5,11 @@ from django.db import models
from troggle.parsers.logbooks import LoadLogbookForExpedition
from troggle.parsers.people import GetPersonExpeditionNameLookup
from troggle.core.forms import PersonForm
from django.core.urlresolvers import reverse
from django.core.urlresolvers import reverse
from django.http import HttpResponseRedirect
# Django uses Context, not RequestContext when you call render_to_response. We always want to use RequestContext, so that django adds the context from settings.TEMPLATE_CONTEXT_PROCESSORS. This way we automatically get necessary settings variables passed to each template. So we use a custom method, render_response instead of render_to_response. Hopefully future Django releases will make this unnecessary.
from troggle.alwaysUseRequestContext import render_response
from utils import render_with_context
import search
import re
@ -37,7 +37,7 @@ def personindex(request):
if person.bisnotable():
notablepersons.append(person)
return render_response(request,'personindex.html', {'persons': persons, 'personss':personss, 'notablepersons':notablepersons, })
return render_with_context(request,'personindex.html', {'persons': persons, 'personss':personss, 'notablepersons':notablepersons, })
def expedition(request, expeditionname):
year = int(expeditionname)
@ -49,7 +49,7 @@ def expedition(request, expeditionname):
message = LoadLogbookForExpedition(expedition)
#message = str(GetPersonExpeditionNameLookup(expedition).keys())
logbookentries = expedition.logbookentry_set.order_by('date')
return render_response(request,'expedition.html', {'expedition': expedition, 'expedition_next':expedition_next, 'expedition_prev':expedition_prev, 'logbookentries':logbookentries, 'message':message, })
return render_with_context(request,'expedition.html', {'expedition': expedition, 'expedition_next':expedition_next, 'expedition_prev':expedition_prev, 'logbookentries':logbookentries, 'message':message, })
def get_absolute_url(self):
return ('expedition', (expedition.year))
@ -64,7 +64,7 @@ def person(request, first_name='', last_name='', ):
person.save()
return HttpResponseRedirect(reverse('profiles_select_profile'))
return render_response(request,'person.html', {'person': person, })
return render_with_context(request,'person.html', {'person': person, })
def get_absolute_url(self):
return settings.URL_ROOT + self.first_name + '_' + self.last_name
@ -77,7 +77,7 @@ def personexpedition(request, first_name='', last_name='', year=''):
person = Person.objects.get(first_name = first_name, last_name = last_name)
expedition = Expedition.objects.get(year=year)
personexpedition = person.personexpedition_set.get(expedition=expedition)
return render_response(request,'personexpedition.html', {'personexpedition': personexpedition, })
return render_with_context(request,'personexpedition.html', {'personexpedition': personexpedition, })
def newQMlink(logbookentry):
biggestQMnumber=0
@ -101,10 +101,10 @@ def logbookentry(request, date, slug):
logbookentry = LogbookEntry.objects.filter(date=date, slug=slug)
if len(logbookentry)>1:
return render_response(request, 'object_list.html',{'object_list':logbookentry})
return render_with_context(request, 'object_list.html',{'object_list':logbookentry})
else:
logbookentry=logbookentry[0]
return render_response(request, 'logbookentry.html', {'logbookentry': logbookentry, 'newQMlink':newQMlink(logbookentry)})
return render_with_context(request, 'logbookentry.html', {'logbookentry': logbookentry, 'newQMlink':newQMlink(logbookentry)})
def logbookSearch(request, extra):
query_string = ''
@ -114,11 +114,11 @@ def logbookSearch(request, extra):
entry_query = search.get_query(query_string, ['text','title',])
found_entries = LogbookEntry.objects.filter(entry_query)
return render_response(request,'logbooksearch.html',
return render_with_context(request,'logbooksearch.html',
{ 'query_string': query_string, 'found_entries': found_entries, })
#context_instance=RequestContext(request))
def personForm(request,pk):
person=Person.objects.get(pk=pk)
form=PersonForm(instance=person)
return render_response(request,'personform.html', {'form':form,})
return render_with_context(request,'personform.html', {'form':form,})

View File

@ -8,7 +8,7 @@ import re
import randSent
from django.http import HttpResponse, HttpResponseRedirect
from django.core.urlresolvers import reverse
from troggle.alwaysUseRequestContext import render_response # see views_logbooks for explanation on this.
from utils import render_with_context
from core.models import *
def showrequest(request):
@ -20,7 +20,7 @@ def stats(request):
statsDict['caveCount'] = int(Cave.objects.count())
statsDict['personCount'] = int(Person.objects.count())
statsDict['logbookEntryCount'] = int(LogbookEntry.objects.count())
return render_response(request,'statistics.html', statsDict)
return render_with_context(request,'statistics.html', statsDict)
def frontpage(request):
message = "no test message" #reverse('personn', kwargs={"name":"hkjhjh"})
@ -37,7 +37,7 @@ def frontpage(request):
cave = Cave
photo = Photo
from django.contrib.admin.templatetags import log
return render_response(request,'frontpage.html', locals())
return render_with_context(request,'frontpage.html', locals())
def todo(request):
message = "no test message" #reverse('personn', kwargs={"name":"hkjhjh"})
@ -51,7 +51,7 @@ def todo(request):
#'randSent':randSent.randomLogbookSentence(),
expeditions = Expedition.objects.order_by("-year")
totallogbookentries = LogbookEntry.objects.count()
return render_response(request,'index.html', {'expeditions':expeditions, 'all':'all', 'totallogbookentries':totallogbookentries, "message":message})
return render_with_context(request,'index.html', {'expeditions':expeditions, 'all':'all', 'totallogbookentries':totallogbookentries, "message":message})
def calendar(request,year):
week=['S','S','M','T','W','T','F']
@ -59,7 +59,7 @@ def calendar(request,year):
expedition=Expedition.objects.get(year=year)
PersonExpeditions=expedition.personexpedition_set.all()
return render_response(request,'calendar.html', locals())
return render_with_context(request,'calendar.html', locals())
def controlPanel(request):
jobs_completed=[]
@ -77,11 +77,11 @@ def controlPanel(request):
jobs_completed.append(item)
else:
if request.user.is_authenticated(): #The user is logged in, but is not a superuser.
return render_response(request,'controlPanel.html', {'caves':Cave.objects.all(),'error':'You must be a superuser to use that feature.'})
return render_with_context(request,'controlPanel.html', {'caves':Cave.objects.all(),'error':'You must be a superuser to use that feature.'})
else:
return HttpResponseRedirect(reverse('auth_login'))
return render_response(request,'controlPanel.html', {'caves':Cave.objects.all(),'expeditions':Expedition.objects.all(),'jobs_completed':jobs_completed})
return render_with_context(request,'controlPanel.html', {'caves':Cave.objects.all(),'expeditions':Expedition.objects.all(),'jobs_completed':jobs_completed})
def downloadCavetab(request):
from export import tocavetab
@ -152,4 +152,4 @@ def ajax_test(request):
mimetype="application/json")
def eyecandy(request):
return render_response(request,'eyecandy.html', {})
return render_with_context(request,'eyecandy.html', {})

View File

@ -4,7 +4,7 @@ import csv
from django.conf import settings
from core.models import QM, LogbookEntry, Cave
from datetime import *
from troggle.save_carefully import save_carefully
from utils import save_carefully
import re, os
def deleteQMs():

View File

@ -2,7 +2,7 @@
import troggle.core.models as models
from django.conf import settings
import csv, time, re, os, logging
from troggle.save_carefully import save_carefully
from utils import save_carefully
##format of CAVETAB2.CSV is
KatasterNumber = 0

View File

@ -13,7 +13,7 @@ import re
import datetime
import os
from troggle.save_carefully import save_carefully
from utils import save_carefully
#
# When we edit logbook entries, allow a "?" after any piece of data to say we've frigged it and

View File

@ -3,18 +3,7 @@
from django.conf import settings
import core.models as models
import csv, re, datetime, os, shutil
from troggle.save_carefully import save_carefully
# Julian: the below code was causing errors and it seems like a duplication of the above. Hope I haven't broken anything by commenting it. -Aaron
#
# if name in expoers2008:
# print "2008:", name
# expomissing.discard(name) # I got an error which I think was caused by this -- python complained that a set changed size during iteration.
# yo = models.Expedition.objects.filter(year = "2008")[0]
# pyo = models.PersonExpedition(person = pObject, expedition = yo, is_guest=is_guest)
# pyo.save()
from utils import save_carefully
def saveMugShot(mugShotPath, mugShotFilename, person):
if mugShotFilename.startswith(r'i/'): #if filename in cell has the directory attached (I think they all do), remove it
@ -39,7 +28,7 @@ def saveMugShot(mugShotPath, mugShotFilename, person):
mugShotObj.save()
def parseMugShotAndBlurb(personline, header, person):
#create mugshot Photo instance
"""create mugshot Photo instance"""
mugShotFilename=personline[header["Mugshot"]]
mugShotPath = os.path.join(settings.EXPOWEB, "folk", mugShotFilename)
if mugShotPath[-3:]=='jpg': #if person just has an image, add it

View File

@ -7,7 +7,7 @@ import sys, os
import os, re, logging
from django.conf import settings
from core.models import Subcave, Cave
from troggle.save_carefully import save_carefully
from utils import save_carefully
def getLinksInCaveDescription(cave):
'''

View File

@ -10,7 +10,7 @@ from PIL import Image
import csv
import re
import datetime
from save_carefully import save_carefully
from utils import save_carefully
def get_or_create_placeholder(year):
""" All surveys must be related to a logbookentry. We don't have a way to

View File

@ -16,8 +16,6 @@ from django import forms
from core.models import Person
from troggle.alwaysUseRequestContext import render_response
from profiles import utils
from django.conf import settings

View File

@ -1,29 +0,0 @@
import logging
def save_carefully(objectType, lookupAttribs={}, nonLookupAttribs={}):
"""Looks up instance using lookupAttribs and carries out the following:
-if instance does not exist in DB: add instance to DB, return (new instance, True)
-if instance exists in DB and was modified using Troggle: do nothing, return (existing instance, False)
-if instance exists in DB and was not modified using Troggle: overwrite instance, return (instance, False)
The checking is accomplished using Django's get_or_create and the new_since_parsing boolean field
defined in core.models.TroggleModel.
"""
instance, created=objectType.objects.get_or_create(defaults=nonLookupAttribs, **lookupAttribs)
if not created and not instance.new_since_parsing:
for k, v in nonLookupAttribs.items(): #overwrite the existing attributes from the logbook text (except date and title)
setattr(instance, k, v)
instance.save()
if created:
logging.info(unicode(instance)+u' was just added to the database for the first time. \n')
if not created and instance.new_since_parsing:
logging.info(unicode(instance)+" has been modified using Troggle, so the current script left it as is. \n")
if not created and not instance.new_since_parsing:
logging.info(unicode(instance)+" existed in the database unchanged since last parse. It was overwritten by the current script. \n")
return (instance, created)

View File

@ -47,6 +47,10 @@
<div id="related">
{% block related %}
<script language="javascript">
$('#related').remove()
/*This is a hack to stop a line appearing because of the empty div border*/
</script>
{% endblock %}
</div>

View File

@ -1,23 +0,0 @@
{% extends "base.html" %}
{% load wiki_markup %}
{% block title %}
Cave search results for "{{ query_string }}"
{% endblock%}
{% block content %}
<h1> Troggle cave search </h1>
Your search string, <b>{{ query_string }}</b>,
{% if found_entries %}
was found in the following <b>{{found_entries.count}}</b> cave underground descriptions and / or official names:
<ul>
{% for cave in found_entries %}
<li><a href="{{ settings.URL_ROOT }}cave/{{ cave.kataster_number }}">{{ cave|wiki_to_html_short }} : {{cave.official_name|wiki_to_html_short }}</a></li>
{% endfor %}
</ul>
{% else %}
was not found in any cave underground descriptions and / or official names. Please try again.
{% endif %}
{% endblock %}

69
utils.py Normal file
View File

@ -0,0 +1,69 @@
from django.conf import settings
from troggle.core.models import LogbookEntry
import random, re, logging
def weighted_choice(lst):
n = random.uniform(0,1)
for item, weight in lst:
if n < weight:
break
n = n - weight
return item
def randomLogbookSentence():
randSent={}
# needs to handle empty logbooks without crashing
#Choose a random logbook entry
randSent['entry']=LogbookEntry.objects.order_by('?')[0]
#Choose again if there are no sentances (this happens if it is a placeholder entry)
while len(re.findall('[A-Z].*?\.',randSent['entry'].text))==0:
randSent['entry']=LogbookEntry.objects.order_by('?')[0]
#Choose a random sentence from that entry. Store the sentence as randSent['sentence'], and the number of that sentence in the entry as randSent['number']
sentenceList=re.findall('[A-Z].*?\.',randSent['entry'].text)
randSent['number']=random.randrange(0,len(sentenceList))
randSent['sentence']=sentenceList[randSent['number']]
return randSent
def save_carefully(objectType, lookupAttribs={}, nonLookupAttribs={}):
"""Looks up instance using lookupAttribs and carries out the following:
-if instance does not exist in DB: add instance to DB, return (new instance, True)
-if instance exists in DB and was modified using Troggle: do nothing, return (existing instance, False)
-if instance exists in DB and was not modified using Troggle: overwrite instance, return (instance, False)
The checking is accomplished using Django's get_or_create and the new_since_parsing boolean field
defined in core.models.TroggleModel.
"""
instance, created=objectType.objects.get_or_create(defaults=nonLookupAttribs, **lookupAttribs)
if not created and not instance.new_since_parsing:
for k, v in nonLookupAttribs.items(): #overwrite the existing attributes from the logbook text (except date and title)
setattr(instance, k, v)
instance.save()
if created:
logging.info(unicode(instance)+u' was just added to the database for the first time. \n')
if not created and instance.new_since_parsing:
logging.info(unicode(instance)+" has been modified using Troggle, so the current script left it as is. \n")
if not created and not instance.new_since_parsing:
logging.info(unicode(instance)+" existed in the database unchanged since last parse. It was overwritten by the current script. \n")
return (instance, created)
def render_with_context(req, *args, **kwargs):
"""this is the snippet from http://www.djangosnippets.org/snippets/3/
Django uses Context, not RequestContext when you call render_to_response. We always want to use RequestContext, so that django adds the context from settings.TEMPLATE_CONTEXT_PROCESSORS. This way we automatically get necessary settings variables passed to each template. So we use a custom method, render_response instead of render_to_response. Hopefully future Django releases will make this unnecessary."""
from django.shortcuts import render_to_response
from django.template import RequestContext
kwargs['context_instance'] = RequestContext(req)
return render_to_response(*args, **kwargs)