Skip to content

Commit

Permalink
mucking around with resource based CRUD, not done, working in progress
Browse files Browse the repository at this point in the history
  • Loading branch information
dianaclarke committed May 5, 2012
1 parent a1210b4 commit 0cd0916
Show file tree
Hide file tree
Showing 17 changed files with 341 additions and 77 deletions.
2 changes: 1 addition & 1 deletion development.ini
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ pyramid.includes =
pyramid_debugtoolbar
pyramid_tm

sqlalchemy.url = sqlite:///%(here)s/pyconca.db
sqlalchemy.url = mysql://pyconca:[email protected]/pyconca?charset=utf8

[server:main]
use = egg:waitress#main
Expand Down
45 changes: 40 additions & 5 deletions pyconca/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,18 +3,53 @@

from .models import DBSession

def _add_resource(config, name):
values = {'name': name}
view = 'pyconca.resources.user_view.%sView' % (name.capitalize())
template = 'pyconca:templates/%(name)s/%(name)s_' % (values)

config.add_route(name + '_index', '/%(name)s' % (values))
config.add_route(name + '_create', '/new/%(name)s' % (values))
config.add_route(name + '_show', '/%(name)s/{id}' % (values))
config.add_route(name + '_delete', '/delete/%(name)s/{id}' % (values))
config.add_route(name + '_update', '/edit/%(name)s/{id}' % (values))

config.add_view(
view,
attr='index',
route_name=name + '_index',
renderer=template + 'index.pt')
config.add_view(
view,
attr='show',
route_name=name + '_show',
renderer=template + 'show.pt')
config.add_view(
view,
attr='create',
route_name=name + '_create',
renderer=template + 'edit.pt')
config.add_view(
view,
attr='update',
route_name=name + '_update',
renderer=template + 'edit.pt')
config.add_view(
view,
attr='delete',
route_name=name + '_delete')

def main(global_config, **settings):
""" This function returns a Pyramid WSGI application.
"""
engine = engine_from_config(settings, 'sqlalchemy.')
DBSession.configure(bind=engine)
config = Configurator(settings=settings)
config.add_static_view('static', 'static', cache_max_age=3600)

config.add_route('index', '/')
config.add_route('about', '/about')
config.add_route('jobs', '/jobs')
config.add_route('events', '/events')
config.add_route('sponsors', '/sponsors')

_add_resource(config, 'user')

config.scan()
return config.make_wsgi_app()

Empty file added pyconca/dao/__init__.py
Empty file.
25 changes: 25 additions & 0 deletions pyconca/dao/base_dao.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
from pyconca.models import DBSession

class BaseDao(object):

def __init__(self, model):
self.model = model

def get(self, id):
return self._query().filter_by(id=id).first()

def index(self):
return self._query().all()

def delete(self, instance):
DBSession.delete(instance)

def create(self):
return self.model()

def save(self, instance):
DBSession.add(instance)
DBSession.flush()

def _query(self):
return DBSession.query(self.model)
7 changes: 7 additions & 0 deletions pyconca/dao/user_dao.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
from pyconca.dao.base_dao import BaseDao
from pyconca.models import User

class UserDao(BaseDao):

def __init__(self):
BaseDao.__init__(self, User)
35 changes: 16 additions & 19 deletions pyconca/models.py
Original file line number Diff line number Diff line change
@@ -1,28 +1,25 @@
from sqlalchemy import (
Column,
Integer,
Text,
)

from sqlalchemy import Column
from sqlalchemy import Integer
from sqlalchemy import String
from sqlalchemy.ext.declarative import declarative_base

from sqlalchemy.orm import (
scoped_session,
sessionmaker,
)
from sqlalchemy.orm import scoped_session
from sqlalchemy.orm import sessionmaker

from zope.sqlalchemy import ZopeTransactionExtension

DBSession = scoped_session(sessionmaker(extension=ZopeTransactionExtension()))
Base = declarative_base()

class MyModel(Base):
__tablename__ = 'models'
id = Column(Integer, primary_key=True)
name = Column(Text, unique=True)
value = Column(Integer)
class User(Base):
__tablename__ = 'user'
__table_args__ = {
'mysql_engine': 'InnoDB',
'mysql_charset': 'utf8'
}

def __init__(self, name, value):
self.name = name
self.value = value
id = Column(Integer, primary_key=True)
username = Column(String(length=30), unique=True, nullable=False)
first_name = Column(String(length=100))
last_name = Column(String(length=100))
email = Column(String(length=100))

Empty file added pyconca/resources/__init__.py
Empty file.
88 changes: 88 additions & 0 deletions pyconca/resources/base_view.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,88 @@
from pyramid.httpexceptions import HTTPFound
from pyramid.renderers import get_renderer
from pyramid.url import route_url

import logging

log = logging.getLogger(__name__)

def site_layout():
renderer = get_renderer('pyconca:templates/layout.pt')
layout = renderer.implementation().macros['layout']
return layout

class BaseView(object):

def __init__(self, request):
self.request = request
self._configure()

def index(self):
response_ = self._build_response()
models = self.dao.index()
self._wrap_model_list(models)
response_[self.name + '_list'] = models
return response_

def show(self):
id = self.request.matchdict['id']
response_ = self._build_response()
model = self.dao.get(id)
self._wrap_model(model)
response_[self.name] = model
return response_

def delete(self):
id = self.request.matchdict['id']
model = self.dao.get(id)
if self.is_post:
self.dao.delete(model)
index_url = self._route_url('index')
return HTTPFound(location=index_url)

def update(self):
id = self.request.matchdict['id']
model = self.dao.get(id)
return self._save(model, is_create=False)

