src/core/rdf_models.py
author ymh <ymh.work@gmail.com>
Sat, 15 Jun 2013 01:33:28 +0200
changeset 0 4095911a7830
child 28 5918a9d353d0
permissions -rw-r--r--
Jocondelab first commit before design

# -*- coding: utf-8 -*-
'''
Created on Jun 11, 2013

@author: ymh
'''

from rdflib import plugin, ConjunctiveGraph, URIRef, Literal
from rdflib.store import Store
from django.db import connections

class TermGraph(ConjunctiveGraph):
    
    def __init__(self, do_open=False, create=False):
        identifier = "jocondelab"        
        store = plugin.get("SQLAlchemy", Store)(identifier=identifier)
        ConjunctiveGraph.__init__(self, store=store, identifier=identifier)
        if do_open:
            self.open(create)

    def open(self, create=False):
        db_settings = connections['default'].settings_dict
        sa_db_settings = {
            'engine': 'postgresql+psycopg2' if db_settings['ENGINE'] == "django.db.backends.postgresql_psycopg2" else db_settings['ENGINE'],
            'user': db_settings['USER'],
            'password': db_settings['PASSWORD'],
            'port': db_settings['PORT'] if db_settings['PORT'] else "5432",
            'host': db_settings['HOST'] if db_settings['HOST'] else "localhost",
            'name': db_settings['NAME']             
        } 
        connect_config = "%(engine)s://%(user)s:%(password)s@%(host)s:%(port)s/%(name)s"%sa_db_settings 

        return ConjunctiveGraph.open(self, connect_config, create=create)

    def get_uri_for_term(self, term, context):
        c = URIRef(context)
        tl = Literal(term)
        
        for s,p,_ in self.triples((None, None, tl), context=c):
            if p in [URIRef("http://www.w3.org/2004/02/skos/core#prefLabel"), URIRef("http://www.w3.org/2004/02/skos/core#alternateLabel")]:
                return unicode(s)
        return None

graph = TermGraph(do_open=True, create=False)