Exemple #1
0
def insert(request):
	
	connection.register([MyRaw])
	collName = get_database().raw
	y = collName.MyRaw()
	
	print request.POST["f_name"],'\t',request.POST["f_tags"],'\t',request.POST["f_content"]
	y.name = request.POST["f_name"]
	tag_l = request.POST["f_tags"].split(",")
	y.tags = tag_l
	y.content = request.POST["f_content"]
	y.save()
	
	name_id = "name"
	tag_id = "tags"
	content_id = "content"
	
	obj = collName.MyRaw.find({name_id:request.POST["f_name"],content_id:request.POST["f_content"]})
	obj_l = list(obj)
	
	for i in obj_l:
		obj_id = str(i._id)
		
	print obj_id
	#After Saving this it is important that we also include it in "to_reduce" collction
	
	collName2 = get_database().to_reduce
	z = collName2.ToReduce()
	z._id = ObjectId(obj_id)
	z.save()
	return render(request,"raw_reduce/thankYou.html",{})
Exemple #2
0
    def tearDown(self):
        for name in get_database().collection_names():
            if name not in ('system.indexes', ):
                get_database().drop_collection(name)

        # because we have to manually control the creation and destruction of
        # databases in Django <1.2, I'll destroy the database here
        if not __django_12__:
            self.connection.creation.destroy_test_db(self.old_database_name)
Exemple #3
0
 def tearDown(self):
     for name in get_database().collection_names():
         if name not in ('system.indexes',):
             get_database().drop_collection(name)
             
     # because we have to manually control the creation and destruction of
     # databases in Django <1.2, I'll destroy the database here
     if not __django_12__:
         self.connection.creation.destroy_test_db(self.old_database_name)
Exemple #4
0
def _read_GSystem(GSystem_ids):
    collection = get_database()[GSystem.collection_name]
    gstype_coll = get_database()[GSystemType.collection_name]
    for id_ in GSystem_ids:
        gsystem = collection.GSystem.one({'_id': ObjectId(id_)})

    	gsystem.name
        gsystem.member_of

        gstype_coll.GSystemType.one({'_id':gsystem.gsystem_type})
        gsystem.attribute_set
        gsystem.relation_set
        gsystem.collection_set
Exemple #5
0
def _create_GSystem(data,how_many):
    collection = get_database()[GSystem.collection_name]  
    GSystem_ids = set()

    gsys_type_coll = get_database()[GSystemType.collection_name]
    gsys_type_cur  = gsys_type_coll.GSystemType.find()

    rel_type_coll = get_database()[RelationType.collection_name]
    at_type_coll = get_database()[AttributeType.collection_name]

    for i in range (how_many):
        #To create GSystemType of capital
        gsystem = collection.GSystem()
        
        gsystem.name = unicode(data[1][i],"utf-8")
        gsystem.member_of = u"GSystem"
        
        gsystem.gsystem_type = gsys_type_cur[0]._id
        
        at_type_name =  at_type_coll.AttributeType.one({"name":"capital"}).name
        gsystem.attribute_set = [{unicode(at_type_name):unicode(data[1][i],"utf-8")}]

        rel_type_name = rel_type_coll.RelationType.one({"name":"is_capital_of"}).name
        gsystem.relation_set =[{unicode(rel_type_name):unicode(data[0][i])}]
        
        gsystem.collection_set = []
        gsystem.save()

        GSystem_ids.add(gsystem.pk)

        #To create GSystemType of country        
        gsystem = collection.GSystem()
        
        gsystem.name = unicode(data[0][i],"utf-8")
        gsystem.member_of = u"GSystem"
        
        gsystem.gsystem_type = gsys_type_cur[0]._id

        at_type_name =  at_type_coll.AttributeType.one({"name":"country"}).name
        gsystem.attribute_set = [{unicode(at_type_name):unicode(data[0][i],"utf-8")}]

        rel_type_name = rel_type_coll.RelationType.one({"name":"has_capital"}).name
        gsystem.relation_set =[{rel_type_name:unicode(data[1][i])}]

        gsystem.collection_set = []
        gsystem.save()

        GSystem_ids.add(gsystem.pk)
    return GSystem_ids
Exemple #6
0
def data_cleanup():
    collection = get_database()[Author.collection_name]
    collection.remove()	

    collection = get_database()[AttributeType.collection_name]
    collection.remove()	

    collection = get_database()[GSystemType.collection_name]
    collection.remove()	

    collection = get_database()[GSystem.collection_name]
    collection.remove()	

    collection = get_database()[RelationType.collection_name]
    collection.remove()	
