Changeset - 664a5b8c551a
[Not reviewed]
default
0 12 0
Marcin Kuzminski - 15 years ago 2010-07-14 18:31:06
marcin@python-works.com
Added application settings, are now customizable from database
fixed all instances of sqlachemy to be removed() after execution.
12 files changed with 115 insertions and 36 deletions:
0 comments (0 inline, 0 general)
pylons_app/controllers/admin/admin.py
Show inline comments
 
@@ -40,9 +40,8 @@ class AdminController(BaseController):
 
    
 
    @HasPermissionAllDecorator('hg.admin')        
 
    def index(self):
 
        sa = meta.Session
 
                         
 
        users_log = sa.query(UserLog).order_by(UserLog.action_date.desc())
 
                                 
 
        users_log = self.sa.query(UserLog).order_by(UserLog.action_date.desc())
 
        p = int(request.params.get('page', 1))
 
        c.users_log = Page(users_log, page=p, items_per_page=10)
 
        c.log_data = render('admin/admin_log.html')
pylons_app/controllers/admin/settings.py
Show inline comments
 
@@ -2,7 +2,7 @@
 
# encoding: utf-8
 
# settings controller for pylons
 
# Copyright (C) 2009-2010 Marcin Kuzminski <marcin@python-works.com>
 
 
 

	
 
# This program is free software; you can redistribute it and/or
 
# modify it under the terms of the GNU General Public License
 
# as published by the Free Software Foundation; version 2
 
@@ -23,20 +23,23 @@ settings controller for pylons
 
@author: marcink
 
"""
 
from formencode import htmlfill
 
from pylons import request, session, tmpl_context as c, url, app_globals as g
 
from pylons import request, session, tmpl_context as c, url, app_globals as g, \
 
    config
 
from pylons.controllers.util import abort, redirect
 
from pylons.i18n.translation import _
 
from pylons_app.lib import helpers as h
 
from pylons_app.lib.auth import LoginRequired, HasPermissionAllDecorator
 
from pylons_app.lib.base import BaseController, render
 
from pylons_app.lib.utils import repo2db_mapper, invalidate_cache
 
from pylons_app.model.db import User, UserLog
 
from pylons_app.model.forms import UserForm
 
from pylons_app.lib.utils import repo2db_mapper, invalidate_cache, \
 
    set_hg_app_config
 
from pylons_app.model.db import User, UserLog, HgAppSettings
 
from pylons_app.model.forms import UserForm, ApplicationSettingsForm
 
from pylons_app.model.hg_model import HgModel
 
from pylons_app.model.user_model import UserModel
 
import formencode
 
import logging
 

	
 
import traceback
 
 
 
log = logging.getLogger(__name__)
 

	
 

	
 
@@ -58,7 +61,15 @@ class SettingsController(BaseController)
 
    def index(self, format='html'):
 
        """GET /admin/settings: All items in the collection"""
 
        # url('admin_settings')
 
        return render('admin/settings/settings.html')
 

	
 
        hgsettings = self.sa.query(HgAppSettings).scalar()
 
        defaults = hgsettings.__dict__ if hgsettings else {}
 
        return htmlfill.render(
 
            render('admin/settings/settings.html'),
 
            defaults=defaults,
 
            encoding="UTF-8",
 
            force_defaults=False
 
        )  
 
    
 
    def create(self):
 
        """POST /admin/settings: Create a new item"""
 
@@ -83,7 +94,46 @@ class SettingsController(BaseController)
 
            initial = HgModel.repo_scan(g.paths[0][0], g.paths[0][1], g.baseui)
 
            repo2db_mapper(initial, rm_obsolete)
 
            invalidate_cache('cached_repo_list')
 
        
 
        if id == 'global':
 
            
 
            application_form = ApplicationSettingsForm()()
 
            try:
 
                form_result = application_form.to_python(dict(request.POST))
 
                title = form_result['app_title']
 
                realm = form_result['app_auth_realm']
 
            
 
                try:
 
                    hgsettings = self.sa.query(HgAppSettings).get(1)
 
                    hgsettings.app_auth_realm = realm
 
                    hgsettings.app_title = title
 
                    
 
                    self.sa.add(hgsettings)
 
                    self.sa.commit()
 
                    set_hg_app_config(config)
 
                    h.flash(_('Updated application settings'),
 
                            category='success')
 
                                    
 
                except:
 
                    log.error(traceback.format_exc())
 
                    h.flash(_('error occured during chaning application settings'),
 
                            category='error')
 
                                
 
                    self.sa.rollback()
 
                    
 

	
 
            except formencode.Invalid as errors:
 
                c.form_errors = errors.error_dict
 
                return htmlfill.render(
 
                     render('admin/settings/settings.html'),
 
                    defaults=errors.value,
 
                    encoding="UTF-8") 
 
                        
 
            
 
            
 
            
 
            
 

	
 
            
 
        return redirect(url('admin_settings'))
 

	
pylons_app/controllers/admin/users.py
Show inline comments
 
@@ -76,7 +76,6 @@ class UsersController(BaseController):
 
                defaults=errors.value,
 
                encoding="UTF-8")
 
        except Exception:
 
            
 
            h.flash(_('error occured during creation of user') \
 
                    % request.POST.get('username'), category='error')            
 
        return redirect(url('users'))
pylons_app/lib/auth.py
Show inline comments
 
@@ -47,7 +47,10 @@ def get_crypt_password(password):
 
@cache_region('super_short_term', 'cached_user')
 
def get_user_cached(username):
 
    sa = meta.Session
 
    user = sa.query(User).filter(User.username == username).one()
 
    try:
 
        user = sa.query(User).filter(User.username == username).one()
 
    finally:
 
        meta.Session.remove()
 
    return user
 

	
 
def authfunc(environ, username, password):
 
@@ -89,8 +92,12 @@ def set_available_permissions(config):
 
    @param config:
 
    """
 
    log.info('getting information about all available permissions')
 
    sa = meta.Session
 
    all_perms = sa.query(Permission).all()
 
    try:
 
        sa = meta.Session
 
        all_perms = sa.query(Permission).all()
 
    finally:
 
        meta.Session.remove()
 
    
 
    config['available_permissions'] = [x.permission_name for x in all_perms]
 

	
 
