Kevin Veroneau avatar Kevin Veroneau committed 65d5909 Draft

Initial code import.

Comments (0)

Files changed (13)

Empty file added.

+from django import forms
+
+class MyForm(forms.Form):
+    name = forms.CharField()
+    age = forms.IntegerField()
+
+class ManageForm(forms.Form):
+    content = forms.CharField(widget=forms.Textarea)

odb/middleware.py

+from django.http import HttpResponse
+from django.forms.forms import Form
+from django.views.generic.edit import FormView
+from odb.traverse import get_object
+from inspect import isclass
+from django.template.base import Template
+from django.template.context import RequestContext
+from django.shortcuts import render
+
+class TraversalMiddleware(object):
+    def process_request(self, req):
+        try:
+            o = get_object(req.path)
+            if hasattr(o, '__getitem__') and 'index' in o:
+                o = o['index']
+            if hasattr(o, 'render') and callable(o.render):
+                return o.render(req)
+            elif isinstance(o, HttpResponse):
+                return o
+            elif isinstance(o, str):
+                return HttpResponse(o)
+            elif isclass(o) and issubclass(o, Form):
+                return FormView.as_view(form_class=o, template_name="odb/form.html")(req)
+            elif isinstance(o, Template):
+                return HttpResponse(o.render(RequestContext(req,{'GET':req.GET})))
+            elif hasattr(o, 'keys') and callable(o.keys):
+                if req.path[-1]!='/':
+                    return None
+                object_list = []
+                for k, v in o.iteritems():
+                    obj = {'name':k, 'class':v.__class__.__name__}
+                    if isinstance(v, dict): obj.update({'is_directory':True})
+                    object_list.append(obj)
+                return render(req, "odb/object_list.html", {'object_list':object_list,'path':req.path})
+            return None
+        except KeyError:
+            return None
+from django.http import HttpResponse
+from odb.forms import MyForm, ManageForm
+from django.template.base import Template
+import shelve
+from django.forms.forms import DeclarativeFieldsMetaclass, Form
+from django import forms
+from django.shortcuts import render
+
+class ManageContent(object):
+    form_class = ManageForm
+    def render(self, req):
+        return self.form_class
+
+class ContentObject(object):
+    content = "Empty Object"
+    manager = ManageContent
+    def __init__(self, content="Empty Object"):
+        self.content = content
+    def render(self, req):
+        return HttpResponse(self.content)
+    def manage(self, req):
+        return self.manager().render(req)
+
+class ObjectGroup(dict):
+    object_class = ContentObject
+
+class Field(object):
+    _content = None
+    _counter = 0
+    def __init__(self, content=None):
+        if content:
+            self.content = content
+        self._counter = Field._counter
+        Field._counter += 1
+    def get_field_class(self):
+        return forms.Field()
+    def validate(self, value):
+        return value
+    def _set_content(self, value):
+        self._content = self.validate(value)
+    def _get_content(self):
+        return self._content
+    def _del_content(self):
+        self._content = None
+    content = property(_get_content, _set_content, _del_content, "Field Contents.")
+
+class CharField(Field):
+    _content = ""
+    def get_field_class(self):
+        return forms.CharField()
+    def validate(self, value):
+        if isinstance(value, str) or isinstance(value, unicode):
+            return value
+        raise ValueError
+
+class TextField(Field):
+    _content = ""
+    def get_field_class(self):
+        return forms.CharField(widget=forms.Textarea)
+    def validate(self, value):
+        if isinstance(value, str) or isinstance(value, unicode):
+            return value
+        raise ValueError
+
+class IntegerField(Field):
+    _content = 0
+    def get_field_class(self):
+        return forms.IntegerField()
+    def validate(self, value):
+        if not isinstance(value, int):
+            raise ValueError
+        return value
+
+class BooleanField(Field):
+    _content = False
+    def get_field_class(self):
+        return forms.BooleanField()
+    def validate(self, value):
+        if not isinstance(value, bool):
+            raise ValueError
+        return value
+
+class Model(object):
+    template_name = "odb/model.html"
+    def __init__(self, *args, **kwargs):
+        self.scan_fields()
+        for k,v in kwargs.iteritems():
+            getattr(self, k).content = v
+    def scan_fields(self):
+        # Used to upgrade older models to include new field attributes.
+        self.fields = [f for f in dir(self) if isinstance(getattr(self,f),Field)]
+    def __getstate__(self):
+        state = {'fields':self.fields}
+        for f in self.fields:
+            state.update({f:getattr(self,f).content})
+        return state
+    def __setstate__(self, state):
+        self.fields = state['fields']
+        for f in self.fields:
+            getattr(self, f).content = state[f]
+    def get_form_class(self):
+        fields = {}
+        for f in self.fields:
+            fields.update({f:getattr(self,f).get_field_class()})
+        return DeclarativeFieldsMetaclass(self.__class__.__name__+"Form", (Form,),fields)
+    def get_initial(self):
+        initial = {}
+        for f in self.fields:
+            initial.update({f:getattr(self,f).content})
+        return initial
+    def get_form(self):
+        return self.get_form_class()(initial=self.get_initial())
+    def process_form(self, form):
+        if form.is_valid():
+            for k,v in form.cleaned_data.iteritems():
+                getattr(self, k).content = v
+            return True
+        return False
+    def get_context_data(self, **kwargs):
+        context = kwargs
+        obj = []
+        for k, v in self.get_initial().iteritems():
+            obj.append({'name':k,'value':v})
+        context.update({'object':obj, 'class':self.__class__.__name__})
+        return context
+    def render(self, req):
+        return render(req, self.template_name, self.get_context_data(path=req.path))
+
+class Person(Model):
+    name = CharField()
+    age = IntegerField()
+    bio = TextField()
+    is_staff = BooleanField()
+
+odb_dict = shelve.open("mydata", writeback=True)
+
+odb_dict3 = {'hello_odb': ContentObject("Hello ContentObject!"),
+            'docs': ObjectGroup()}
+
+odb_dict2 = {'hello_odb': HttpResponse("Hello Object Database!"),
+            'test123': {'file.txt': HttpResponse("Hello World!"), 'me':"My name is Kevin!"},
+            'myform': MyForm,
+            'templates': {'index': "Not allowed.", 'odb': {'form.html': Template("<table>{{form}}</table>")}},
+            'index': Template("{{GET.name}}")}
+from django.template.loader import BaseLoader
+from odb.traverse import get_object
+from django.template.base import TemplateDoesNotExist
+
+class TraverseLoader(BaseLoader):
+    is_usable = True
+    
+    def load_template(self, template_name, template_dirs=None):
+        template = get_object("/templates/%s" % template_name)
+        if template == None:
+            raise TemplateDoesNotExist
+        return template, None