Exemple #7
0
def perform_map_reduce(request):
	#db = get_database()
	#gs_collection = db[GSystem.collection_name]

	#connection.register([ToReduce])	
	collName = get_database()["to_reduce"]
	instances = collName.ToReduce.find()
	y = list(instances)
	
	#connection.register([MyReduce])
	collName2 = get_database()["reduce"]
	
	
	#connection.register([MyRaw])
	collName3 = get_database()["raw"]
	
	
	for x in y:
		z = collName2.MyReduce()
		orignal_doc = collName3.MyRaw.find_one({"_id":x._id})
		z_old = collName2.MyReduce.find_one({"orignal":x._id})
		
		print "ORIGNAL DOC >>>>>>>>>>>>>>>>>>>>>>>>",orignal_doc		
		
		if z_old:
			print "OLD DOC >>>>>>>>>>>>>>>>>>>>> ",z_old
			#z_old.name = dict(map_reduce(orignal_doc.name,mapper,reducer))
			#z_old.tags = orignal_doc.tags
			#z_old.content = dict(map_reduce(orignal_doc.content,mapper,reducer))
			#z_old.save()
			#collName2.MyReduce.remove({"orignal":x._id})
			z_old.delete()
			
		
		z.name = dict(map_reduce(orignal_doc.name,mapper,reducer))
		#z.name = list(dict(map_reduce(orignal_doc.name,mapper,reducer)))
		z.tags = orignal_doc.tags
		z.content = dict(map_reduce(orignal_doc.content,mapper,reducer))
		#z.content = list(dict(map_reduce(orignal_doc.content,mapper,reducer)))
		z.orignal = x._id
		print "NAME>>>>>>>>>>>>>>>>>",z.name
		print "CONTENT>>>>>>>>>>>>>>",z.content
		z.save()
		print "OKOKOKOKK"
		x.delete()
	
	
	return render(request,"raw_reduce/thankYou.html",{"name":"pranav"})
Exemple #8
0
def _update_attribute_type(attribute_type_ids):
    collection = get_database()[AttributeType.collection_name]
    for id_ in attribute_type_ids:
        collection.update({'_id': ObjectId(id_)}, 
                          {'$set': {'name': u"edited_text",
                                    'data_type':'bool',
                                    'verbose_name':'mnbdvf',
                                    'null':'false',
                                    'blank':'false',
                                    'help_text': u'help ... ,jkjkuh',
                                    'max_digits': '15',
                                    'decimal_places': '2',
                                    'auto_now':'true',
                                    'auto_now_at':'false',
                                    'upload_to':u'url.....',
                                    'path':u'url.......',
                                    'verify_exist': 'true',
                                    'min_length': '10',
                                    'required': 'true',
                                    'label': u'label text',
                                    'unique': 'false',
                                    'validators':'[is_blank, valid, is_email]',
                                    'default': u'this is default',
                                    'editable': 'false'}
                           }, 
                          upsert=False, multi=True)
Exemple #9
0
def _read_attribute_type(attribute_type_ids):
    collection = get_database()[AttributeType.collection_name]
    for id_ in attribute_type_ids:
        attribute_type = collection.AttributeType.one({'_id': ObjectId(id_)})

    	attribute_type.name
        attribute_type.member_of
		
        attribute_type.data_type
        attribute_type.verbose_name
        attribute_type.null
        attribute_type.blank
        attribute_type.help_text
        attribute_type.max_digits
        attribute_type.decimal_places
        attribute_type.auto_now
        attribute_type.auto_now_at
        attribute_type.upload_to
        attribute_type.path
        attribute_type.verify_exist
        attribute_type.min_length
        attribute_type.required
        attribute_type.label
        attribute_type.unique
        attribute_type.validators
        attribute_type.default
        attribute_type.editable