def set_base_path(config):
 
@@ -140,7 +147,8 @@ def fill_perms(user):
 
                p = 'repository.write'
 
            else:
 
                p = perm.Permission.permission_name
 
            user.permissions['repositories'][perm.Repo2Perm.repository] = p            
 
            user.permissions['repositories'][perm.Repo2Perm.repository] = p
 
    meta.Session.remove()         
 
    return user
 
    
 
def get_user(session):
pylons_app/lib/db_manage.py
Show inline comments
 
@@ -34,7 +34,7 @@ sys.path.append(ROOT)
 
from pylons_app.lib.auth import get_crypt_password
 
from pylons_app.model import init_model
 
from pylons_app.model.db import User, Permission, HgAppUi, HgAppSettings
 
from pylons_app.model.meta import Session, Base
 
from pylons_app.model import meta
 
from sqlalchemy.engine import create_engine
 
import logging
 

	
 
@@ -51,7 +51,7 @@ class DbManage(object):
 
        dburi = 'sqlite:////%s' % jn(ROOT, self.dbname)
 
        engine = create_engine(dburi, echo=log_sql) 
 
        init_model(engine)
 
        self.sa = Session()
 
        self.sa = meta.Session
 
        self.db_exists = False
 
    
 
    def check_for_db(self, override):
 
@@ -71,7 +71,7 @@ class DbManage(object):
 
            log.info("database exisist and it's going to be destroyed")
 
            if self.db_exists:
 
                os.remove(jn(ROOT, self.dbname))
 
        Base.metadata.create_all(checkfirst=override)
 
        meta.Base.metadata.create_all(checkfirst=override)
 
        log.info('Created tables for %s', self.dbname)
 
    
 
    def admin_prompt(self):
pylons_app/lib/middleware/simplehg.py
Show inline comments
 
@@ -52,8 +52,7 @@ class SimpleHg(object):
 
        self.application = application
 
        self.config = config
 
        #authenticate this mercurial request using 
 
        realm = self.config['hg_app_auth_realm']
 
        self.authenticate = AuthBasicAuthenticator(realm, authfunc)
 
        self.authenticate = AuthBasicAuthenticator('', authfunc)
 
        
 
    def __call__(self, environ, start_response):
 
        if not is_mercurial(environ):
 
@@ -64,6 +63,7 @@ class SimpleHg(object):
 
        #===================================================================
 
        username = REMOTE_USER(environ)
 
        if not username:
 
            self.authenticate.realm = self.config['hg_app_auth_realm']
 
            result = self.authenticate(environ)
 
            if isinstance(result, str):
 
                AUTH_TYPE.update(environ, 'basic')
 
@@ -208,7 +208,9 @@ class SimpleHg(object):
 
        except Exception as e:
 
            sa.rollback()
 
            log.error('could not log user action:%s', str(e))
 
    
 
        finally:
 
            meta.Session.remove()
 
        
 
    def __invalidate_cache(self, repo_name):
 
        """we know that some change was made to repositories and we should
 
        invalidate the cache to see the changes right away but only for
pylons_app/lib/utils.py
Show inline comments
 
@@ -29,7 +29,7 @@ import logging
 
from mercurial import ui, config, hg
 
from mercurial.error import RepoError
 
from pylons_app.model.db import Repository, User, HgAppUi, HgAppSettings
 
from pylons_app.model.meta import Session
 
from pylons_app.model import meta
 
log = logging.getLogger(__name__)
 

	
 

	
 
@@ -80,12 +80,21 @@ def check_repo(repo_name, base_path, ver
 

	
 
@cache_region('super_short_term', 'cached_hg_ui')
 
def get_hg_ui_cached():
 
    sa = Session()
 
    return sa.query(HgAppUi).all()    
 
    try:
 
        sa = meta.Session
 
        ret = sa.query(HgAppUi).all()
 
    finally:
 
        meta.Session.remove()
 
    return ret
 

	
 

	
 
def get_hg_settings():
 
    sa = Session()
 
    ret = sa.query(HgAppSettings).scalar()
 
    try:
 
        sa = meta.Session
 
        ret = sa.query(HgAppSettings).scalar()
 
    finally:
 
        meta.Session.remove()
 
        
 
    if not ret:
 
        raise Exception('Could not get application settings !')
 
    return ret
 
@@ -183,7 +192,7 @@ def repo2db_mapper(initial_repo_list, re
 
    """
 
    from pylons_app.model.repo_model import RepoModel
 
    
 
    sa = Session()
 
    sa = meta.Session
 
    user = sa.query(User).filter(User.admin == True).first()
 
    
 
    rm = RepoModel()
 
