mango r205 - in branches/django: . mango



Author: ovitters
Date: Sat Jun 21 17:58:09 2008
New Revision: 205
URL: http://svn.gnome.org/viewvc/mango?rev=205&view=rev

Log:
	Try and port the mess to Python using the Django framework.
	* .bzrignore: Ignore the django directory.
	* mango/manage.py: Standard Django script to manage the Django
	project.
	* mango/models.py: Describes the Database (needs a bit of work).
	* mango/settings.py: Django settings and the config.xml file.
	* mango/urls.py: Maps URLs to functions which will be called.
	* mango/views.py: Handles turning an http request into an http
	response (application/xml).


Added:
   branches/django/   (props changed)
      - copied from r204, /trunk/
   branches/django/.bzrignore
   branches/django/mango/
   branches/django/mango/manage.py   (contents, props changed)
   branches/django/mango/models.py
   branches/django/mango/settings.py
   branches/django/mango/urls.py
   branches/django/mango/views.py
Modified:
   branches/django/ChangeLog

Added: branches/django/.bzrignore
==============================================================================
--- (empty file)
+++ branches/django/.bzrignore	Sat Jun 21 17:58:09 2008
@@ -0,0 +1 @@
+django

Added: branches/django/mango/manage.py
==============================================================================
--- (empty file)
+++ branches/django/mango/manage.py	Sat Jun 21 17:58:09 2008
@@ -0,0 +1,11 @@
+#!/usr/bin/env python
+from django.core.management import execute_manager
+try:
+    import settings # Assumed to be in the same directory.
+except ImportError:
+    import sys
+    sys.stderr.write("Error: Can't find the file 'settings.py' in the directory containing %r. It appears you've customized things.\nYou'll have to run django-admin.py, passing it your settings module.\n(If the file settings.py does indeed exist, it's causing an ImportError somehow.)\n" % __file__)
+    sys.exit(1)
+
+if __name__ == "__main__":
+    execute_manager(settings)

Added: branches/django/mango/models.py
==============================================================================
--- (empty file)
+++ branches/django/mango/models.py	Sat Jun 21 17:58:09 2008
@@ -0,0 +1,75 @@
+# This is an auto-generated Django model module.
+# You'll have to do the following manually to clean this up:
+#     * Rearrange models' order
+#     * Make sure each model has one field with primary_key=True
+# Feel free to rename the models, but don't rename db_table values or field names.
+#
+# Also note: You'll have to insert the output of 'django-admin.py sqlcustom [appname]'
+# into your database.
+
+from django.db import models
+
+class AccountRequest(models.Model):
+    id = models.AutoField(primary_key=True)
+    uid = models.CharField(max_length=15)
+    cn = models.CharField(max_length=255)
+    mail = models.EmailField(max_length=255)
+    comment = models.TextField()
+    timestamp = models.DateTimeField()
+    authorizationkeys = models.TextField()
+    status = models.CharField(max_length=1, default='P')
+    is_new_account = models.CharField(max_length=1, default='Y')
+    is_mail_verified = models.CharField(max_length=1, default='N')
+    mail_token = models.CharField(max_length=40)
+    class Meta:
+        db_table = u'account_request'
+
+class AccountGroups(models.Model):
+    id = models.AutoField(primary_key=True)
+    request = models.ForeignKey(AccountRequest)
+    cn = models.CharField(max_length=15)
+    voucher_group = models.CharField(max_length=50, blank=True, null=True)
+    verdict = models.CharField(max_length=1, default='P')
+    voucher = models.CharField(max_length=15, blank=True, null=True)
+    denial_message = models.CharField(max_length=255, blank=True, null=True)
+    class Meta:
+        db_table = u'account_groups'
+
+class Foundationmembers(models.Model):
+    id = models.IntegerField(primary_key=True)
+    firstname = models.CharField(max_length=150, blank=True)
+    lastname = models.CharField(max_length=150, blank=True)
+    email = models.CharField(max_length=300, blank=True)
+    comments = models.TextField(blank=True)
+    first_added = models.DateField()
+    last_renewed_on = models.DateField(null=True, blank=True)
+    last_update = models.DateTimeField()
+    resigned_on = models.DateField(null=True, blank=True)
+    class Meta:
+        db_table = u'foundationmembers'
+
+class Ftpmirrors(models.Model):
+    name = models.CharField(max_length=60, blank=True)
+    url = models.CharField(max_length=300, blank=True)
+    location = models.CharField(max_length=72, blank=True)
+    email = models.CharField(max_length=120, blank=True)
+    comments = models.TextField(blank=True)
+    description = models.TextField(blank=True)
+    id = models.IntegerField(primary_key=True)
+    active = models.IntegerField(null=True, blank=True)
+    last_update = models.DateTimeField()
+    class Meta:
+        db_table = u'ftpmirrors'
+
+class Webmirrors(models.Model):
+    name = models.CharField(max_length=60, blank=True)
+    url = models.CharField(max_length=300, blank=True)
+    location = models.CharField(max_length=72, blank=True)
+    email = models.CharField(max_length=120, blank=True)
+    comments = models.TextField(blank=True)
+    description = models.TextField(blank=True)
+    id = models.IntegerField(primary_key=True)
+    active = models.IntegerField(null=True, blank=True)
+    class Meta:
+        db_table = u'webmirrors'
+