odb/templates/odb/base.html

+<html>
+ <head>
+  <title>{% block title %}{{title|default:"Object Database"}}{% endblock %}</title>
+  {% block extrahead %}{% endblock %}
+ </head>
+ <body>
+  {% block body %}
+  {{content}}
+  {% endblock %}
+ </body>
+</html>

odb/templates/odb/form.html

+{% extends "odb/base.html" %}
+
+{% block body %}
+<form action="" method="post">{% csrf_token %}
+<table>
+{{form}}
+</table>
+<input type="submit" value="{{button|default:"Submit"}}" /></form>
+{% endblock %}

odb/templates/odb/manage.html

+{% extends "odb/object_list.html" %}
+
+{% block title %}Management Console{% endblock %}
+
+{% block extranav %}
+<form action="/create{{path}}" method="post">{% csrf_token %}
+New Object: <input type="text" name="obj_name" />
+<input type="submit" value="Create Object"/>
+</form>
+{% endblock %}
+
+{% block body %}
+{{block.super}}
+<a href="{{path}}">View on site</a>
+{% endblock %}

odb/templates/odb/model.html

+{% extends "odb/base.html" %}
+
+{% block title %}{{class}} - {{path}}{% endblock %}
+
+{% block body %}
+<h2>{{class}} - {{path}}</h2>
+<table>
+<thead><tr><th>Field name</th><th>Value</th></tr></thead>
+<tbody>
+{% for field in object %}
+<tr><td>{{field.name|title}}</td><td>{{field.value}}</td></tr> 
+{% endfor %}
+</tbody></table>
+<a href="/manage{{path}}">Edit</a>
+{% endblock %}