@@ -208,3 +217,5 @@ def repo2db_mapper(initial_repo_list, re
 
                sa.delete(repo)
 
                sa.commit()
 

	
 
    
 
    meta.Session.remove()
pylons_app/model/forms.py
Show inline comments
 
@@ -267,5 +267,14 @@ def RepoSettingsForm(edit=False):
 
    return _RepoForm
 

	
 

	
 
def ApplicationSettingsForm():
 
    class _ApplicationSettingsForm(formencode.Schema):
 
        allow_extra_fields = True
 
        filter_extra_fields = False
 
        app_title = UnicodeString(strip=True, min=3, not_empty=True)
 
        app_auth_realm = UnicodeString(strip=True, min=3, not_empty=True)
 
        
 
    return _ApplicationSettingsForm
 
 
 

	
 

	
pylons_app/model/hg_model.py
Show inline comments
 
@@ -28,7 +28,7 @@ from beaker.cache import cache_region
 
from mercurial import ui
 
from mercurial.hgweb.hgwebdir_mod import findrepos
 
from vcs.exceptions import RepositoryError, VCSError
 
from pylons_app.model.meta import Session
 
from pylons_app.model import meta
 
from pylons_app.model.db import Repository
 
from sqlalchemy.orm import joinedload
 
import logging
 
@@ -81,7 +81,7 @@ class HgModel(object):
 
        :param repos_path: path to directory it could take syntax with 
 
        * or ** for deep recursive displaying repositories
 
        """
 
        sa = Session()
 
        sa = meta.Session()
 
        def check_repo_dir(path):
 
            """
 
            Checks the repository
 
@@ -122,6 +122,7 @@ class HgModel(object):
 
                        repos_list[name].contact = dbrepo.user.full_contact
 
            except OSError:
 
                continue
 
        meta.Session.remove()
 
        return repos_list
 
        
 
    def get_repos(self):
pylons_app/templates/admin/settings/settings.html
Show inline comments
 
@@ -20,7 +20,7 @@
 
     ${h.form(url('admin_setting', id='mapping'),method='put')}
 
       <table class="table_disp">
 
           <tr class="header">
 
            <td colspan="2">${_('Remap andv rescan repositories')}</td>
 
            <td colspan="2">${_('Remap and rescan repositories')}</td>
 
           </tr>
 
           <tr align="right">
 
            <td><span class="tooltip" tooltip_title="${h.tooltip(_('In case a repository was deleted from filesystem and there are leftovers in the database check this option to scan obsolete data in database and remove it.'))}">
 
@@ -36,11 +36,11 @@
 
	       </tr>
 
	       <tr>
 
	           <td>${_('Application name')}</td>
 
	           <td>${h.text('app_title')}</td>
 
	           <td>${h.text('app_title',size=30)}${self.get_form_error('app_title')}</td>
 
	       </tr>
 
           <tr>
 
               <td>${_('Realm text')}</td>
 
               <td>${h.text('app_auth_realm')}</td>
 
               <td>${h.text('app_auth_realm',size=30)}${self.get_form_error('app_auth_realm')}</td>
 
           </tr>
 
           <tr>
 
	           <td></td>
pylons_app/templates/index.html
Show inline comments
 
## -*- coding: utf-8 -*-
 
<%inherit file="base/base.html"/>
 
<%def name="title()">
 
    ${c.repos_prefix} Mercurial Repositories
 
    ${c.repos_prefix}
 
</%def>
 
<%def name="breadcrumbs()">
 
	${c.repos_prefix} Mercurial Repositories
 
	${c.repos_prefix}
 
</%def>
 
<%def name="page_nav()">
 
	${self.menu('home')}
pylons_app/templates/login.html
Show inline comments
 
## -*- coding: utf-8 -*-
 
<%inherit file="base/base.html"/>
 
<%def name="title()">
 
    ${c.repos_prefix} Mercurial Repositories
 
    ${c.repos_prefix}
 
</%def>
 
<%def name="breadcrumbs()">
 
	${c.repos_prefix} Mercurial Repositories
 
	${c.repos_prefix}
 
</%def>
 
<%def name="page_nav()">
 
	&nbsp;
0 comments (0 inline, 0 general)