Grigoriy Petukhov avatar Grigoriy Petukhov committed dbd07ae

Add django application

Comments (0)

Files changed (24)

 trustlink.php
 research.txt
 test_var
+example_site/settings_local.py
+example_site/var
 
 syntax:regexp
Add a comment to this file

example_site/__init__.py

Empty file added.

example_site/app.py

+import os
+import sys
+import os.path
+import site
+
+root = os.path.dirname(__file__)
+if not root in sys.path[:1]:
+    sys.path.insert(0, root)
+os.environ['DJANGO_SETTINGS_MODULE'] = 'settings'
+
+from django.core.handlers.wsgi import WSGIHandler
+application = WSGIHandler()

example_site/base.html

+<!doctype html>
+<html>
+<head>
+    <title>{% block title %}{% endblock %}</title>
+    <meta charset="utf-8">
+    <meta name="Keywords" content="{% block meta_keywords %}{% endblock %}" />
+    <meta name="Description" content="{% block meta_description %}{% endblock %}" />
+    <link rel="shortcut icon" href="{{ STATIC_URL }}favicon.ico" />
+
+    <link rel="stylesheet" href="{{ STATIC_URL }}css/reset.css">
+    <link rel="stylesheet" href="{{ STATIC_URL }}css/960.css">
+    <link rel="stylesheet" href="{{ STATIC_URL }}css/text.css">
+    <link rel="stylesheet" href="{{ STATIC_URL }}css/style.css">
+    {% block extra_css %}{% endblock %}
+
+    <!-- Grab Google CDN's jQuery, with a protocol relative URL; fall back to local if offline -->
+    <script src="//ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>
+    <script>window.jQuery || document.write('<script src="{{ STATIC_URL }}js/jquery-1.6.2.min.js"><\/script>')</script>
+
+    {% block extra_head %}{% endblock %}
+</head>
+
+<body>
+    <div id="container">
+        <header>
+            <div class="container_12">
+                <div class="grid_6">
+                    <div class="header-logo">
+                        <a href="/">
+                            <div class="site-name">
+                                {{ request.get_host.title }}
+                            </div>
+                        </a>
+                        <div class="description">django template</div>
+                    </div>
+                </div>
+                <div class="grid_6">
+                    <div class="header-banner">
+                    </div>
+                </div>
+            </div>
+            {% if messages %}
+            <div class="container_12">
+                <div class="grid_12">
+                    <div class="site-messages">
+                        {% for message in messages %}
+                        <li{% if message.tags %} class="{{ message.tags }}"{% endif %}>{{ message }}</li>
+                        {% endfor %}
+                    </div>
+                </div>
+            </div>
+            {% endif %}
+        </header>
+        <div id="main" role="main">
+            <div class="container_12">
+                <div class="grid_8">
+                    {% block content %}{% endblock %}
+                </div>
+                <div class="grid_4">
+                    {% block sidebar %}{% endblock %}
+                </div>
+            </div>
+        </div>
+        <footer>
+            <div class="container_12">
+                <div class="grid_6">
+                    <a href="/">{{ request.get_host.title }}</a> &copy; 2011
+                </div>
+                <div class="grid_6 right">
+                    {% include "counters.html" %}
+                </div>
+            </div>
+        </footer>
+    </div> <!--! end of #container -->
+
+    <script defer src="{{ STATIC_URL }}js/common.js"></script>
+    {% block extra_js %}{% endblock %}
+
+</body>
+</html>

example_site/fabfile.py