Added: branches/django/mango/settings.py
==============================================================================
--- (empty file)
+++ branches/django/mango/settings.py	Sat Jun 21 17:58:09 2008
@@ -0,0 +1,146 @@
+# Django settings for mango project.
+
+DEBUG = True
+TEMPLATE_DEBUG = DEBUG
+
+ADMINS = (
+    # ('Your Name', 'your_email domain com'),
+)
+
+MANAGERS = ADMINS
+
+DATABASE_ENGINE = 'mysql'           # 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'.
+DATABASE_NAME = 'mango'             # Or path to database file if using sqlite3.
+DATABASE_USER = 'root'             # Not used with sqlite3.
+DATABASE_PASSWORD = ''         # Not used with sqlite3.
+DATABASE_HOST = ''             # Set to empty string for localhost. Not used with sqlite3.
+DATABASE_PORT = ''             # Set to empty string for default. Not used with sqlite3.
+
+# 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.
+# If running in a Windows environment this must be set to the same as your
+# system time zone.
+TIME_ZONE = 'UTC'
+
+
+SITE_ROOT = r'mango/django/'
+# Language code for this installation. All choices can be found here:
+# http://www.i18nguy.com/unicode/language-identifiers.html
+LANGUAGE_CODE = 'en-us'
+
+SITE_ID = 1
+
+# If you set this to False, Django will make some optimizations so as not
+# to load the internationalization machinery.
+USE_I18N = True
+
+# Absolute path to the directory that holds media.
+# Example: "/home/media/media.lawrence.com/"
+MEDIA_ROOT = ''
+
+# URL that handles the media served from MEDIA_ROOT. Make sure to use a
+# trailing slash if there is a path component (optional in other cases).
+# Examples: "http://media.lawrence.com";, "http://example.com/media/";
+MEDIA_URL = ''
+
+# URL prefix for admin media -- CSS, JavaScript and images. Make sure to use a
+# trailing slash.
+# Examples: "http://foo.com/media/";, "/media/".
+ADMIN_MEDIA_PREFIX = '/media/'
+
+# Make this unique, and don't share it with anybody.
+SECRET_KEY = 'u(9-ndez*a1wi-438du+!rx$o+7nntz1w$tb0i_3m)+w$jt=sh'
+
+# List of callables that know how to import templates from various sources.
+TEMPLATE_LOADERS = (
+    'django.template.loaders.filesystem.load_template_source',
+    'django.template.loaders.app_directories.load_template_source',
+#     'django.template.loaders.eggs.load_template_source',
+)
+
+SESSION_ENGINE = "django.contrib.sessions.backends.file"
+
+MIDDLEWARE_CLASSES = (
+    'django.middleware.common.CommonMiddleware',
+    'django.contrib.sessions.middleware.SessionMiddleware',
+    'django.contrib.auth.middleware.AuthenticationMiddleware',
+    'django.middleware.doc.XViewMiddleware',
+)
+
+ROOT_URLCONF = 'mango.urls'
+
+TEMPLATE_DIRS = (
+    # Put strings here, like "/home/html/django_templates" or "C:/www/django/templates".
+    # Always use forward slashes, even on Windows.
+    # Don't forget to use absolute paths, not relative paths.
+)
+
+INSTALLED_APPS = (
+#    'django.contrib.auth',
+    'django.contrib.contenttypes',
+    'django.contrib.sessions',
+    'django.contrib.sites',
+)
+
+
+cfg_opts = set((
+    'cached_date',       # Date config last read from disk
+    'mode',              # Runtime mode (Live/Preview/Development)
+    'base_url',          # Base URL
+
+    'accounts_db_url',   # Mirrors MySQL database URL
+    'mirrors_db_url',    # Mirrors MySQL database URL
+    'membership_db_url', # Foundation membership MySQL database URL
+
+    'mail_backend',       # Mail backend
+    'mail_sendmail_path', # Path to sendmail (sendmail backend)
+    'mail_sendmail_args', # Additional options for sendmail (sendmail backend)
+    'mail_smtp_host',     # SMTP server hostname (smtp backend)
+    'mail_smtp_port',     # SMTP server port (smtp backend)
+    'mail_smtp_auth',     # Whether or not to use smtp authentication (smtp backend)
+    'mail_smtp_username', # Username to use for SMTP authentication (smtp backend)
+    'mail_smtp_password', # Password to use for SMTP authentication (smtp backend)
+    'mail_smtp_localhost', # Value to give when sending EHLO or HELO (smtp backend)
+    'mail_smtp_timeout',  # SMTP connection timeout
+    'mail_smtp_persist',  # Whether or not to use persistent SMTP connections (smtp backend)
+
+    'ldap_url',            # LDAP URL
+    'ldap_binddn',         # LDAP bind DN
+    'ldap_bindpw',         # LDAP bind PW
+    'ldap_basedn',         # LDAP base DN
+    'ldap_users_basedn',   # LDAP users base DN
+    'ldap_groups_basedn',  # LDAP groups base DN
+    'ldap_modules_basedn', # LDAP modules base DN
+    'ldap_aliases_basedn', # LDAP aliases base DN
+
+    'token_salt',          # Salt to be used in e-mail tokens
+
+    'support_email',       # Support e-mail
+    'account_email',       # Email address of person(s) who handles account management -->
+
+    'session_path'        # Session save path
+))
+
+MANGO_CFG = {}
+
+try:
+    import xml.etree.cElementTree as et
+except ImportError:
+    import cElementTree as et
+
+cfg_files = ('/var/www/mango/config.xml', '/etc/mango/config.xml')
+
+import os.path
+for f in cfg_files:
+    if os.path.exists(f):
+        doc = et.parse(file(f, 'r'))
+        root = doc.getroot()
+        for el in root.getchildren():
+            if el.tag in cfg_opts:
+                MANGO_CFG[el.tag] = el.text
+        
+        break
+
+    MANGO_CFG['base_url'] = 'http://localhost/mango/django/www'
+