Exemple #10
0
def _create_attribute_type():
    collection = get_database()[AttributeType.collection_name]
    attribute_type_ids = set()
    attr_type_names = [u"country", u"capital"]
	
    for i in attr_type_names:
        attribute_type = collection.AttributeType()
        attribute_type.name = i
        attribute_type.member_of = u"attribute_type"
		
        attribute_type.data_type = "unicode"
        attribute_type.verbose_name = "Place"
        attribute_type.null = True
        attribute_type.blank = True
        attribute_type.help_text = u"helptext"
        attribute_type.max_digits = 10
        attribute_type.decimal_places = 2
        attribute_type.auto_now = True
        attribute_type.auto_now_at = True
        attribute_type.upload_to = u"url"
        attribute_type.path = u"url/name"
        attribute_type.verify_exist = True
        attribute_type.min_length = 5
        attribute_type.required = True
        attribute_type.label = u"Label"
        attribute_type.unique = True
        attribute_type.validators = []
        attribute_type.default = u"default"
        attribute_type.editable = True
		
        attribute_type.save()
        attribute_type_ids.add(attribute_type.pk)
      
    return attribute_type_ids
    def render_to_response(self, request):
        results = []
        end = timezone.now()
        start = end - timezone.timedelta(seconds=3600)

        cursor = get_database().Diagnostic.find({
            'timestamp': {
                '$gte': start,
                '$lt': end
            },
        }).sort('timestamp')

        first = True
        for doc in cursor:
            if first:
                keys = ['Timestamp']
                for st in doc['status']:
                    for kv in st['values']:
                        keys.append(kv['key'])
                if len(keys) >= 0:
                    continue
                results.append('"%s"\n' % '","'.join(keys))
                first = False

            values = [timezone.make_naive(doc['timestamp'])]
            for st in doc['status']:
                for kv in st['values']:
                    values.append(kv['value'])
            results.append('"%s"\n' % '","'.join(['%s' % v for v in values]))

        return StreamingHttpResponse(results, content_type='text/csv')
    def handle(self, *args, **options):

        history_manager = HistoryManager()
        rcs_obj = RCS()

        collection = get_database()[Triple.collection_name]
        cur = collection.Triple.find({"_type": "GAttribute"})

        for n in cur:
            if type(n["attribute_type"]) == ObjectId:
                attr_type = collection.Node.one({"_id": n["attribute_type"]})
                if attr_type:
                    collection.update(
                        {"_id": n["_id"]},
                        {
                            "$set": {
                                "attribute_type": {
                                    "$ref": attr_type.collection_name,
                                    "$id": attr_type._id,
                                    "$db": attr_type.db.name,
                                }
                            }
                        },
                    )
                else:
                    collection.remove({"_id": n["_id"]})

            subject_doc = collection.Node.one({"_id": n.subject})
            n.name = subject_doc.name + " -- " + n.attribute_type["name"] + " -- " + n.object_value

            # Creates a history (version-file) for GAttribute documents
            if history_manager.create_or_replace_json_file(n):
                fp = history_manager.get_file_path(n)
                message = "This document (" + n.name + ") is created on " + subject_doc.created_at.strftime("%d %B %Y")
                rcs_obj.checkin(fp, 1, message.encode("utf-8"), "-i")
Exemple #13
0
def load(request):
    if not request.user.is_authenticated():
        return HttpResponseRedirect("/accounts/login")
    if request.method == 'POST':
        form = ImportDeliciousForm(request.POST,request.FILES)
        if form.is_valid():
            db = get_database()[Bookmark.collection_name]
            html=request.FILES['exported'].read().decode('utf8')
            soup=BeautifulSoup(html)
            for item in soup.findAll('dt'):
                desc=''
                next=item.findNextSiblings()
                if next:
                    next=next[0]
                    if 'name' in dir(next) and next.name=='dd':
                        desc=unescape(u''.join(imap(unicode, next.contents)))
                db.Bookmark({'url': urlSanitize(item.a['href']),
                             'seq': getNextVal('seq'),
                             'tags': item.a['tags'].split(','),
                             'user': unicode(request.user),
                             'created': datetime.fromtimestamp(float(item.a['add_date'])),
                             'private': item.a['private']=='1',
                             'title': unescape(unicode(item.a.string)),
                             'notes': unicode(desc)}).save()
            return HttpResponseRedirect('/u/%s/' % request.user)
    else:
        form = ImportDeliciousForm()
    return render_to_response('import.html', { 'form': form, }, context_instance=RequestContext(request) )