+from __future__ import with_statement
+from fabric import api
+from fabric.contrib import django
+import os
+
+# Configuration
+ENV_DIR = '.env'
+REMOTE_ROOT = ''
+api.env.user = 'web'
+api.env.hosts = []
+
+# Activate the virtualenv
+try:
+    activate_this = ENV_DIR + '/bin/activate_this.py'
+    execfile(activate_this, dict(__file__=activate_this))
+except IOError:
+    pass
+else:
+    django.settings_module('settings')
+
+
+def _database_name():
+    "Return name of default database"
+
+    import settings
+
+    return settings.DATABASES['default']['NAME']
+
+
+def _database_engine():
+    "Return engine of default database"
+
+    import settings
+
+    return settings.DATABASES['default']['ENGINE']
+
+
+def reset():
+    """
+    Drop databse, create new, then do syncdb and migrate.
+    """
+
+    import settings
+
+    if getattr(settings, 'DATABASE_RESET_SILENTLY', None):
+        response = 'yes'
+    else:
+        response = raw_input('Are you sure you want to reset site\'s database? Enter yes to continue: ')
+
+    if response == 'yes':
+        dbname = _database_name()
+        engine = _database_engine()
+        with api.settings(warn_only=True):
+            if 'psycopg' in engine:
+                api.local('dropdb %s' % dbname)
+            elif 'sqlite' in engine:
+                api.local('rm %s' % dbname)
+            else:
+                raise Exception('Unknown engine: %s' % engine)
+        if 'psycopg' in engine:
+            api.local('createdb %s' % dbname)
+        elif 'sqlite' in engine:
+            if not os.path.exists(os.path.split(dbname)[0]):
+                os.makedirs(os.path.split(dbname)[0])
+        api.local('./manage.py syncdb --noinput')
+        if 'south' in settings.INSTALLED_APPS:
+            api.local('./manage.py migrate')
+    else:
+        print 'Cancelling'
+
+
+def run():
+    "Run debug server"
+
+    api.local('./manage.py runserver 0.0.0.0:8000')
+
+
+def run_plus():
+    "Run debug server with werkzeug debugger"
+
+    api.local('./manage.py runserver_plus 0.0.0.0:8000')
+
+
+def buildenv():
+    # Ignore "IOError: [Errno 26] Text file busy: 'var/.env/bin/python'"
+    # when debug server is live
+    with api.settings(warn_only=True):
+        api.local('virtualenv --no-site-packages %s' % ENV_DIR, capture=False)
+    api.local('%s/bin/easy_install pip' % ENV_DIR, capture=False)
+    api.local('%s/bin/pip install --use-mirrors -r requirements.txt' % ENV_DIR, capture=False)
+
+
+def dbdump():
+    "Create dump of database"
+
+    api.local('pg_dump -Fc -Z9 -x -f /tmp/dump.pack %s' % _database_name())
+
+
+def dbsync():
+    """
+    Download remote database dump and load it into local database.
+    """
+
+    with api.cd(REMOTE_ROOT):
+        api.run('fab dbdump')
+    api.get('/tmp/dump.pack', '/tmp/dump.pack')
+    dbload()
+
+
+def dbload(path='/tmp/dump.pack'):
+    with api.settings(warn_only=True):
+        api.local('dropdb %s' % _database_name())
+        api.local('createdb %s' % _database_name())
+    with api.settings(warn_only=True):
+        api.local('pg_restore -v -c -x -d %s %s' % (_database_name(), path))
+
+
+def shell():
+    "Run shell_plus management command."
+
+    api.local('./manage.py shell_plus')
+
+
+def deploy():
+    import settings
+
+    api.local('hg push')
+    with api.cd(REMOTE_ROOT):
+        api.run('hg up')
+        api.run('./manage.py syncdb --noinput')
+        if 'south' in settings.INSTALLED_APPS:
+            api.run('./manage.py migrate')
+        api.run('touch app.py')
+
+
+def update_lib(name):
+    """
+    Update dependency which has record in requirements.txt matched to given ``name``.
+    """
+    
+    for line in open('requirements.txt'):
+        if name in line:
+            line = line.strip()
+            if not line.startswith('#'):
+                api.local('%s/bin/pip install --use-mirrors -U %s' % (ENV_DIR, line.strip()))
+
+
+def startapp(name):
+    """
+    Create application files from template.
+    """
+
+    api.local('cp -r .app_template %s' % name)

example_site/generate.py