Added: branches/django/mango/urls.py
==============================================================================
--- (empty file)
+++ branches/django/mango/urls.py	Sat Jun 21 17:58:09 2008
@@ -0,0 +1,16 @@
+from django.conf.urls.defaults import *
+
+from mango.views import current_datetime, list_users, test_index, list_accounts
+import mango.settings
+
+urlpatterns = patterns('',
+    (r'^%stime/$' % mango.settings.SITE_ROOT, current_datetime),
+    (r'^%susers/$' % mango.settings.SITE_ROOT, list_users),
+    (r'^%stest/$' % mango.settings.SITE_ROOT, test_index),
+    (r'^%saccounts/$' % mango.settings.SITE_ROOT, list_accounts),
+    # Example:
+    # (r'^mango/', include('mango.foo.urls')),
+
+    # Uncomment this for admin:
+#     (r'^admin/', include('django.contrib.admin.urls')),
+)

Added: branches/django/mango/views.py
==============================================================================
--- (empty file)
+++ branches/django/mango/views.py	Sat Jun 21 17:58:09 2008
@@ -0,0 +1,79 @@
+from django.http import HttpResponse
+from django.conf import settings
+import datetime
+
+import ldap
+import models
+
+try:
+    import xml.etree.cElementTree as ET
+except ImportError:
+    import cElementTree as ET
+
+
+def get_xmldoc(title, request):
+    doc = ET.ElementTree(ET.Element('page', {
+        'title': title,
+        'mode': settings.MANGO_CFG['mode'],
+        'baseurl': settings.MANGO_CFG['base_url'],
+        'thisurl': request.path,
+        'token': "afd0e0d9eab69ab904c7a43f6bd3810156f0afc9", # TODO: generate token
+        'support': settings.MANGO_CFG['support_email'],
+    }))
+
+    # TODO: 
+    #  - determine if user is logged in, if so:
+    #    add user details to XML
+
+    return doc, doc.getroot()
+
+def get_xmlresponse(doc, template, response=None):
+    if response is None:
+        response = HttpResponse(mimetype='text/xml')
+
+    response.write(ET.tostring(ET.ProcessingInstruction('xml-stylesheet', 'href="%s" type="text/xsl"' % template)))
+    doc.write(response, 'utf-8')
+    return response
+
+def current_datetime(request):
+    now = datetime.datetime.now()
+    html = "<html><body>It is now %s.</body></html>" % now
+    return HttpResponse(html)
+
+
+def list_users(request):
+    l = ldap.initialize(settings.MANGO_CFH['ldap_url'])
+#    l.simple_bind("cn=Manager,dc=gnome,dc=org")
+
+    filter = '(objectClass=posixAccount)'
+    stuff = l.search_s(settings.MANGO_CFG['ldap_users_basedn'],
+               ldap.SCOPE_SUBTREE, filter, None)
+
+    html = '<pre>%s</pre>' % "\n".join(["%s: %s" % (item[0], repr(item[1])) for item in stuff])
+    return HttpResponse(html)
+
+def test_index(request):
+    doc, root = get_xmldoc('Login Page', request)
+    root.append(ET.Element('homepage'))
+
+    return get_xmlresponse(doc, "../www/index.xsl")
+
+def list_accounts(request):
+    doc, root = get_xmldoc('List Accounts', request)
+    el1 = ET.SubElement(root, 'listaccounts')
+
+    accounts = models.AccountRequest.objects.all()
+    for account in accounts:
+        el2 = ET.SubElement(el1, 'account', dict([a for a in account.__dict__.iteritems() if a[0] not in ('id', 'timestamp')]))
+        el2g = ET.SubElement(el2, 'groups')
+        for group in account.accountgroups_set.filter(verdict__exact='A'):
+            d = {'cn': group.cn}
+            if group.voucher is not None:
+                d['approvedby'] = group.voucher
+                d['module'] = group.voucher_group
+
+            el3 = ET.SubElement(el2g, 'group', d)
+
+    return get_xmlresponse(doc, "../www/list_accounts.xsl")
+
+



[Date Prev][Date Next]   [Thread Prev][Thread Next]   [Thread Index] [Date Index] [Author Index]