def create(self):
model = self.dao.create()
return self._save(model, is_create=True)

def _save(self, model, is_create):
if self.is_post:
self._populate(model, is_create)
self.dao.save(model)
show_url = self._route_url('show', id=model.id)
return HTTPFound(location=show_url)
response_ = self._build_response()
self._wrap_model(model, is_create)
response_[self.name] = model
return response_

def _wrap_model_list(self, models):
for model in models:
self._wrap_model(model)

def _wrap_model(self, model, is_create=False):
if is_create:
model.save_url = self._route_url('create')
else:
model.show_url = self._route_url('show', id=model.id)
model.update_url = self._route_url('update', id=model.id)
model.delete_url = self._route_url('delete', id=model.id)
model.save_url = model.update_url

def _build_response(self):
return {
'layout': site_layout(),
'index_url': self._route_url('index'),
'create_url': self._route_url('create'),
}

def _route_url(self, action, **kwargs):
return route_url(self.name + '_' + action, self.request, **kwargs)

@property
def is_post(self):
return self.request.environ['REQUEST_METHOD'] == 'POST'
14 changes: 14 additions & 0 deletions pyconca/resources/user_view.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
from pyconca.dao.user_dao import UserDao
from pyconca.resources.base_view import BaseView

class UserView(BaseView):

def _configure(self):
self.name = 'user'
self.dao = UserDao()

def _populate(self, user, is_create):
user.first_name = self.request.params['first_name']
user.last_name = self.request.params['last_name']
user.username = self.request.params['username']
user.email = self.request.params['email']
24 changes: 11 additions & 13 deletions pyconca/scripts/initializedb.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,23 +2,19 @@
import sys
import transaction

from sqlalchemy import engine_from_config
from pyramid.paster import get_appsettings
from pyramid.paster import setup_logging

from pyramid.paster import (
get_appsettings,
setup_logging,
)
from sqlalchemy import engine_from_config

from ..models import (
DBSession,
MyModel,
Base,
)
from ..models import Base
from ..models import DBSession
from ..models import User

def usage(argv):
cmd = os.path.basename(argv[0])
print('usage: %s <config_uri>\n'
'(example: "%s development.ini")' % (cmd, cmd))
'(example: "%s development.ini")' % (cmd, cmd))
sys.exit(1)

def main(argv=sys.argv):
Expand All @@ -31,5 +27,7 @@ def main(argv=sys.argv):
DBSession.configure(bind=engine)
Base.metadata.create_all(engine)
with transaction.manager:
model = MyModel(name='one', value=1)
DBSession.add(model)
taavi = User(username='taavi', first_name='Taavi', last_name='Burns')
diana = User(username='diana', first_name='Diana', last_name='Clarke')
DBSession.add(taavi)
DBSession.add(diana)
Empty file added pyconca/templates/__init__.py
Empty file.
Empty file.
52 changes: 52 additions & 0 deletions pyconca/templates/user/user_edit.pt
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
<div metal:use-macro="layout">
<div metal:fill-slot="content">

<div class="row-fluid">
<div class="span12">
<br>
<h1>
<a tal:attributes="href index_url">users</a> /
<span tal:condition="user.id" tal:replace="user.username">
<span tal:condition="not user.id">create</span>
</h1>
<hr>
<form class="form-horizontal" action="" method="">

<div class="control-group">
<label class="control-label" for="first_name">First Name</label>
<div class="controls">
<input type="text" maxlength="100" name="first_name" value="${user.first_name}">
</div>
</div>

<div class="control-group">
<label class="control-label" for="last_name">Last Name</label>
<div class="controls">
<input type="text" maxlength="100" name="last_name" value="${user.last_name}">
</div>
</div>

<div class="control-group">
<label class="control-label" for="username">Username</label>
<div class="controls">
<input type="text" maxlength="30" name="username" value="${user.username}">
</div>
</div>

<div class="control-group">
<label class="control-label" for="email">Email Address</label>
<div class="controls">
<input type="text" maxlength="100" name="email" value="${user.email}">
</div>
</div>

<input class="btn btn-primary" type="submit" value="Save"
onclick="this.form.action='${user.save_url}';this.form.method='POST';"/>
<input class="btn" type="submit" value="Cancel"
onclick="this.form.action='${index_url}';this.form.method='GET';"/>
</form>
</div>
</div>

</div><!-- content slot -->
</div><!-- layout template -->
49 changes: 49 additions & 0 deletions pyconca/templates/user/user_index.pt
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
<div metal:use-macro="layout">
<div metal:fill-slot="content">

<div class="row-fluid">
<div class="span9">
<br>
<h1>users</h1>
<br>
</div>
<div class="span3">
<br>
<form action="" method="">
<input class="btn btn-primary pull-right" type="submit" value="New User"
onclick="this.form.action='${create_url}';this.form.method='GET';"/>
</form>
</div>
<hr>
</div>

<div class="row-fluid">
<div class="span12">
<table class="table table-striped table-bordered">
<tr>
<th>Name</th>
<th>Username</th>
<th>Email</th>
</tr>
<div tal:repeat="user user_list">
<tr>
<td>
<a tal:attributes="href user.show_url">
<span tal:replace="user.first_name">
<span tal:replace="user.last_name">
</a>
</td>
<td>
<span tal:replace="user.username">
</td>
<td>
<span tal:replace="user.email">
</td>
</tr>
</div>
</table>
</div>
</div>

</div><!-- content slot -->
</div><!-- layout template -->
Loading

0 comments on commit 0cd0916

Please sign in to comment.