+#!.env/bin/python
+# -*- coding: utf-8 -*-
+import os
+import sys
+from common.system import setup_django
+setup_django(__file__)
+
+from django.conf import settings
+from django.core.management import call_command
+from django.contrib.auth.models import User
+from django.contrib.sites.models import Site
+
+def common():
+    "Generate default users, default Site object."
+
+    try:
+        os.mkdir('var')
+    except OSError:
+        pass
+    
+    try:
+        from settings import DEFAULT_USERS
+    except ImportError:
+        pass
+    else:
+        for username, email, password, is_superuser in DEFAULT_USERS:
+            try:
+                User.objects.get(username=username)
+            except User.DoesNotExist:
+                print 'Creating %s user' % username
+                user = User.objects.create_user(username, email, password)
+                if is_superuser:
+                    user.is_superuser = True
+                    user.is_staff = True
+                    user.save()
+        
+    HOST = None
+    try:
+        from settings import HOSTNAME as HOST
+    except ImportError:
+        try:
+            from settings import DOMAIN as HOST
+        except ImportError:
+            try:
+                from settings import HOST
+            except ImportError:
+                pass
+
+
+    if HOST:
+        site = Site.objects.get_current()
+        site.domain = HOST
+        site.name = HOST
+        site.save()
+        print 'Configuring Site instance: %s' % HOST
+
+
+def all():
+    "Generate all possible data"
+
+    common()
+
+
+if __name__ == "__main__":
+    func = sys.argv[1]
+    globals()[func]()

example_site/manage.py

