You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@steve.apache.org by hu...@apache.org on 2015/03/30 12:08:20 UTC

svn commit: r1670034 - in /steve/trunk/pysteve/lib: backends/es.py backends/files.py constants.py election.py voter.py

Author: humbedooh
Date: Mon Mar 30 10:08:20 2015
New Revision: 1670034

URL: http://svn.apache.org/r1670034
Log:
class-ify backends

Modified:
    steve/trunk/pysteve/lib/backends/es.py
    steve/trunk/pysteve/lib/backends/files.py
    steve/trunk/pysteve/lib/constants.py
    steve/trunk/pysteve/lib/election.py
    steve/trunk/pysteve/lib/voter.py

Modified: steve/trunk/pysteve/lib/backends/es.py
URL: http://svn.apache.org/viewvc/steve/trunk/pysteve/lib/backends/es.py?rev=1670034&r1=1670033&r2=1670034&view=diff
==============================================================================
--- steve/trunk/pysteve/lib/backends/es.py (original)
+++ steve/trunk/pysteve/lib/backends/es.py Mon Mar 30 10:08:20 2015
@@ -21,212 +21,190 @@ import random
 import time
 from lib import constants
 
-es = None
-
-def init(config):
-    global es
-    from elasticsearch import Elasticsearch
-    es = Elasticsearch([
-                    {
-                        'host': config.get("elasticsearch", "host"),
-                        'port': int(config.get("elasticsearch", "port")),
-                        'url_prefix': config.get("elasticsearch", "uri"),
-                        'use_ssl': False if config.get("elasticsearch", "secure") == "false" else True
-                    },
-                ])
-    if not es.indices.exists("steve"):
-        es.indices.create(index = "steve", body = {
-                "settings": {
-                    "number_of_shards" : 3,
-                    "number_of_replicas" : 1
-                }
-            }
-        )
+class ElasticSearchBackend:
+    es = None
     
-
-
-def exists(election, *issue):
-    doc = "elections"
-    eid = election
-    if issue and issue[0]:
-        doc = "issues"
-        eid = hashlib.sha224(election + "/" + issue[0]).hexdigest()
-    return es.exists(index="steve", doc_type=doc, id=eid)
+    def __init__(self, config):
+        from elasticsearch import Elasticsearch
+        self.es = Elasticsearch([
+                        {
+                            'host': config.get("elasticsearch", "host"),
+                            'port': int(config.get("elasticsearch", "port")),
+                            'url_prefix': config.get("elasticsearch", "uri"),
+                            'use_ssl': False if config.get("elasticsearch", "secure") == "false" else True
+                        },
+                    ])
+        if not self.es.indices.exists("steve"):
+            self.es.indices.create(index = "steve", body = {
+                    "settings": {
+                        "number_of_shards" : 3,
+                        "number_of_replicas" : 1
+                    }
+                }
+            )
+        
     
     
-
-def getBasedata(election):
-    "Get base data from an election"
-    res = es.get(index="steve", doc_type="elections", id=election)
-    if res:
-        return res['_source']
-    return None
-
-
-def close(election, reopen = False):
-    "Mark an election as closed"
-    basedata = getBasedata(election)
-    if reopen:
-        basedata['closed'] = False
-    else:
-        basedata['closed'] = True
-    es.index(index="steve", doc_type="elections", id=election, body = basedata )
+    def document_exists(self, election, *issue):
+        doc = "elections"
+        eid = election
+        if issue and issue[0]:
+            doc = "issues"
+            eid = hashlib.sha224(election + "/" + issue[0]).hexdigest()
+        return self.es.exists(index="steve", doc_type=doc, id=eid)
         