Exemple #14
0
    def test_homepage(self):
        """homepage shows a list of nodes and allows to add or delete
        existing nodes """
        response = self.client.get(reverse('homepage'))
        self.assertTrue(response.status_code, 200)
        self.assertTrue('No nodes in the gnowledge base' in response.content)

        data = {'name': '',
                'creationtime': '2010-12-31',
                'tags': ' semantic web , network '}
        response = self.client.post(reverse('homepage'), data)
        self.assertEqual(response.status_code, 200)
        self.assertTrue('class="errorlist"' in response.content)
        self.assertTrue('This field is required' in response.content)

        data['name'] = 'gnowsys'
        response = self.client.post(reverse('homepage'), data)
        self.assertEqual(response.status_code, 302)

        response = self.client.get(reverse('homepage'))
        self.assertTrue(response.status_code, 200)
        self.assertTrue('gnowsys' in response.content)
        self.assertTrue('31 December 2010' in response.content)
        self.assertTrue('Tags: semantic web, network' in response.content)

        collection = get_database()[Node.collection_name]
        node = collection.Node.one()
        assert node.topic == u"gnowsys"
        delete_url = reverse('delete_node', args=[str(node._id)])
        response = self.client.get(delete_url)
        self.assertEqual(response.status_code, 302)

        response = self.client.get(reverse('homepage'))
        self.assertTrue(response.status_code, 200)
        self.assertTrue('gnowsys' not in response.content)
Exemple #15
0
    def handle(self, *args, **options):
        db=get_database()
        collection = db[Node.collection_name]
        """
        cur=collection.Node.find({'group_set':{'$exists':True}})
        for each in cur:
            gps = collection.Node.find({'_type':u'Group'})
            for eachgps in gps:
                grpname = unicode(eachgps.name)
                if grpname.strip() in each.group_set:
                    each.group_set.remove(grpname)
                    each.group_set.append(eachgps._id)
            for each_group_set_item in each.group_set:
                if type(each_group_set_item)==unicode:
                    each.group_set.remove(each_group_set_item)
            each.save()
        """

        cur=collection.Node.find({'group_set':{'$exists':True}})
        for n in cur:
            gs = n.group_set
            n.group_set = []
            for group in gs:
                if type(group) == unicode:
                    group_obj=collection.Node.one({'name': group})
                    if group_obj:
                        n.group_set.append(group_obj._id)
                else:
                    n.group_set.append(group)
            n.save()
Exemple #16
0
    def setUp(self):
        if not __django_12__:
            # Ugly but necessary
            from django.db import load_backend
            backend = load_backend('django_mongokit.mongodb')

            def get(key):
                return getattr(settings, key, None)

            self.connection = backend.DatabaseWrapper({
                'DATABASE_HOST':
                get('MONGO_DATABASE_HOST'),
                'DATABASE_NAME':
                settings.MONGO_DATABASE_NAME,
                'DATABASE_OPTIONS':
                get('MONGO_DATABASE_OPTIONS'),
                'DATABASE_PASSWORD':
                get('MONGO_DATABASE_PASSWORD'),
                'DATABASE_PORT':
                get('MONGO_DATABASE_PORT'),
                'DATABASE_USER':
                get('MONGO_DATABASE_USER'),
                'TIME_ZONE':
                settings.TIME_ZONE,
            })
            self.old_database_name = settings.MONGO_DATABASE_NAME
            self.connection.creation.create_test_db()

        db = get_database()
        assert 'test_' in db.name, db.name
Exemple #17
0
def create_page(request):
    if not request.is_ajax():
        return HttpResponse(status=400, content="Only ajax requests are accepted here")


    db = get_database()
    try:
        post_data = json.loads(request.body)
    except ValueError:
        resp = {'status': 'error', 'message': "Unable to parse json"}
        return HttpResponse(json.dumps(resp), content_type='application/json', status=400)

    if "items" not in post_data:
        resp = {"status": "error", "message": "need param 'items'"}
        return HttpResponse(json.dumps(resp), content_type='application/json', status=400)
    elif "tags" not in post_data:
        resp = {"status": "error", "message": "need param 'tags'"}
        return HttpResponse(json.dumps(resp), content_type='application/json', status=400)
    elif "name" not in post_data:
        resp = {"status": "error", "message": "need param 'name'"}
        return HttpResponse(json.dumps(resp), content_type='application/json', status=400)


    post_data["slug"] = slugify(post_data["name"])
    post_data["user"] = request.user.id
    db.pages.save(post_data)

    resp = {
        'status': 'ok',
        'message': 'Saved... Thanks!',
        'slug': post_data["slug"]
    }
    return HttpResponse(json.dumps(resp), content_type='application/json')
Exemple #18
0
def mongo_fetch(request):
    collections = get_database()[DataMe.collection_name]
    data_docs = collections.DataMe.find_one()
    resp = {}
    resp['name'] = data_docs['name']
    resp['surname'] = data_docs['surname']
    return json.dumps(str(resp), ensure_ascii=False)
Exemple #19
0
def home(request):
    db = get_database()
    pages = db.pages.find()
    return TemplateResponse(request, 'home.html', {'pages': pages})


    return TemplateResponse(request, 'home.html')