+#!/usr/bin/env python
+from django.core.management import execute_manager
+import imp
+try:
+    imp.find_module('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" % __file__)
+    sys.exit(1)
+
+import settings
+
+if __name__ == "__main__":
+    execute_manager(settings)
+

example_site/settings.py

+import os.path
+import sys
+
+ROOT = os.path.dirname(os.path.realpath(__file__))
+sys.path.insert(0, os.path.join(ROOT, 'apps'))
+
+# Debug
+DEBUG = True
+TEMPLATE_DEBUG = DEBUG
+
+# Admins
+ADMINS = (
+    ('Grigoriy Petukhov', 'lorien@lorien.name'),
+)
+MANAGERS = ADMINS
+
+# Time & locale
+TIME_ZONE = 'Europe/Moscow'
+LANGUAGE_CODE = 'ru-ru'
+USE_I18N = True
+USE_L10N = True
+SITE_ID = 1
+DATETIME_FORMAT = 'd F, Y H:i'
+DATE_FORMAT = 'd F, Y'
+
+# Static files
+MEDIA_ROOT = os.path.join(ROOT, 'static')
+MEDIA_URL = '/static/'
+STATIC_ROOT = os.path.join(ROOT, 'static/pub')
+STATIC_URL = '/static/pub/'
+STATICFILES_DIRS = ()
+STATICFILES_FINDERS = (
+    'django.contrib.staticfiles.finders.FileSystemFinder',
+    'django.contrib.staticfiles.finders.AppDirectoriesFinder',
+)
+
+# Templates
+TEMPLATE_LOADERS = (
+    'django.template.loaders.filesystem.Loader',
+    'django.template.loaders.app_directories.Loader',
+)
+
+TEMPLATE_DIRS = (
+    os.path.join(ROOT, 'templates'),
+)
+
+# Apps, middlewares
+MIDDLEWARE_CLASSES = (
+    #'django.middleware.cache.UpdateCacheMiddleware',
+    'django.contrib.sessions.middleware.SessionMiddleware',
+    'django.middleware.csrf.CsrfViewMiddleware',
+    'django.contrib.auth.middleware.AuthenticationMiddleware',
+    'django.contrib.messages.middleware.MessageMiddleware',
+    #'debug_toolbar.middleware.DebugToolbarMiddleware',
+    #'django.middleware.cache.FetchFromCacheMiddleware',
+)
+
+INSTALLED_APPS = (
+    'django.contrib.auth',
+    'django.contrib.contenttypes',
+    'django.contrib.sessions',
+    'django.contrib.sites',
+    'django.contrib.messages',
+    'django.contrib.staticfiles',
+    'django.contrib.admin',
+    # 3rd party libraries
+    'trustlink.django',
+)
+
+TEMPLATE_CONTEXT_PROCESSORS = (
+    'django.contrib.auth.context_processors.auth',
+    'django.core.context_processors.debug',
+    'django.core.context_processors.i18n',
+    'django.core.context_processors.media',
+    'django.core.context_processors.request',
+    'django.core.context_processors.static',
+    'django.contrib.messages.context_processors.messages',
+)
+ROOT_URLCONF = 'urls'
+
+# Logging
+LOGGING = {
+    'version': 1,
+    'disable_existing_loggers': False,
+    'formatters': {
+        'verbose': {
+            'format': '%(asctime)s %(module)s %(process)d %(thread)d %(message)s'
+        },
+        'simple': {
+            'format': '%(name)s %(levelname)s %(message)s'
+        },
+    },
+    'handlers': {
+        'mail_admins': {
+            'level': 'ERROR',
+            'class': 'django.utils.log.AdminEmailHandler'
+        },
+        'null': {
+            'level':'DEBUG',
+            'class':'django.utils.log.NullHandler',
+        },
+        'console':{
+            'level':'DEBUG',
+            'class':'logging.StreamHandler',
+            'formatter': 'simple'
+        }
+    },
+    'loggers': {
+        'django.request': {
+            'handlers': ['mail_admins'],
+            'level': 'ERROR',
+            'propagate': True,
+        },
+        'django': {
+            'handlers': ['console'],
+            'level': 'INFO',
+        },
+        'south': {
+            'handlers': ['console'],
+            'level': 'INFO',
+        },
+        '': {
+            'handlers': ['console'],
+            'level': 'DEBUG',
+        },
+    }
+}
+
+# Misc.
+TEST_DATABASE_CHARSET = 'utf8'
+DEFAULT_FROM_EMAIL = 'desconto.ru <noreply@desconto.ru>'
+DEBUG_TOOLBAR_CONFIG  = {
+    'INTERCEPT_REDIRECTS': False,
+}
+
+EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'
+SECRET_KEY = 'asdf97as8df79asd7f98as7df97ad'
+TRUSTLINK_DATA_DIR = os.path.join(ROOT, 'var')
+TRUSTLINK_HOST = 'test.com'
+
+from settings_local import *
+
+# Check that SECRET_KEY exists
+if not SECRET_KEY:
+    raise Exception('You must provide SECRET_KEY value in settings_local.py')

example_site/templates/404.html

+not found

example_site/templates/500.html

+5XX error

example_site/templates/base.html

+{% load trustlink_tags %}
+<body>
+    <table>
+        <tr>
+            <td><a href="/">Home</a></td>
+            <td>{% trustlink_links %}</td>
+        </tr>
+    </table>
+    <hr/>
+    {% block content %}{% endblock %}
+</body>

example_site/templates/home.html

+{% extends 'base.html' %}
+
+{% block content %}
+<h1>This is home page</h1>
+<ul>
+    <li><a href="/page/one">Page one</a></li>
+    <li><a href="/page/two">Page two</a></li>
+</ul>
+{% endblock %}

example_site/templates/page.html

+{% extends 'base.html' %}
+{% load trustlink_tags %}
+
+{% block content %}
+<h1>Page {{ name }}</h1>
+<p>
+Just for testing try to call trustlink tag again:
+{% trustlink_links %}
+{% endblock %}

example_site/urls.py

+from django.conf.urls.defaults import *
+from django.conf import settings
+from django.conf.urls.static import static
+from django.contrib import admin
+from django.views.generic.simple import direct_to_template
+
+admin.autodiscover()
+
+urlpatterns = patterns('',
+    url(r'^admin/', include(admin.site.urls)),
+    url(r'^$', 'views.home'),
+    url(r'^page/(.+)$', 'views.page'),
+) + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

example_site/views.py

+from django.shortcuts import render
+
+def home(request):
+    return render(request, 'home.html')
+
+
+def page(request, name):
+    return render(request, 'page.html', {'name': name})

trustlink/client.py

 import os.path
 import anydbm
 import json
+import urllib
 
 SPECIAL_KEYS = ('__test_tl_link__', '__trustlink_end__', '__trustlink__start__',
                 '__trustlink_robots__', '__trustlink_delimiter__',
                 '__trustlink__after_text__', '__trustlink_before_text__')
 
 
+class TrustlinkError(Exception):
+    pass
+
+
+def smart_str(val):
+    if isinstance(val, unicode):
+        return val.encode('utf-8')
+    else:
+        return val
+
+
 class TrustlinkClient(object):
     def __init__(self, trustlink_user, url, data_dir,
-                 remote_ip=None,
+                 remote_ip=None, test=False,
                  static=False, multi_site=False,
                  verbose=False, charset='utf-8', force_show_code=False,
                  request_headers=None, request_params=None):
         self.static = static
         self.data_dir = data_dir
         self.remote_ip = remote_ip
+        self.test = test
 
         if host_prepared.startswith('www.'):
             self.host = host_prepared[4:]
 
         self.trustlink_user = trustlink_user
         self.isrobot = False
-        self.test = False
 
-        if request_headers and request_headers.get('Trustlink') == self.trustlink_user:
+        if request_headers and request_headers.get('HTTP_TRUSTLINK') == self.trustlink_user:
             self.test = True
             self.isrobot = True
             self.verbose = True
             self.force_show_code = True
             self.verbose = True
 
+
     def build_links(self):
         db = self.init_database_handler()
         prepend = ''
         append = ''
 
-        start = db.get('__trustlink_start__', None)
+        def get(key, default=None):
+            val = db.get(key)
+            if val is not None:
+                return json.loads(val)
+            else:
+                return default
+
+        start = get('__trustlink_start__', None)
         if start:
-            if self.remote_ip in db.get('__trustlink_robots__', []):
+            if (self.remote_ip and self.remote_ip in get('__trustlink_robots__', [])
+                or self.force_show_code):
                 prepend += start
 
 
         if self.test:
             links = [
-                json.loads(db.get('__test_tl_link__', [])),
+                get('__test_tl_link__', []),
             ]
         else:
-            links = [json.loads(x) for x in db.get(self.url, [])]
+            links = [x for x in get(smart_str(self.url), [])]
 
         items = []
         for link in links:
             else:
                 item['url'] = link['url']
 
-            link_info = urlsplit(link['url'])
+            link_info = urlsplit(item['url'])
             host = link_info.hostname
             if host.startswith('www.'):
                 host = host[4:]
             item['host'] = host
             items.append(item)
 
-        end = db.get('__trustlink_end__', None)
+        end = get('__trustlink_end__', None)
         if end:
-            if self.remote_ip in db.get('__trustlink_robots__', []):
+            if (self.remote_ip and self.remote_ip in get('__trustlink_robots__', [])
+                or self.force_show_code):
                 append += end
 
         if self.test:
             prepend = '<noindex>' + prepend
             append = append + '</noindex>'
 
-        return {'prepend': prepend, 'items': items, 'append': append}
+        return {
+            'prepend': prepend,
+            'links': items,
+            'append': append,
+        }
 
     def init_database_handler(self):
         path = os.path.join(self.data_dir, 'trustlink.%s.db' % self.host)
+        if not os.path.exists(path):
+            raise TrustlinkError('Link database does not exist at %s' % path)
         db = anydbm.open(path)
         return db
 
         shutil.copy(tmp_path, path)
 
     def network_request(self, url):
-        return urllib.urlopen(tl_url).read()
+        return urllib.urlopen(url).read()
Add a comment to this file

trustlink/django/__init__.py

Empty file added.

Add a comment to this file

trustlink/django/management/__init__.py

Empty file added.

Add a comment to this file

trustlink/django/management/commands/__init__.py

Empty file added.

Add a comment to this file

trustlink/django/templatetags/__init__.py

Empty file added.

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.