odb/templates/odb/object_list.html

+{% extends "odb/base.html" %}
+
+{% block title %}Object Database - {{path}}{% endblock %}
+
+{% block body %}
+<h2>{{path}}</h2>
+{% block extranav %}<a href="/manage{{path}}">Management Console</a>{% endblock %}
+<ul>
+{% for ob in object_list %}
+{% if ob.is_directory %}
+<li><a href="{{ob.name}}/">{{ob.name}}</a> - Directory</li>
+{% else %}
+<li><a href="{{ob.name}}">{{ob.name}}</a> - {{ob.class}}</li>
+{% endif %}
+{% endfor %}
+</ul>
+{% endblock %}
+"""
+This file demonstrates writing tests using the unittest module. These will pass
+when you run "manage.py test".
+
+Replace this 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.assertEqual(1 + 1, 2)
+from odb.models import odb_dict
+
+def get_object(path):
+    if path == '/':
+        return odb_dict
+    if path[-1] == '/':
+        path = path[:-1]
+    try:
+        o = "odb_dict"
+        for e in path[1:].split('/'):
+            o += "['%s']" % e
+        ob = eval(o)
+    except KeyError:
+        return None
+    return ob
+
+def put_object(path, o):
+    if path == '/':
+        return False
+    if path[-1] == '/':
+        path = path[:-1]
+    ob = "odb_dict"
+    for e in path[1:].split('/')[:-1]:
+        ob += "['%s']" % str(e)
+    eval(ob)[str(path.split('/')[-1])] = o
+    odb_dict.sync()
+    return True
+from odb.traverse import get_object, put_object
+from django.http import HttpResponse
+from odb.models import ContentObject, ObjectGroup, Model, Person
+from django.views.generic.edit import FormView
+from django.shortcuts import redirect, render
+
+def manage(req, path):
+    o = get_object(path)
+    if hasattr(o, 'iteritems') and callable(o.iteritems):
+        object_list = []
+        for k, v in o.iteritems():
+            obj = {'name':k, 'class':v.__class__.__name__}
+            if isinstance(v, dict): obj.update({'is_directory':True})
+            object_list.append(obj)
+        return render(req, "odb/manage.html", {'object_list':object_list,'path':path})
+    if not isinstance(o, Model):
+        return HttpResponse('Object type not supported.')
+    if req.method == 'POST':
+        form = o.get_form_class()(req.POST)
+        if o.process_form(form):
+            if put_object(path, o):
+                return redirect(path)
+            return HttpResponse('Error saving object.')
+    else:
+        form = o.get_form()
+    return render(req, "odb/form.html", {'form':form})
+
+def create(req, path):
+    if req.method == 'GET':
+        return HttpResponse('Error!')
+    obj_name = req.POST.get('obj_name', None)
+    if obj_name == None:
+        return redirect(path)
+    o = get_object(path)
+    if obj_name in o:
+        return redirect("%s%s" % (path, obj_name))
+    p = Person()
+    if put_object("%s%s" % (path,obj_name), p):
+        return redirect("/manage%s%s" % (path, obj_name))
+    return HttpResponse("Error creating object.")
+
+def remove(req, path):
+    o = get_object("/"+"/".join(path[1:].split('/')[:-1]))
+    del o[str(path[1:].split('/')[-1])]
+    return redirect(path)
+
+def mkdir(req, path):
+    put_object(path, {})
+    return redirect(path)
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.