save point (see note)

Added initial database schema and ability to install it, added init-db command
to pyramid scaffold.
This commit is contained in:
Lance Edgar 2012-03-24 12:15:11 -05:00
parent 925cd30b96
commit 8ceb98baf4
29 changed files with 1116 additions and 191 deletions

View file

@ -5,10 +5,15 @@
"""
import os.path
import edbob
import pyramid_beaker
from pyramid.config import Configurator
import edbob
from {{package}}._version import __version__
from {{package}}.db import DBSession
def main(global_config, **settings):
"""
@ -39,7 +44,7 @@ def main(global_config, **settings):
config.set_session_factory(session_factory)
pyramid_beaker.set_cache_regions_from_settings(settings)
# Initialize edbob
# Configure edbob
edbob.basic_logging()
edbob.init('{{package}}', os.path.abspath(settings['edbob.config']))

View file

@ -0,0 +1,82 @@
#!/usr/bin/env python
"""
``{{package}}.commands`` -- Console Commands
"""
import sys
import edbob
from edbob import commands
from {{package}} import __version__
class Command(commands.Command):
"""
The primary command for {{project}}.
"""
name = '{{package}}'
version = __version__
description = "{{project}}"
long_description = ''
class InitDatabaseCommand(commands.Subcommand):
"""
Initializes the database. This is meant to be leveraged as part of setting
up the application. The database used by this command will be determined
by config, for example::
.. highlight:: ini
[edbob.db]
sqlalchemy.url = postgresql://user:pass@localhost/{{package}}
"""
name = 'init-db'
description = "Initialize the database"
def run(self, args):
from edbob.db import engine, Session
from edbob.db.util import install_core_schema
from edbob.db.exceptions import CoreSchemaAlreadyInstalled
# Install core schema to database.
try:
install_core_schema(engine)
except CoreSchemaAlreadyInstalled, err:
print err
return
from edbob.db.classes import Role, User
from edbob.db.auth import administrator_role
session = Session()
# Create 'admin' user with full rights.
admin = User(username='admin', password='admin')
admin.roles.append(administrator_role(session))
session.add(admin)
# Do any other bootstrapping you like here...
session.commit()
session.close()
print "Initialized database %s" % engine.url
def main(*args):
"""
The primary entry point for the command system.
"""
if args:
args = list(args)
else:
args = sys.argv[1:]
cmd = Command()
cmd.run(*args)

View file

@ -0,0 +1,11 @@
#!/usr/bin/env python
"""
``{{package}}.db`` -- Database Stuff
"""
from sqlalchemy.orm import scoped_session, sessionmaker
from zope.sqlalchemy import ZopeTransactionExtension
DBSession = scoped_session(sessionmaker(extension=ZopeTransactionExtension()))

View file

@ -5,9 +5,13 @@
Welcome to the {{project}} project.
Installation
------------
Getting Started
---------------
Install the project with::
- cd <directory containing this file>
$ pip install {{package}}
- $venv/bin/python setup.py develop
- $venv/bin/populate_{{package}} development.ini
- $venv/bin/pserve --reload development.ini

View file

@ -51,6 +51,9 @@ port = 6543
[edbob]
include_config = ['%(here)s/production.ini']
[edbob.db]
sqlalchemy.url = sqlite:///{{package}}.sqlite
####################
# logging

View file

@ -41,9 +41,12 @@ port = 6543
####################
[edbob]
timezone = US/Central
init = edbob.time, edbob.db
# shell.python = ipython
[edbob.db]
sqlalchemy.url = postgresql://user:pass@localhost/{{package}}
[edbob.mail]
smtp.server = localhost
# smtp.username = user
@ -56,6 +59,9 @@ recipients.default = [
]
subject.default = Message from {{project}}
[edbob.time]
timezone = US/Central
####################
# logging

View file

@ -39,12 +39,19 @@ requires = [
#
# package # low high
'decorator', # 3.3.2
'edbob', # 0.1a1
'Mako', # 0.6.2
'pyramid', # 1.3b2
'pyramid_beaker', # 0.6.1
'pyramid_debugtoolbar', # 1.0
'pyramid_tm', # 0.3
'SQLAlchemy', # 0.7.6
'Tempita', # 0.5.1
'transaction', # 1.2.0
'waitress', # 0.8.1
'WebHelpers', # 1.3
'zope.sqlalchemy', # 0.7
]
@ -77,6 +84,12 @@ setup(
zip_safe = False,
entry_points = """
[console_scripts]
{{package}} = {{package}}.commands:main
[{{package}}.commands]
init-db = {{package}}.commands:InitDatabaseCommand
[paste.app_factory]
main = {{package}}:main

View file

@ -26,21 +26,56 @@
``edbob.pyramid.subscribers`` -- Subscribers
"""
from pyramid.security import authenticated_userid
# from sqlahelper import get_session
import edbob
from edbob.db.auth import has_permission
from edbob.pyramid import helpers
def add_renderer_globals(event):
def before_render(event):
"""
Adds goodies to the global template renderer context.
Adds goodies to the global template renderer context:
* ``h``
* ``url``
* ``edbob``
"""
renderer_globals = event
renderer_globals['h'] = helpers
renderer_globals['edbob'] = edbob
renderer_globals['url'] = event['request'].route_url
renderer_globals['edbob'] = edbob
def context_found(event):
"""
This hook attaches the :class:`edbob.User` instance for the currently
logged-in user to the request (if there is one) as ``request.user``.
Also adds a ``has_perm()`` function to the request, which is a shortcut for
:func:`edbob.db.auth.has_permission()`.
"""
def has_perm_func(request):
def has_perm(perm):
if not request.current_user:
return False
return has_permission(request.current_user, perm)
return has_perm
request = event.request
request.user = None
request.has_perm = has_perm_func(request)
uuid = authenticated_userid(request)
if uuid:
request.user = get_session().query(rattail.User).get(uuid)
def includeme(config):
config.add_subscriber('edbob.pyramid.subscribers:add_renderer_globals',
config.add_subscriber('edbob.pyramid.subscribers:before_render',
'pyramid.events.BeforeRender')
config.add_subscriber('edbob.pyramid.subscribers.context_found',
'pyramid.events.ContextFound')

View file

@ -31,6 +31,9 @@ import os.path
from pyramid.response import Response
from pyramid.view import view_config
from pyramid.httpexceptions import HTTPFound
from edbob.db.auth import authenticate_user
_here = os.path.join(os.path.dirname(__file__), os.pardir)
@ -51,6 +54,29 @@ def home(context, request):
@view_config(route_name='login', renderer='login.mako')
def login(context, request):
"""
The login view, responsible for displaying and handling the login form.
"""
if request.params.get('referer'):
referer = request.params['referer']
elif request.session.get('referer'):
referer = request.session.pop('referer')
else:
referer = request.referer or request.route_url('home')
# if request.current_user:
# return HTTPFound(location=referer)
# form = Form(self.request, schema=UserLogin)
# if form.validate():
# user = authenticate_user(self.Session(), form.data['username'], form.data['password'])
# if user:
# self.request.session.flash("%s logged in at %s" % (
# user.display_name,
# datetime.datetime.now().strftime("%I:%M %p")))
# headers = remember(self.request, user.uuid)
# return HTTPFound(location=referer, headers=headers)
# self.request.session.flash("Invalid username or password.")
# return {'form':FormRenderer(form), 'referer':referer}
return {}