-
-def getIssue(electionID, issueID):
-    "Get JSON data from an issue"
-    issuedata = None
-    ihash = ""
-    iid = hashlib.sha224(electionID + "/" + issueID).hexdigest()
-    res = es.get(index="steve", doc_type="issues", id=iid)
-    if res:
-        issuedata = res['_source']
-        ihash = hashlib.sha224(json.dumps(issuedata)).hexdigest()
-    return issuedata, ihash
-
-
-def getVotes(electionID, issueID):
-    "Read votes from the vote file"
-    res = es.search(index="steve", doc_type="votes", q = "election:%s AND issue:%s" % (electionID, issueID), size = 9999999)
-    results = len(res['hits']['hits'])
-    if results > 0:
-        votes = {}
-        for entry in res['hits']['hits']:
-            votes[entry['_source']['key']] = entry['_source']['data']['vote']
-        return votes
-    return {}
-
-
-
-def getVotesRaw(electionID, issueID):
-    res = es.search(index="steve", doc_type="votes", q = "election:%s AND issue:%s" % (electionID, issueID), size = 9999999)
-    results = len(res['hits']['hits'])
-    if results > 0:
-        votes = {}
-        for entry in res['hits']['hits']:
-            votes[entry['_source']['key']] = entry['_source']['data']
-        return votes
-    return {}
-
-
-def createElection(electionID, basedata):
-    "Create a new election"
-    es.index(index="steve", doc_type="elections", id=electionID, body =
-        basedata
-    );
-
-def updateElection(electionID, basedata):
-    es.index(index = "steve", doc_type = "elections", id=electionID, body = basedata)
-
-def updateIssue(electionID, issueID, issueData):
-    es.index(index = "steve", doc_type = "issues", id=hashlib.sha224(electionID + "/" + issueID).hexdigest(), body = issueData)
-
-
-def listIssues(election):
-    "List all issues in an election"
-    issues = []
-    try:
-        res = es.search(index="steve", doc_type="issues", sort = "id", q = "election:%s" % election, size = 999)
+        
+    
+    def get_basedata(self, election):
+        "Get base data from an election"
+        res = self.es.get(index="steve", doc_type="elections", id=election)
+        if res:
+            return res['_source']
+        return None
+    
+    
+    def close(self, election, reopen = False):
+        "Mark an election as closed"
+        basedata = getBasedata(election)
+        if reopen:
+            basedata['closed'] = False
+        else:
+            basedata['closed'] = True
+        self.es.index(index="steve", doc_type="elections", id=election, body = basedata )
+            
+    
+    def issue_get(self, electionID, issueID):
+        "Get JSON data from an issue"
+        issuedata = None
+        ihash = ""
+        iid = hashlib.sha224(electionID + "/" + issueID).hexdigest()
+        res = self.es.get(index="steve", doc_type="issues", id=iid)
+        if res:
+            issuedata = res['_source']
+            ihash = hashlib.sha224(json.dumps(issuedata)).hexdigest()
+        return issuedata, ihash
+    
+    
+    def votes_get(self, electionID, issueID):
+        "Read votes from the vote file"
+        res = self.es.search(index="steve", doc_type="votes", q = "election:%s AND issue:%s" % (electionID, issueID), size = 9999999)
         results = len(res['hits']['hits'])
         if results > 0:
+            votes = {}
             for entry in res['hits']['hits']:
-                issues.append(entry['_source']['id'])
-    except:
-        pass # THIS IS OKAY! ES WILL FAIL IF THERE ARE NO ISSUES YET
-    return issues
-
-def listElections():
-    "List all elections"
-    elections = []
-    try:
-        res = es.search(index="steve", doc_type="elections", sort = "id", q = "*", size = 99999)
+                votes[entry['_source']['key']] = entry['_source']['data']['vote']
+            return votes
+        return {}
+    
+    
+    
+    def votes_get_raw(self, electionID, issueID):
+        res = self.es.search(index="steve", doc_type="votes", q = "election:%s AND issue:%s" % (electionID, issueID), size = 9999999)
         results = len(res['hits']['hits'])
         if results > 0:
+            votes = {}
             for entry in res['hits']['hits']:
-                source  = entry['_source']
-                elections.append(source['id'])
-    except Exception as err:
-        pass # THIS IS OKAY! On initial setup, this WILL fail until an election has been created
-    return elections
-
-def vote(electionID, issueID, uid, vote):
-    "Casts a vote on an issue"
-    eid = hashlib.sha224(electionID + ":" + issueID + ":" + uid).hexdigest()
-    es.index(index="steve", doc_type="votes", id=eid, body =
-        {
-            'issue': issueID,
-            'election': electionID,
-            'key': uid,
-            'data': {
-                'timestamp': time.time(),
-                'vote': vote
+                votes[entry['_source']['key']] = entry['_source']['data']
+            return votes
+        return {}
+    
+    
+    def election_create(self,electionID, basedata):
+        "Create a new election"
+        self.es.index(index="steve", doc_type="elections", id=electionID, body =
+            basedata
+        );
+    
+    def election_update(self,electionID, basedata):
+        self.es.index(index = "steve", doc_type = "elections", id=electionID, body = basedata)
+    
+    def issue_update(self,electionID, issueID, issueData):
+        self.es.index(index = "steve", doc_type = "issues", id=hashlib.sha224(electionID + "/" + issueID).hexdigest(), body = issueData)
+    
+    
+    def issue_list(self, election):
+        "List all issues in an election"
+        issues = []
+        try:
+            res = self.es.search(index="steve", doc_type="issues", sort = "id", q = "election:%s" % election, size = 999)
+            results = len(res['hits']['hits'])
+            if results > 0:
+                for entry in res['hits']['hits']:
+                    issues.append(entry['_source']['id'])
+        except:
+            pass # THIS IS OKAY! ES WILL FAIL IF THERE ARE NO ISSUES YET
+        return issues
+    
+    def election_list(self):
+        "List all elections"
+        elections = []
+        try:
+            res = self.es.search(index="steve", doc_type="elections", sort = "id", q = "*", size = 99999)
+            results = len(res['hits']['hits'])
+            if results > 0:
+                for entry in res['hits']['hits']:
+                    source  = entry['_source']
+                    elections.append(source['id'])
+        except Exception as err:
+            pass # THIS IS OKAY! On initial setup, this WILL fail until an election has been created
+        return elections
+    
+    def vote(self,electionID, issueID, uid, vote):
+        "Casts a vote on an issue"
+        eid = hashlib.sha224(electionID + ":" + issueID + ":" + uid).hexdigest()
+        self.es.index(index="steve", doc_type="votes", id=eid, body =
+            {
+                'issue': issueID,
+                'election': electionID,
+                'key': uid,
+                'data': {
+                    'timestamp': time.time(),
+                    'vote': vote
+                }
             }
-        }
-    );
+        );
+        
+        
+    def issue_delete(self, electionID, issueID):
+        "Deletes an issue if it exists"
+        self.es.delete(index="steve", doc_type="issues", id=hashlib.sha224(electionID + "/" + issueID).hexdigest());
+        
+    def issue_create(self,electionID, issueID, data):
+        self.es.index(index="steve", doc_type="issues", id=hashlib.sha224(electionID + "/" + issueID).hexdigest(), body = data);
     
     
-def deleteIssue(electionID, issueID):
-    "Deletes an issue if it exists"
-    es.delete(index="steve", doc_type="issues", id=hashlib.sha224(electionID + "/" + issueID).hexdigest());
     
-def createIssue(electionID, issueID, data):
-    es.index(index="steve", doc_type="issues", id=hashlib.sha224(electionID + "/" + issueID).hexdigest(), body = data);
-
-
-
-def voter_get(electionID, votekey):
-    "Get the UID/email for a voter given the vote key hash"
-    try:
-        res = es.search(index="steve", doc_type="voters", q = "election:%s" % electionID, size = 999999)
-        results = len(res['hits']['hits'])
-        if results > 0:
-            for entry in res['hits']['hits']:
-                voter = entry['_source']
-                if voter['hash'] == votekey:
-                    return voter['uid']
-    except:
-        return False # ES Error, probably not seeded the voters doc yet
-
-def voter_add(election, PID, xhash):
-    eid = hashlib.sha224(election + ":" + PID).hexdigest()
-    es.index(index="steve", doc_type="voters", id=eid, body = {
-        'election': election,
-        'hash': xhash,
-        'uid': PID
-        }
-    )
-    
-def voter_remove(election, UID):
-    votehash = hashlib.sha224(election + ":" + UID).hexdigest()
-    es.delete(index="steve", doc_type="voters", id=votehash);
-
-def voter_has_voted(election, issue, uid):
-    eid = hashlib.sha224(election + ":" + issue + ":" + uid).hexdigest()
-    try:
-        return es.exists(index="steve", doc_type="votes", id=eid)
-    except:
-        return False
+    def voter_get_uid(self, electionID, votekey):
+        "Get the UID/email for a voter given the vote key hash"
+        try:
+            res = self.es.search(index="steve", doc_type="voters", q = "election:%s" % electionID, size = 999999)
+            results = len(res['hits']['hits'])
+            if results > 0:
+                for entry in res['hits']['hits']:
+                    voter = entry['_source']
+                    if voter['hash'] == votekey:
+                        return voter['uid']
+        except:
+            return False # ES Error, probably not seeded the voters doc yet
+    
+    def voter_add(self,election, PID, xhash):
+        eid = hashlib.sha224(election + ":" + PID).hexdigest()
+        self.es.index(index="steve", doc_type="voters", id=eid, body = {
+            'election': election,
+            'hash': xhash,
+            'uid': PID
+            }
+        )
+        
+    def voter_remove(self,election, UID):
+        votehash = hashlib.sha224(election + ":" + UID).hexdigest()
+        self.es.delete(index="steve", doc_type="voters", id=votehash);
+    
+    def voter_has_voted(self,election, issue, uid):
+        eid = hashlib.sha224(election + ":" + issue + ":" + uid).hexdigest()
+        try:
+            return self.es.exists(index="steve", doc_type="votes", id=eid)
+        except:
+            return False
 
-constants.appendBackend( {
-    'id': 'elasticsearch',
-    'init': init,
-    'document_exists': exists,
-    'get_basedata': getBasedata,
-    'election_close': close,
-    'election_vote': vote,
-    'election_list': listElections,
-    'issue_list': listIssues,
-    'election_create': createElection,
-    'issue_create': createIssue,
-    'issue_delete': deleteIssue,
-    'election_update': updateElection,
-    'issue_update': updateIssue,
-    'issue_get': getIssue,
-    'vote': vote,
-    'votes_get': getVotes,
-    'votes_get_raw': getVotesRaw,
-    'voter_get_uid': voter_get,
-    'voter_add': voter_add,
-    'voter_remove': voter_remove,
-    'voter_has_voted': voter_has_voted
-})
\ No newline at end of file
+constants.appendBackend("elasticsearch", ElasticSearchBackend)
\ No newline at end of file

Modified: steve/trunk/pysteve/lib/backends/files.py
URL: http://svn.apache.org/viewvc/steve/trunk/pysteve/lib/backends/files.py?rev=1670034&r1=1670033&r2=1670034&view=diff
==============================================================================
--- steve/trunk/pysteve/lib/backends/files.py (original)
+++ steve/trunk/pysteve/lib/backends/files.py Mon Mar 30 10:08:20 2015
@@ -22,218 +22,196 @@ import time
 
 from lib import constants
 
-homedir = None
-
-def init(config):
-    global homedir
-    homedir = config.get("general", "homedir")
+class FileBasedBackend:
+    homedir = None
     
-
-def exists(election, *issue):
-    "Returns True if an election/issue exists, False otherwise"
-    elpath = os.path.join(homedir, "issues", election)
-    if issue:
-        elpath += "/" + issue[0] + ".json"
-        return os.path.isfile(elpath)
-    else:
-        return os.path.isdir(elpath)
-
-
-def getBasedata(election):
-    "Get base data from an election"
-    elpath = os.path.join(homedir, "issues", election)
-    if os.path.isdir(elpath):
-        with open(elpath + "/basedata.json", "r") as f:
-            data = f.read()
-            f.close()
-            basedata = json.loads(data)
-            if hideHash and 'hash' in basedata:
-                del basedata['hash']
-            basedata['id'] = election
-            return basedata
-    return None
-
-def close(election, reopen = False):
-    "Mark an election as closed"
-
-    elpath = os.path.join(homedir, "issues", election)
-    basedata = getBasedata(election)
-    if reopen:
-        basedata['closed'] = False
-    else:
-        basedata['closed'] = True
-    with open(elpath + "/basedata.json", "w") as f:
-        f.write(json.dumps(basedata))
-        f.close()
-
-
-def getIssue(electionID, issueID):
-    "Get JSON data from an issue"
-    issuedata = None
-    ihash = ""
-    issuepath = os.path.join(homedir, "issues", electionID, issueID) + ".json"
-    if os.path.isfile(issuepath):        
-        with open(issuepath, "r") as f:
-            data = f.read()
-            ihash = hashlib.sha224(data).hexdigest()
+    def __init__(self, config):
+        self.homedir = config.get("general", "homedir")
+    
+    
+    def document_exists(election, *issue):
+        "Returns True if an election/issue exists, False otherwise"
+        elpath = os.path.join(self.homedir, "issues", election)
+        if issue:
+            elpath += "/" + issue[0] + ".json"
+            return os.path.isfile(elpath)
+        else:
+            return os.path.isdir(elpath)
+    
+    
+    def get_basedata(election):
+        "Get base data from an election"
+        elpath = os.path.join(self.homedir, "issues", election)
+        if os.path.isdir(elpath):
+            with open(elpath + "/basedata.json", "r") as f:
+                data = f.read()
+                f.close()
+                basedata = json.loads(data)
+                if hideHash and 'hash' in basedata:
+                    del basedata['hash']
+                basedata['id'] = election
+                return basedata
+        return None
+    
+    def close(election, reopen = False):
+        "Mark an election as closed"
+    
+        elpath = os.path.join(self.homedir, "issues", election)
+        basedata = getBasedata(election)
+        if reopen:
+            basedata['closed'] = False
+        else:
+            basedata['closed'] = True
+        with open(elpath + "/basedata.json", "w") as f:
+            f.write(json.dumps(basedata))
             f.close()
-            issuedata = json.loads(data)
-
-    return issuedata, ihash
-
-
-def getVotes(electionID, issueID):
-    "Read votes from the vote file"
-    rvotes = getVotesRaw(electionID, issueID)
-    votes = {}
-    for key in rvotes:
-        votes[key] = rvotes[key]['vote']
-    return {}
-
-
-def getVotesRaw(electionID, issueID):
-    issuepath = os.path.join(homedir, "issues", electionID, issueID) + ".json.votes"
-    if os.path.isfile(issuepath):
-        with open(issuepath, "r") as f:
-            votes = json.loads(f.read())
+    
+    
+    def issue_get(electionID, issueID):
+        "Get JSON data from an issue"
+        issuedata = None
+        ihash = ""
+        issuepath = os.path.join(self.homedir, "issues", electionID, issueID) + ".json"
+        if os.path.isfile(issuepath):        
+            with open(issuepath, "r") as f:
+                data = f.read()
+                ihash = hashlib.sha224(data).hexdigest()
+                f.close()
+                issuedata = json.loads(data)
+    
+        return issuedata, ihash
+    
+    
+    def votes_get(electionID, issueID):
+        "Read votes from the vote file"
+        rvotes = getVotesRaw(electionID, issueID)
+        votes = {}
+        for key in rvotes:
+            votes[key] = rvotes[key]['vote']
+        return {}
+    
+    
+    def votes_get_raw(electionID, issueID):
+        issuepath = os.path.join(self.homedir, "issues", electionID, issueID) + ".json.votes"
+        if os.path.isfile(issuepath):
+            with open(issuepath, "r") as f:
+                votes = json.loads(f.read())
+                f.close()
+                return votes
+        return {}
+    
+    
+    def election_create(eid, basedata):
+        elpath = os.path.join(self.homedir, "issues", eid)
+        os.mkdir(elpath)
+        with open(elpath  + "/basedata.json", "w") as f:
+            f.write(json.dumps(basedata))
+            f.close()
+        with open(elpath  + "/voters.json", "w") as f:
+            f.write("{}")
             f.close()
-            return votes
-    return {}
-
-
-def createElection(eid, basedata):
-    elpath = os.path.join(homedir, "issues", eid)
-    os.mkdir(elpath)
-    with open(elpath  + "/basedata.json", "w") as f:
-        f.write(json.dumps(basedata))
-        f.close()
-    with open(elpath  + "/voters.json", "w") as f:
-        f.write("{}")
-        f.close()
-
-
-def updateElection(electionID, basedata):
-    elpath = os.path.join(homedir, "issues", electionID)
-    with open(elpath  + "/basedata.json", "w") as f:
-        f.write(json.dumps(basedata))
-        f.close()
-
-def updateIssue(electionID, issueID, issueData):
-    issuepath = os.path.join(homedir, "issues", electionID, issueID) + ".json"
-    with open(issuepath, "w") as f:
-        f.write(json.dumps(issueData))
-        f.close()
-
-
-def listIssues(election):
-    "List all issues in an election"
-    issues = []
-    elpath = os.path.join(homedir, "issues", election)
-    if os.path.isdir(elpath):
-        issues = [f.strip(".json") for f in os.listdir(elpath) if os.path.isfile(os.path.join(elpath, f)) and f != "basedata.json" and f != "voters.json" and f.endswith(".json")]
-    return issues
-
-def listElections():
-    "List all elections"
-    elections = []
-    path = os.path.join(homedir, "issues")
-    if os.path.isdir(path):
-        elections = [f for f in os.listdir(path) if os.path.isdir(os.path.join(path, f))]
-    return elections
-
-def vote(electionID, issueID, uid, vote):
-    "Casts a vote on an issue"
-    votes = {}
-    issuepath = os.path.join(homedir, "issues", electionID, issueID) + ".json"
-    if os.path.isfile(issuepath + ".votes"):
-        with open(issuepath + ".votes", "r") as f:
-            votes = json.loads(f.read())
-            f.close()
-    votes[uid] = {
-        'vote': vote,
-        'timestamp': time.time()
-    }
-    with open(issuepath + ".votes", "w") as f:
-        f.write(json.dumps(votes))
-        f.close()
     
-
-def deleteIssue(electionID, issueID):
-    "Deletes an issue if it exists"
     
-    issuepath = os.path.join(homedir, "issues", electionID, issueID) + ".json"
-    if os.path.isfile(issuepath):
-        os.unlink(issuepath)
-    if os.path.isfile(issuepath + ".votes"):
-        os.unlink(issuepath + ".votes")
-
-def createIssue(electionID, issueID, data):
-    issuepath = os.path.join(homedir, "issues", electionID, issueID) + ".json"
-    with open(issuepath, "w") as f:
-        f.write(json.dumps(data))
-        f.close()
-
-def voter_get(electionID, votekey):
-    "Get vote UID/email with a given vote key hash"
-    elpath = os.path.join(homedir, "issues", electionID)
-    with open(elpath + "/voters.json", "r") as f:
-        voters = json.loads(f.read())
-        f.close()
-        for voter in voters:
-            if voters[voter] == xhash:
-                return voter
-    return None
-
-def voter_add(election, PID, xhash):
-    elpath = os.path.join(homedir, "issues", election)
-    with open(elpath + "/voters.json", "r") as f:
-        voters = json.loads(f.read())
-        f.close()
-    voters[PID] = xhash
-    with open(elpath + "/voters.json", "w") as f:
-        f.write(json.dumps(voters))
-        f.close()
-
-def voter_remove(election, UID):
-    elpath = os.path.join(homedir, "issues", election)
-    with open(elpath + "/voters.json", "r") as f:
-        voters = json.loads(f.read())
-        f.close()
-    if UID in voters:
-        del voters[UID]
-    with open(elpath + "/voters.json", "w") as f:
-        f.write(json.dumps(voters))
-        f.close()
+    def election_update(electionID, basedata):
+        elpath = os.path.join(self.homedir, "issues", electionID)
+        with open(elpath  + "/basedata.json", "w") as f:
+            f.write(json.dumps(basedata))
+            f.close()
+    
+    def issue_update(electionID, issueID, issueData):
+        issuepath = os.path.join(self.homedir, "issues", electionID, issueID) + ".json"
+        with open(issuepath, "w") as f:
+            f.write(json.dumps(issueData))
+            f.close()
+    
+    
+    def issue_list(election):
+        "List all issues in an election"
+        issues = []
+        elpath = os.path.join(self.homedir, "issues", election)
+        if os.path.isdir(elpath):
+            issues = [f.strip(".json") for f in os.listdir(elpath) if os.path.isfile(os.path.join(elpath, f)) and f != "basedata.json" and f != "voters.json" and f.endswith(".json")]
+        return issues
+    
+    def election_list():
+        "List all elections"
+        elections = []
+        path = os.path.join(self.homedir, "issues")
+        if os.path.isdir(path):
+            elections = [f for f in os.listdir(path) if os.path.isdir(os.path.join(path, f))]
+        return elections
+    
+    def vote(electionID, issueID, uid, vote):
+        "Casts a vote on an issue"
+        votes = {}
+        issuepath = os.path.join(self.homedir, "issues", electionID, issueID) + ".json"
+        if os.path.isfile(issuepath + ".votes"):
+            with open(issuepath + ".votes", "r") as f:
+                votes = json.loads(f.read())
+                f.close()
+        votes[uid] = {
+            'vote': vote,
+            'timestamp': time.time()
+        }
+        with open(issuepath + ".votes", "w") as f:
+            f.write(json.dumps(votes))
+            f.close()
         
-def voter_has_voted(election, issue, uid):
-    path = os.path.join(homedir, "issues", election, issue)
-    votes = {}
-    if os.path.isfile(path + ".json.votes"):
-        with open(path + ".json.votes", "r") as f:
-            votes = json.loads(f.read())
+    
+    def issue_delete(electionID, issueID):
+        "Deletes an issue if it exists"
+        
+        issuepath = os.path.join(self.homedir, "issues", electionID, issueID) + ".json"
+        if os.path.isfile(issuepath):
+            os.unlink(issuepath)
+        if os.path.isfile(issuepath + ".votes"):
+            os.unlink(issuepath + ".votes")
+    
+    def issue_create(electionID, issueID, data):
+        issuepath = os.path.join(self.homedir, "issues", electionID, issueID) + ".json"
+        with open(issuepath, "w") as f:
+            f.write(json.dumps(data))
+            f.close()
+    
+    def voter_get_uid(electionID, votekey):
+        "Get vote UID/email with a given vote key hash"
+        elpath = os.path.join(self.homedir, "issues", electionID)
+        with open(elpath + "/voters.json", "r") as f:
+            voters = json.loads(f.read())
+            f.close()
+            for voter in voters:
+                if voters[voter] == xhash:
+                    return voter
+        return None
+    
+    def voter_add(election, PID, xhash):
+        elpath = os.path.join(self.homedir, "issues", election)
+        with open(elpath + "/voters.json", "r") as f:
+            voters = json.loads(f.read())
+            f.close()
+        voters[PID] = xhash
+        with open(elpath + "/voters.json", "w") as f:
+            f.write(json.dumps(voters))
+            f.close()
+    
+    def voter_remove(election, UID):
+        elpath = os.path.join(self.homedir, "issues", election)
+        with open(elpath + "/voters.json", "r") as f:
+            voters = json.loads(f.read())
+            f.close()
+        if UID in voters:
+            del voters[UID]
+        with open(elpath + "/voters.json", "w") as f:
+            f.write(json.dumps(voters))
             f.close()
-    return True if uid in votes else False
+            
+    def voter_has_voted(election, issue, uid):
+        path = os.path.join(self.homedir, "issues", election, issue)
+        votes = {}
+        if os.path.isfile(path + ".json.votes"):
+            with open(path + ".json.votes", "r") as f:
+                votes = json.loads(f.read())
+                f.close()
+        return True if uid in votes else False
 
-constants.appendBackend( {
-    'id': 'file',
-    'init': init,
-    'document_exists': exists,
-    'get_basedata': getBasedata,
-    'election_close': close,
-    'election_vote': vote,
-    'election_list': listElections,
-    'issue_list': listIssues,
-    'election_create': createElection,
-    'issue_create': createIssue,
-    'issue_delete': deleteIssue,
-    'election_update': updateElection,
-    'issue_update': updateIssue,
-    'issue_get': getIssue,
-    'vote': vote,
-    'votes_get': getVotes,
-    'votes_get_raw': getVotesRaw,
-    'voter_get_uid': voter_get,
-    'voter_add': voter_add,
-    'voter_remove': voter_remove,
-    'voter_has_voted': voter_has_voted
-})
\ No newline at end of file
+constants.appendBackend("file", FileBasedBackend)
\ No newline at end of file

Modified: steve/trunk/pysteve/lib/constants.py
URL: http://svn.apache.org/viewvc/steve/trunk/pysteve/lib/constants.py?rev=1670034&r1=1670033&r2=1670034&view=diff
==============================================================================
--- steve/trunk/pysteve/lib/constants.py (original)
+++ steve/trunk/pysteve/lib/constants.py Mon Mar 30 10:08:20 2015
@@ -36,17 +36,20 @@ def appendVote(*types):
         if not found:
             VOTE_TYPES += (t,)
         
-def appendBackend(*args):
+def appendBackend(t, c):
     """Append a new database backend"""
     global DB_TYPES
-    for t in args:
-        found = False
-        for v in DB_TYPES:
-            if v['id'] == t['id']:
-                found = True
-                break
-        if not found:
-            DB_TYPES += (t,)
+    found = False
+    for b in DB_TYPES:
+        if b.get('id') == t:
+            found = True
+            break
+    if not found:
+        DB_TYPES += ( {
+            'id': t,
+            'constructor': c
+        },)
+    
             
 def initBackend(config):
     # Set up DB backend
@@ -55,13 +58,11 @@ def initBackend(config):
     dbtype = config.get("database", "dbsys")
     for b in DB_TYPES:
         if b.get('id') == dbtype:
-            backend = b
+            backend = b['constructor'](config)
             break
     
     if not backend:
         raise Exception("Unknown database backend: %s" % dbtype)
-    else:
-        backend['init'](config)
     return backend
 
 # For vote types with N number of seats/spots, this value denotes

Modified: steve/trunk/pysteve/lib/election.py
URL: http://svn.apache.org/viewvc/steve/trunk/pysteve/lib/election.py?rev=1670034&r1=1670033&r2=1670034&view=diff
==============================================================================
--- steve/trunk/pysteve/lib/election.py (original)
+++ steve/trunk/pysteve/lib/election.py Mon Mar 30 10:08:20 2015
@@ -36,20 +36,20 @@ backend = constants.initBackend(config)
 
 def exists(election, *issue):
     "Returns True if an election/issue exists, False otherwise"
-    return backend['document_exists'](election, *issue)
+    return backend.document_exists(election, *issue)
 
 def getBasedata(election, hideHash=False):
     "Get base data from an election"
-    return backend['get_basedata'](election)
+    return backend.get_basedata(election)
 
 def close(election, reopen = False):
     "Mark an election as closed"
-    backend['election_close'](election, reopen)
+    backend.close(election, reopen)
     
 
 def getIssue(electionID, issueID):
     "Get JSON data from an issue"
-    issuedata, ihash = backend['issue_get'](electionID, issueID)
+    issuedata, ihash = backend.issue_get(electionID, issueID)
     if issuedata:
         issuedata['hash'] = ihash
         issuedata['id'] = issueID
@@ -67,10 +67,10 @@ def getIssue(electionID, issueID):
 
 def getVotes(electionID, issueID):
     "Read votes from the vote file"
-    return backend['votes_get'](electionID, issueID)
+    return backend.votes_get(electionID, issueID)
 
 def getVotesRaw(electionID, issueID):
-    return backend['votes_get_raw'](electionID, issueID)
+    return backend.votes_get_raw(electionID, issueID)
 
 
 def createElection(eid, title, owner, monitors, starts, ends, isopen):
@@ -84,24 +84,24 @@ def createElection(eid, title, owner, mo
             'hash': hashlib.sha512("%f-stv-%s" % (time.time(), os.environ['REMOTE_ADDR'] if 'REMOTE_ADDR' in os.environ else random.randint(1,99999999999))).hexdigest(),
             'open': isopen
         }
-    backend['election_create'](eid, basedata)
+    backend.election_create(eid, basedata)
     
 
 def updateElection(electionID, basedata):
-    backend['election_update'](electionID, basedata)
+    backend.election_update(electionID, basedata)
 
 
 def updateIssue(electionID, issueID, issueData):
-    backend['issue_update'](electionID, issueID, issueData)
+    backend.issue_update(electionID, issueID, issueData)
 
 
 def listIssues(election):
     "List all issues in an election"
-    return backend['issue_list'](election)
+    return backend.issue_list(election)
 
 def listElections():
     "List all elections"
-    return backend['election_list']()
+    return backend.election_list()
 
 
 def getVoteType(issue):
@@ -124,7 +124,7 @@ def vote(electionID, issueID, voterID, v
             uid = voter.get(electionID, basedata, voterID)
             voteType['vote_func'](basedata, issueID, voterID, vote, uid)
             
-        backend['vote'](electionID, issueID, voterID, vote)
+        backend.vote(electionID, issueID, voterID, vote)
         
         # LURK on who voted :O :O :O
        # if config.has_option("general", "lurk") and config.get("general", "lurk") == "yes":
@@ -158,7 +158,7 @@ def deleteIssue(electionID, issueID):
     "Deletes an issue if it exists"
     
     if exists(electionID, issueID):
-        backend['issue_delete'](electionID, issueID)
+        backend.issue_delete(electionID, issueID)
     else:
         raise Exception("No such election")
 
@@ -179,4 +179,4 @@ def getHash(electionID):
     return tothash, "\n".join(output)
 
 def createIssue(electionID, issueID, data):
-    backend['issue_create'](electionID, issueID, data)
\ No newline at end of file
+    backend.issue_create(electionID, issueID, data)
\ No newline at end of file

Modified: steve/trunk/pysteve/lib/voter.py
URL: http://svn.apache.org/viewvc/steve/trunk/pysteve/lib/voter.py?rev=1670034&r1=1670033&r2=1670034&view=diff
==============================================================================
--- steve/trunk/pysteve/lib/voter.py (original)
+++ steve/trunk/pysteve/lib/voter.py Mon Mar 30 10:08:20 2015
@@ -29,22 +29,22 @@ backend = constants.initBackend(config)
 
 def get(election, basedata, uid):
     xhash = hashlib.sha512(basedata['hash'] + uid).hexdigest()
-    return backend['voter_get_uid'](election, xhash)
+    return backend.voter_get_uid(election, xhash)
     
         
 def add(election, basedata, PID):
     uid = hashlib.sha224("%s%s%s%s" % (PID, basedata['hash'], time.time(), random.randint(1,99999999))).hexdigest()
     xhash = hashlib.sha512(basedata['hash'] + uid).hexdigest()
-    backend['voter_add'](election, PID, xhash)
+    backend.voter_add(election, PID, xhash)
     return uid, xhash
     
 def remove(election, basedata, UID):
-    backend['voter_remove'](election, UID)
+    backend.voter_remove(election, UID)
     
 
 def hasVoted(election, issue, uid):
     issue = issue.strip(".json")
-    return backend['voter_has_voted'](election, issue, uid)
+    return backend.voter_has_voted(election, issue, uid)
 
 
 def email(rcpt, subject, message):