Exemple #20
0
    def get_redirect_url(self, *args, **kwargs):

    	if self.request.user.is_authenticated():
            collection = get_database()[Node.collection_name]
            auth_obj = collection.GSystemType.one({'_type': u'GSystemType', 'name': u'Author'})
            if auth_obj:
                auth_type = auth_obj._id
            auth = ""
            auth = collection.Group.one({'_type': u"Author", 'name': unicode(self.request.user)})            
            # This will create user document in Author collection to behave user as a group.
            
            if auth is None:
                auth = collection.Author()
                
                auth.name = unicode(self.request.user)      
                auth.password = u""
                auth.member_of.append(auth_type)
                auth.group_type = u"PUBLIC"
                auth.edit_policy = u"NON_EDITABLE"
                auth.subscription_policy = u"OPEN"
                user_id = int(self.request.user.pk)
                auth.created_by = user_id
                auth.modified_by = user_id
                if user_id not in auth.contributors:
                    auth.contributors.append(user_id)
                auth.save()
                
            # This will return a string in url as username and allows us to redirect into user group as soon as user logsin.
            #return "/{0}/".format(auth.pk)
        return "/home/"     
    def handle(self, *args, **options):

        history_manager = HistoryManager()
        rcs_obj = RCS()

        collection = get_database()[Triple.collection_name]
        cur = collection.Triple.find({'_type': 'GAttribute'})

        for n in cur:
            if type(n['attribute_type']) == ObjectId:
                attr_type = collection.Node.one({'_id': n['attribute_type']})
                if attr_type:
                    collection.update({'_id': n['_id']}, {
                        '$set': {
                            'attribute_type': {
                                "$ref": attr_type.collection_name,
                                "$id": attr_type._id,
                                "$db": attr_type.db.name
                            }
                        }
                    })
                else:
                    collection.remove({'_id': n['_id']})

            subject_doc = collection.Node.one({'_id': n.subject})
            n.name = subject_doc.name + " -- " + n.attribute_type[
                'name'] + " -- " + n.object_value

            # Creates a history (version-file) for GAttribute documents
            if history_manager.create_or_replace_json_file(n):
                fp = history_manager.get_file_path(n)
                message = "This document (" + n.name + ") is created on " + subject_doc.created_at.strftime(
                    "%d %B %Y")
                rcs_obj.checkin(fp, 1, message.encode('utf-8'), "-i")
Exemple #22
0
def mongo_fetch(request):
	collections = get_database()[DataMe.collection_name]
	data_docs = collections.DataMe.find_one()
	resp = {}
	resp['name'] = data_docs['name']
	resp['surname'] = data_docs['surname']
	return json.dumps(str(resp),ensure_ascii=False)
Exemple #23
0
def export(request):
    if not request.user.is_authenticated():
        return HttpResponseRedirect("/accounts/login")
    db = get_database()[Bookmark.collection_name]
    return render_to_response('export.html',
                              {'bookmarks': db.find({'user': request.user.username.encode('utf8')})},
                              context_instance=RequestContext(request) )
Exemple #24
0
def mongo_remove(request, name, surname, ustr):
    collections = get_database()[DataMe.collection_name]
    return str(
        collections.remove({
            'name': name,
            'surname': surname,
            'ustr': ustr
        }))
Exemple #25
0
def export(request):
    if not request.user.is_authenticated():
        return HttpResponseRedirect("/accounts/login")
    db = get_database()[Bookmark.collection_name]
    return render_to_response(
        'export.html',
        {'bookmarks': db.find({'user': request.user.username.encode('utf8')})},
        context_instance=RequestContext(request))
Exemple #26
0
def view(request, slug):
    db = get_database()
    page = db.pages.find_one({"slug": slug})
    if page is None:
        raise Http404


    return TemplateResponse(request, 'page.html', {'page': page})
Exemple #27
0
def _read_GSystemType(GSystemType_ids):
    collection = get_database()[GSystemType.collection_name]
    for id_ in GSystemType_ids:
        gsystem_type = collection.GSystemType.one({'_id': ObjectId(id_)})

    	gsystem_type.name
        gsystem_type.member_of
        gsystem_type.attribute_type_set
Exemple #28
0
def mongo_add(request, name='Smit', surname='Patwa', ustr='Pingu'):
	collections = get_database()[DataMe.collection_name]
	obj = collections.DataMe()
	obj['name'] = name
	obj['surname'] = surname
	obj['ur_str'] = ustr
	obj.save()
	return 'Saved'
Exemple #29
0
def mongo_add(request, name='Smit', surname='Patwa', ustr='Pingu'):
    collections = get_database()[DataMe.collection_name]
    obj = collections.DataMe()
    obj['name'] = name
    obj['surname'] = surname
    obj['ur_str'] = ustr
    obj.save()
    return 'Saved'
    def handle(self, *args, **options):
        
        collection = get_database()[Node.collection_name]

        # Renames field: 'modified_by' to 'contributors'
        collection.update({'modified_by': {'$exists': True}}, {'$rename': {'modified_by': "contributors"}}, upsert=False, multi=True)

        # Updates location fields' values from '{}' (empty dictionary) to '[]' (empty list)
        collection.update({'location': {}}, {'$set': {'location': []}}, upsert=False, multi=True)
Exemple #31
0
    def handle(self, *args, **options):
        db = get_database()
        collection = db[Node.collection_name]

        # [A] Get the " GSystemType/AttributeType/RelationType " nodes (for whom 'gsystem_type' field doesn't exist)
        cur_ty_mo = collection.Node.find({'_type': {'$in': ['GSystemType', 'AttributeType', 'RelationType']}})

        # Listing the nodes
        for n in cur_ty_mo:
            # Replace 'member_of' field with ObjectId of MetaType to which that document belongs
            # - But right now we don't have such MetaType documents
            # - Currently going to keep 'member_of' field... EMPTY!

            n.member_of = []
            n.save()

        # ===================================================================================================================================


        # [B] Get the " GSystem/File/Group " nodes for whom 'member_of' and 'gsystem_type' fields exist
        cur_nc_mo = collection.Node.find({'member_of': {'$exists': True}, 'gsystem_type': {'$exists': True}})

        # Listing the nodes
        for n in cur_nc_mo:

            # Replace 'member_of' field with ObjectId of GSystemType to which that document belongs

            if not n.gsystem_type:
                # If 'gsystem_type' field is EMPTY
                #   - Special case: Exists with 'Group' documents, they consists of value only for 'member_of' field (not for 'gsystem_type' field)
                #   - In this case, 'member_of' field is a list that consists of name of the GSystemType (i.e. 'Group')
                #   - So extract this value first from 'member_of' field, then assign/override 'member_of' field with an empty list.
                #   - For extracted value (i.e. name of the GSystemType), fetch it's documents ObjectId from database; and append this ObjectId to the 'member_of' field

                gsystem_name_list = n.member_of
                n.member_of = []

                # Iterate name list
                for name in gsystem_name_list:
                    gsystem_node = collection.Node.one({'_type': 'GSystemType', 'name': name})
                    n.member_of.append(gsystem_node._id)

            else:
                # Else 'gsystem_type' field is NOT empty
                #   - This field contains list of ObjectIds' of GSystemType to which the document belongs
                #   - Assign/Override 'member_of' field with an empty list
                #   - Append these ObjectIds to the 'member_of' field

                gsystem_oid_list = n.gsystem_type
                n.member_of = []

                n.member_of = gsystem_oid_list

            n.save()

        # Remove 'gsystem_type' field from already existing documents where ever it exists!
        collection.update({'gsystem_type': {'$exists': True}}, {'$unset': {'gsystem_type': ""}}, multi=True)
Exemple #32
0
def _update_GSystem(GSystem_ids):
    collection = get_database()[GSystem.collection_name]
    for id_ in GSystem_ids:
        collection.update({'_id': ObjectId(id_)}, 
                          {'$set': {'name': u'edited_text',
                                    'gsystem_type': u'52495d205a40920ab18ed028',
                                    'relation_set': "{u'has_capital': u'Alberta'}",
                                    'attribute_set': ''}
                           }, 
                          upsert=False, multi=True)
Exemple #33
0
def _create_GSystemType():
    collection = get_database()[GSystemType.collection_name]

    GSystemType_ids = set()    

    at_coll = get_database()[AttributeType.collection_name]	
    at_cur = at_coll.AttributeType.find()

    gsystem_type = collection.GSystemType()
    gsystem_type.name = u"places"
    gsystem_type.member_of = u"GSystemType"

    for i in at_cur:
        gsystem_type.attribute_type_set.append(i)

    gsystem_type.save()
    GSystemType_ids.add(gsystem_type.pk)

    return GSystemType_ids
Exemple #34
0
def edit_page_view(request, slug):
    db = get_database()
    page = db.pages.find_one({"slug": slug})
    if page is None:
        raise Http404

    page["json"] = dumps(page)


    return TemplateResponse(request, 'edit_page.html', {'page': page})
Exemple #35
0
def edit_page(request):
    if not request.is_ajax():
        return HttpResponse(status=400, content="Only ajax requests are accepted here")


    db = get_database()
    try:
        post_data = json.loads(request.body)
    except ValueError:
        resp = {'status': 'error', 'message': "Unable to parse json"}
        return HttpResponse(json.dumps(resp), content_type='application/json', status=400)


    if "id" not in post_data:
        resp = {"status": "error", "message": "need param id"}
        return HttpResponse(json.dumps(resp), content_type='application/json', status=400)

    page = db.pages.find_one({"_id": ObjectId(post_data["id"])})

    if page is None:
        resp = {"status": "error", "message": "howto not found"}
        return HttpResponse(json.dumps(resp), content_type='application/json', status=404)

    if "items" not in post_data:
        resp = {"status": "error", "message": "need param 'items'"}
        return HttpResponse(json.dumps(resp), content_type='application/json', status=400)
    elif "tags" not in post_data:
        resp = {"status": "error", "message": "need param 'tags'"}
        return HttpResponse(json.dumps(resp), content_type='application/json', status=400)
    elif "change_reason" not in post_data:
        resp = {"status": "error", "message": "need param 'change_reason'"}
        return HttpResponse(json.dumps(resp), content_type='application/json', status=400)


    page_revision = page
    page_revision["change_reason"] = post_data["change_reason"]
    page_revision["page_id"] = page_revision["_id"]
    del page_revision["_id"]
    db.pages.revisions.save(page)

    del page["change_reason"]
    page["items"] = post_data["items"]
    page["tags"] = post_data["tags"]
    page["name"] = post_data["name"]
    page["user"] = request.user.id
    page["_id"] = ObjectId(post_data["id"])

    db.pages.save(page)
    resp = {
        'status': 'ok',
        'message': 'Saved... Thanks!',
        'slug': page["slug"],
        "data": page
    }
    return HttpResponse(dumps(resp), content_type='application/json')
Exemple #36
0
def _create_relation_type():
    collection = get_database()[RelationType.collection_name]
    gstype_coll = get_database()[GSystemType.collection_name]
    relation_type_ids = set()
    
    relation_type = collection.RelationType()
    relation_type.name = u"has_capital"
    relation_type.member_of = u"relation_type"
    
    relation_type.inverse_name = u"is_capital_of"
    relation_type.slug = "has_capital"
    
    relation_type.subject_type = [gstype_coll.GSystemType.one({"name":"places"})._id]
    relation_type.object_type = [gstype_coll.GSystemType.one({"name":"places"})._id]
    
    relation_type.is_symmetric = True
    relation_type.is_reflexive = True
    relation_type.is_transitive = True				
    
    relation_type.save()
    relation_type_ids.add(relation_type.pk)      
    
    #Automatic creation of reverse RelationType from above RelationType object
    relation_type = collection.RelationType()

    relation_type.name = u"is_capital_of"
    relation_type.member_of = u"relation_type"
    
    relation_type.inverse_name = u"has_capital"
    relation_type.slug = "is_capital_of"

    relation_type.subject_type = [gstype_coll.GSystemType.one({"name":"places"})._id]
    relation_type.object_type = [gstype_coll.GSystemType.one({"name":"places"})._id]

    relation_type.is_symmetric = True
    relation_type.is_reflexive = True
    relation_type.is_transitive = True				

    relation_type.save()
    relation_type_ids.add(relation_type.pk)      

    return relation_type_ids
Exemple #37
0
def getItemByUrl(url):
    db = get_database()[Bookmark.collection_name]
    if slugRe.match(url):
        item = db.find_one({'seq': base62.to_decimal(url)})
    else:
        url = fixApacheMadness(url)
        url = urlSanitize(url)
        item = db.find_one({'url': url})
    if not item:
        raise Http404
    return item
Exemple #38
0
def getItemByUrl(url):
    db = get_database()[Bookmark.collection_name]
    if slugRe.match(url):
        item=db.find_one({'seq':base62.to_decimal(url)})
    else:
        url=fixApacheMadness(url)
        url=urlSanitize(url)
        item=db.find_one({'url':url})
    if not item:
        raise Http404
    return item
