Skip to content

Instantly share code, notes, and snippets.

@aodag
Created August 1, 2015 09:41
Show Gist options
  • Save aodag/9bccb58224e6f1914ddb to your computer and use it in GitHub Desktop.
Save aodag/9bccb58224e6f1914ddb to your computer and use it in GitHub Desktop.
import os
import logging
import deform
import pkg_resources
import whitenoise
from webob.exc import (
HTTPFound,
HTTPNotFound,
)
from colanderalchemy import SQLAlchemySchemaNode
from datetime import datetime
from repoze.tm import TM
from sqlalchemy import (
engine_from_config,
Column,
Date,
DateTime,
Integer,
UnicodeText,
)
from sqlalchemy.orm import (
scoped_session,
sessionmaker,
)
from sqlalchemy.ext.declarative import declarative_base
import zope.sqlalchemy
from webob.dec import wsgify
from webdispatch.urldispatcher import URLDispatcher
from jinja2 import (
Environment,
FileSystemLoader,
)
logging.basicConfig(level=logging.DEBUG)
here = os.path.dirname(__file__)
templates = Environment(
loader=FileSystemLoader([os.path.join(here, 'templates')]),
)
Session = scoped_session(sessionmaker())
zope.sqlalchemy.register(Session)
Base = declarative_base()
class Person(Base):
__tablename__ = 'people'
query = Session.query_property()
id = Column(Integer, primary_key=True)
first_name = Column(UnicodeText,
nullable=False)
last_name = Column(UnicodeText,
nullable=False)
birthday = Column(Date,
nullable=False)
created = Column(DateTime,
default=datetime.now)
edited = Column(DateTime,
default=datetime.now,
onupdate=datetime.now)
@property
def fullname(self):
return "{self.first_name} {self.last_name}".format(self=self)
def static_url(s):
return s.replace("deform:static", "/deform-static")
@wsgify
def index(request):
tmpl = templates.get_template('index.html')
people = Person.query.all()
url = request.environ['webdispatch.urlgenerator']
return tmpl.render(people=people,
url=url,
static_url=static_url)
schema = SQLAlchemySchemaNode(Person,
excludes=['id', 'created', 'edited'])
@wsgify
def new_person_form(request):
form = deform.Form(schema,
buttons=('add',),
)
resources = form.get_widget_resources()
if request.method == 'POST':
ctrl = request.POST.items()
try:
params = form.validate(ctrl)
person = Person(**params)
Session.add(person)
logging.info('created person %s', person)
return HTTPFound(location="/")
except deform.ValidationFailure as e:
form = e
tmpl = templates.get_template('form.html')
return tmpl.render(form=form,
static_url=static_url,
widget_resources=resources)
@wsgify
def edit_person_form(request):
person_id = request.urlvars['person_id']
person = Person.query.filter(Person.id == person_id).first()
if person is None:
return HTTPNotFound()
appstruct = vars(person)
form = deform.Form(schema,
buttons=('update',),
)
resources = form.get_widget_resources()
if request.method == 'POST':
ctrl = request.POST.items()
try:
params = form.validate(ctrl)
for k, v in params.items():
setattr(person, k, v)
logging.info('edited person %s', person)
return HTTPFound(location="/")
except deform.ValidationFailure as e:
form = e
appstruct = None
tmpl = templates.get_template('form.html')
return tmpl.render(form=form,
appstruct=appstruct,
static_url=static_url,
widget_resources=resources)
def make_app(global_conf, **app_conf):
engine = engine_from_config(app_conf)
Session.remove()
Session.configure(bind=engine)
Base.metadata.create_all(bind=engine)
deform_static = pkg_resources.resource_filename('deform', 'static')
app = URLDispatcher()
app.add_url("top", "/", index)
app.add_url("new_person_form", "/new", new_person_form)
app.add_url("edit_person_form", "/{person_id}/edit", edit_person_form)
app = whitenoise.WhiteNoise(app)
app.add_files(deform_static,
prefix='deform-static')
app = TM(app)
return app
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="{{ static_url('deform:static/css/bootstrap.min.css') }}">
{% if widget_resources %}
{% for css in widget_resources['css'] %}
<link rel="stylesheet" href="{{ static_url(css) }}">
{% endfor %}
{% endif %}
<script src="{{ static_url('deform:static/scripts/bootstramp.min.js') }}"></script>
<script src="{{ static_url('deform:static/scripts/jquery-2.0.3.min.js') }}"></script>
{% if widget_resources %}
{% for js in widget_resources['js'] %}
<script src="{{ static_url(js) }}"></script>
{% endfor %}
{% endif %}
</head>
<body>
<div class="container">
{% block body %}
{% endblock %}
</div>
</body>
</html>
{% extends "base.html" %}
{% block body %}
{% if appstruct %}
{{ form.render(appstruct)|safe }}
{% else %}
{{ form.render()|safe }}
{% endif %}
{% endblock %}
{% extends "base.html" %}
{% block body %}
<table class="table">
<tr>
<th>#</th>
<th>Name</th>
<th>Birthday</th>
</tr>
{% for person in people %}
<tr>
<td>
<a href="{{ url.generate('edit_person_form', person_id=person.id) }}">
{{ person.id }}
</a>
</td>
<td>{{ person.fullname }}</td>
<td>{{ person.birthday }}</td>
</tr>
{% endfor %}
</table>
<a href="new" class="btn btn-primary">
<i class="glyphicon glyphicon-plus"></i>
</a>
{% endblock %}
Chameleon==2.22
colander==1.0
ColanderAlchemy==0.3.3
deform==2.0a2
iso8601==0.1.10
Jinja2==2.8
MarkupSafe==0.23
Paste==2.0.2
PasteDeploy==1.5.2
PasteScript==2.0.2
peppercorn==0.5
repoze.tm2==2.0
six==1.9.0
SQLAlchemy==1.0.8
transaction==1.4.4
translationstring==1.3
waitress==0.8.9
WebDispatch==1.3
WebOb==1.4.1
wheel==0.24.0
whitenoise==2.0.2
zope.deprecation==4.1.2
zope.interface==4.1.2
zope.sqlalchemy==0.7.6
@terapyon
Copy link

terapyon commented Aug 3, 2015

失礼しました。組み込み関数ですね。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment