Commit 9bd2ff8c authored by Nagarjuna's avatar Nagarjuna

new branch with mongokit

parent cbd82261
......@@ -2,11 +2,11 @@ gstudio
=======
A Django application to recreate gnowsys-studio from scratch using
mongodb as storage. It uses django_mongodb_engine.
mongodb as storage. It uses django_mongokit.
This project will eventually metamorphose into an implementation of
http://www.gnu.org/software/gnowsys/ framework to create generic network
networks using Node Description Framework.
networks using Node Description Framework (NDF).
The project is released under GNU AGPL v3 license.
......
Django Implementation of GNOWSYS http://www.gnu.org/software/gnowsys/
Copyright (c) 2011, 2012 Free Software Foundation
Copyright (c) 2013 Free Software Foundation
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
......@@ -15,34 +15,3 @@ Copyright (c) 2011, 2012 Free Software Foundation
along with this program. If not, see <http://www.gnu.org/licenses/>.
This project incorporates work covered by the following copyright and permission notice:
Copyright (c) 2009, Julien Fache
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the
distribution.
* Neither the name of the author nor the names of other
contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
OF THE POSSIBILITY OF SUCH DAMAGE.
from django.db import models
# Create your models here.
"""
This file demonstrates two different styles of tests (one doctest and one
unittest). These will both pass when you run "manage.py test".
Replace these with more appropriate tests for your application.
"""
from django.test import TestCase
class SimpleTest(TestCase):
def test_basic_addition(self):
"""
Tests that 1 + 1 always equals 2.
"""
self.failUnlessEqual(1 + 1, 2)
__test__ = {"doctest": """
Another way to test that 1 + 1 is equal to 2.
>>> 1 + 1 == 2
True
"""}
"""
This file demonstrates two different styles of tests (one doctest and one
unittest). These will both pass when you run "manage.py test".
Replace these with more appropriate tests for your application.
"""
from django.test import TestCase
class SimpleTest(TestCase):
def test_basic_addition(self):
"""
Tests that 1 + 1 always equals 2.
"""
self.failUnlessEqual(1 + 1, 2)
__test__ = {"doctest": """
Another way to test that 1 + 1 is equal to 2.
>>> 1 + 1 == 2
True
"""}
from django.conf.urls.defaults import *
import views
urlpatterns = patterns('',
url(r'^$', views.run, name='run'),
)
This diff is collapsed.
This diff is collapsed.
import datetime
from django import forms
from django_mongokit.forms import DocumentForm
from models import Node
from models import Author
class NodeForm(DocumentForm):
tags = forms.CharField(max_length=250)
def clean_tags(self):
value = self.cleaned_data['tags']
return [tag.strip() for tag in value.split(',')]
class Meta:
document = Node
fields = ['name', 'node_type', 'tags']
class AuthorForm(DocumentForm):
''' '''
class Meta:
document = Author
fields = ['_id', 'name']
import datetime
from django_mongokit import connection
from django_mongokit.document import DjangoDocument
from bson import ObjectId
from django.contrib.auth.models import User
@connection.register
class Author(DjangoDocument):
collection_name = 'authors'
structure = {
'name': unicode,
'created_at': datetime.datetime
}
required_fields = ['name']
default_values = {'created_at':datetime.datetime.utcnow}
use_dot_notation = True
def __unicode__(self):
return self._id
def identity(self):
return self.__unicode__()
@connection.register
class Node(DjangoDocument):
collection_name = 'nodes'
structure = {
'name': unicode,
'altnames': unicode,
'plural': unicode,
'node_type': unicode, # Node_Type_Choices
'created_at': datetime.datetime,
'created_by': ObjectId, # Author Class
#'rating':
'start_publication': datetime.datetime,
'content': unicode,
'content_org': unicode,
#'image':
'tags': [unicode],
'featured': bool,
'last_update': datetime.datetime,
'modified_by': [ObjectId], # list of Author Class
'history': [ObjectId], # list of Any Type of Class (Previous)
'comment_enabled': bool,
'login_required': bool
#'password': basestring,
}
required_fields = ['name', 'node_type']
default_values = {'created_at':datetime.datetime.utcnow}
use_dot_notation = True
def __unicode__(self):
return self._id
def identity(self):
return self.__unicode__()
def save(self, *args, **kwargs):
''' on save insert created_at '''
self.created_at = datetime.datetime.today()
super(Node, self).save(*args, **kwargs)
@connection.register
class AttributeType(Node):
collection_name = 'attributeTypes'
structure = {
'dataType': basestring, # Field_Type_Choices
'verbose_name': basestring,
'null': bool,
'blank': bool,
'help_text': unicode,
'max_digits': int,
'decimal_places': int,
'auto_now': bool,
'auto_now_at': bool,
'upload_to': unicode,
'path': unicode,
'verify_exist': bool,
'min_length': int,
'required': bool,
'label': unicode,
'unique': bool,
#'validators': list
'default': unicode,
'editable': bool
}
#required_fields = ['dataType']
use_dot_notation = True
@connection.register
class Attribute(Node):
collection_name = 'attributes'
structure = {
'attribute_type': ObjectId, # AttributeType
'attribute_value': None # To store values of created attribute type
}
use_dot_notation = True
@connection.register
class RelationType(Node):
collection_name = 'relationTypes'
structure = {
'inverse_name': unicode,
'slug': basestring,
'is_symmetric': bool,
'is_reflexive': bool,
'is_transitive': bool
}
use_dot_notation = True
@connection.register
class Relation(Node):
collection_name = 'relations'
structure = {
'relation_type': ObjectId, # RelationType Class
'related_object': ObjectId # Node Class
}
use_dot_notation = True
@connection.register
class GSystemType(Node):
collection_name = 'gsystemTypes'
structure = {
'attribute_type_set': [ObjectId] # list of Attribute Class
}
use_dot_notation = True
@connection.register
class GSystem(Node):
collection_name = 'gsystems'
structure = {
'gsystem_type': ObjectId, # GSystemType Class
'attribute_set': [ObjectId], # list of Attribute Class
'relation_set': [ObjectId], # list of Relation Class
'collection_set': [ObjectId] # list of GSystem Class
}
use_dot_notation = True
<!DOCTYPE html>
<html>
<body>
<h1 align="center">Node Description Framework of <a href="http://www.gnu.org/software/gnowsys/">GNOWSYS</a></h1>
<hr>
<h3><a href="{% url 'wikipage' %}">Wikipage</a></h3>
</body>
</html>
<!DOCTYPE html>
<html>
<body>
<h1>Users</h1>
Node Description Framework of <a href="http://www.gnu.org/software/gnowsys/">GNOWSYS</a>
<hr>
<form action="." method="post">
{% csrf_token %}
{{ form.as_p }}
<input type="submit" value="+ Add User">
</form>
<hr>
{% load url from future %}
{% for user in authors %}
{% if forloop.first %}
<h2>{{ authors_count }} Authors</h2>
{% endif %}
<div>
<p><strong>{{ user.identity }}</strong>
&ndash; {{ user.creationtime|date:"j F Y" }}<br>
Name: {{ user.name }}<br>
</p>
</div>
{% empty %}
<p><em>No authors</em></p>
{% endfor %}
</body>
</html>
<!DOCTYPE html>
<html>
<body>
<h1>Wikipage</h1>
<hr>
Create a new wikipage
<form action="." method="post">
{% csrf_token %}
{{ form.as_p }}
<input type="submit" value="+ Add Node">
</form>
<hr>
{% load url from future %}
{% for node in nodes %}
{% if forloop.first %}
<h3>Number Of Nodes : {{ nodes_count }} </h3>
{% endif %}
<div>
<p><strong>{{ node.name }}</strong><br><br>
Created at : {{ node.created_at|date:"j F Y" }}<br>
Nodetype : {{ node.node_type }}<br>
Tags : {{ node.tags|join:", " }}<br>
<a href="{% url 'delete_node' node %}">delete</a>
</p>
</div>
{% empty %}
<p><em>No nodes in the gnowledge base</em></p>
{% endfor %}
</body>
</html>
<!DOCTYPE html>
<html>
<body>
{% load url from future %}
{% for node in nodes %}
<div>
<p><strong>{{ node.name }}</strong><br><br>
Created at : {{ node.created_at|date:"j F Y" }}<br>
Nodetype : {{ node.node_type }}<br>
Tags : {{ node.tags|join:", " }}<br>
<a href="{% url 'delete_node' node %}">delete</a>
</p>
</div>
{% endfor %}
</body>
</html>
<!--Write below code in wiki_node -->
<!--<div>
<p><a href="{% url 'wiki_node' %}">{{ node.name }}</a></p>
</div>-->
from django.template import Library, Node, Author
register = Library()
class DumbNode(Node):
def render(self, context):
return ''
@register.tag
def csrf_token(parser, token):
return DumbNode()
from django.core.urlresolvers import reverse
import datetime
from django.test import TestCase
from django.conf import settings
from django_mongokit import get_database
from models import Node
try:
from django.db import connections
__django_12__ = True
except ImportError:
__django_12__ = False
class ExampleTest(TestCase):
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
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)
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")
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)
#from django.conf.urls.defaults import patterns, url
from django.conf.urls import patterns, url
import views
urlpatterns = patterns('',
url(r'^$', views.homepage, name='homepage'),
url(r'^wikipage/', views.wikipage, name='wikipage'),
#url(r'^wiki_node/', views.wiki_node, name='wiki_node'),
url(r'^users/', views.userspage, name='userspage'),
url(r'^delete/(?P<_id>[\w-]+)$', views.delete_node, name='delete_node'),
)
try:
from bson import ObjectId
except ImportError: # old pymongo
from pymongo.objectid import ObjectId
from django.http import HttpResponseRedirect
from django.core.urlresolvers import reverse
from django.shortcuts import render_to_response
from django.template import RequestContext
from django_mongokit import get_database
from models import Node, Author
from forms import NodeForm, AuthorForm
def homepage(request):
return render_to_response(
"ndf/home.html",context_instance=RequestContext(request)
)
def wikipage(request):
collection = get_database()[Node.collection_name]
nodes = collection.Node.find()
nodes.sort('creationtime', -1)
nodes_count = nodes.count()
if request.method == "POST":
form = NodeForm(request.POST, collection=collection)
if form.is_valid():
form.save()
return HttpResponseRedirect(reverse('wikipage'))
else:
form = NodeForm(collection=collection)
return render_to_response(
"ndf/wiki.html", {
'nodes': nodes,
'form': form,
'nodes_count': nodes_count,
},
context_instance=RequestContext(request)
)
"""
def wiki_node(request):
collection = get_database()[Node.collection_name]
nodes = collection.Node.find()
return render_to_response(
"ndf/wiki_node.html", {
'nodes': nodes,
},
context_instance=RequestContext(request)
)
"""
def userspage(request):
collection = get_database()[Author.collection_name]
authors = collection.Author.find()
authors.sort('creationtime', -1)
authors_count = authors.count()
if request.method == "POST":
form = AuthorForm(request.POST, collection=collection)
if form.is_valid():
form.save()
return HttpResponseRedirect(reverse('userspage'))
else:
form = AuthorForm(collection=collection)
return render_to_response(
"ndf/users.html", {
'authors': authors,
'form': form,
'authors_count': authors_count
},
context_instance=RequestContext(request)
)
def delete_node(request, _id):
collection = get_database()[Node.collection_name]
node = collection.Node.one({"_id": ObjectId(_id)})
node.delete()
return HttpResponseRedirect(reverse("wikipage"))
# Django settings for gstudio_mdb project.
import os.path
# Django settings for gnowsys-ndf project.
DEBUG = True
TEMPLATE_DEBUG = DEBUG
DEBUG_PROPAGATE_EXCEPTIONS = DEBUG
ADMINS = (
# ('Your Name', 'your_email@example.com'),
......@@ -12,22 +11,25 @@ ADMINS = (
MANAGERS = ADMINS
DATABASES = {
'default': {
'ENGINE': 'django_mongodb_engine',
'NAME': 'my_tumble_log'
}
'default': {
'ENGINE': 'django.db.backends.sqlite3', # Add 'postgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle'.
'NAME': 'example-sqlite3.db',
},
'mongodb': {
'ENGINE': 'django_mongokit.mongodb',
'NAME': 'example',
'USER': '',
'PASSWORD': '',
'HOST': '',
'PORT': '',
},
}
# Hosts/domain names that are valid for this site; required if DEBUG is False
# See https://docs.djangoproject.com/en/1.4/ref/settings/#allowed-hosts
ALLOWED_HOSTS = []
# Local time zone for this installation. Choices can be found here:
# http://en.wikipedia.org/wiki/List_of_tz_zones_by_name
# although not all choices may be available on all operating systems.
# In a Windows environment this must be set to your system time zone.
USE_TZ = True
TIME_ZONE = 'Asia/Kolkata'
# Language code for this installation. All choices can be found here:
......@@ -82,7 +84,8 @@ STATICFILES_FINDERS = (
)
# Make this unique, and don't share it with anybody.
SECRET_KEY = '(t2(xg3z$a#@$_(y@c()d4yjtefm%r$6sejzu_%k9z!h4q1p&j'
SECRET_KEY = '7st0sdv&amp;7yw*eh)zmaz8#t48nr$&amp;ql#ow=$0l^#b_b&amp;$9c*$4c'
# List of callables that know how to import templates from various sources.
TEMPLATE_LOADERS = (
'django.template.loaders.filesystem.Loader',
......@@ -100,34 +103,26 @@ MIDDLEWARE_CLASSES = (
# 'django.middleware.clickjacking.XFrameOptionsMiddleware',
)
ROOT_URLCONF = 'gstudio_mdb.urls'
ROOT_URLCONF = 'gnowsys_ndf.urls'
# Python dotted path to the WSGI application used by Django's runserver.<