Exemple #39
0
    def test_creating_basic_node(self):
        """test to create a basic node """
        collection = get_database()[Node.collection_name]
        node = collection.Node()
        node.name = u"gnowsys"
        node.creationtime = datetime.datetime.now()
        node.tags = [u"semantic web", u"network"]
        node.validate()
        node.save()

        self.assertTrue(node['_id'])
        self.assertEqual(node.name, u"gnowsys")
Exemple #40
0
def _update_relation_type(relation_type_ids):
    collection = get_database()[RelationType.collection_name]
    for id_ in relation_type_ids:
        collection.update({'_id': ObjectId(id_)},
                          {'$set': {'name': u'edited_text',
                                    'inverse_name': u'xkmjdkgkl',
                                    'slug':'slug-string',
                                    'is_symmetric':'false',
                                    'is_reflexive':'false',
                                    'is_transitive':'false'}
                           }, 
                          upsert=False, multi=True)
Exemple #41
0
    def handle(self, *args, **options):
        db = get_database()
        collection = db[Node.collection_name]

        cur = collection.Node.find({'type_of': {'$exists': True}})
        for n in cur:
            gst = n.type_of
            if gst == 'profile_pic':
                type_obj = collection.Node.one({'name': gst})
                if type_obj:
                    n.type_of = ObjectId(type_obj._id)

                    n.save()
Exemple #42
0
def _create_talks(how_many):
    # 1 Create 1,000 talks
    collection = get_database()[Talk.collection_name]
    ids = set()
    for i in range(how_many):
        talk = collection.Talk()
        talk.topic = __random_topic()
        talk.when = __random_when()
        talk.tags = __random_tags()
        talk.duration = __random_duration()
        talk.save()
        ids.add(talk.pk)
    return ids
Exemple #43
0
    def test_creating_talk_basic(self):
        """test to create a Talk instance"""
        collection = get_database()[Talk.collection_name]
        talk = collection.Talk()
        talk.topic = u"Bla"
        talk.when = datetime.datetime.now()
        talk.tags = [u"foo", u"bar"]
        talk.duration = 5.5
        talk.validate()
        talk.save()

        self.assertTrue(talk['_id'])
        self.assertEqual(talk.duration, 5.5)
Exemple #44
0
def _read_relation_type(relation_type_ids):
    collection = get_database()[RelationType.collection_name]
    for id_ in relation_type_ids:
        relation_type = collection.RelationType.one({'_id': ObjectId(id_)})

    	relation_type.name
        relation_type.member_of

        relation_type.inverse_name
        relation_type.slug
        relation_type.subject_type
        relation_type.object_type
        relation_type.is_symmetric
        relation_type.is_reflexive
        relation_type.is_transitive
Exemple #45
0
def _read_author_nodes(author_ids):
    collection = get_database()[Author.collection_name]
    for id_ in author_ids:
        author = collection.Author.one({'_id': ObjectId(id_)})

    	author.username
    	author.password
    	author.email
    	author.first_name
    	author.last_name
        author.address
    	author.phone
    	author.is_active
    	author.is_staff
    	author.is_superuser
    	author.created_at
    	author.last_login
Exemple #46
0
def _update_author_nodes(author_ids):
    collection = get_database()[Author.collection_name]
    for id_ in author_ids:
        collection.update({'_id': ObjectId(id_)}, 
                          {'$set': {'username': u'edited_text', 
                                    'password': u'edit12%',
                                    'email': u'*****@*****.**',
                                    'first_name':'uyhskk',
                                    'last_name':'ksdbmplp',
                                    'phone':'4568965874L',
                                    'is_active':'true',
                                    'is_staff':'false',
                                    'is_superuser':'******',
                                    'created_at':'datetime.datetime(2013, 9, 20, 14, 13, 44, 304360)',
                                    'last_login':'******'}
                          }, 
                          upsert=False, multi=True)
Exemple #47
0
def delete(request, url):
    if not request.user.is_authenticated():
        return HttpResponseRedirect("/accounts/login")
    url = fixApacheMadness(url)
    try:
        user = User.objects.get(username=request.user)
        db = get_database()[Bookmark.collection_name]
        for obj in db.find({'url': url, 'user': unicode(request.user)}):
            for hash in obj.get('snapshot', []):
                if not hash.strip(): continue
                fname = "%s/snapshots/%s" % (settings.BASE_PATH, hash)
                if os.path.exists(fname):
                    os.unlink(fname)
            db.remove(obj)
    except ObjectDoesNotExist:
        print "meh delete not working. user, url or obj not existing"
    return HttpResponseRedirect('/u/%s/' % request.user)