Create a gist now

Instantly share code, notes, and snippets.

@aodag /guestbook.py
Last active Dec 26, 2015

What would you like to do?
guestbook作ってみた!
# -*- coding: utf-8 -*-
import os
from datetime import datetime
from babel.dates import format_datetime
import sqlalchemy as sa
import sqlalchemy.orm as orm
from sqlalchemy.ext.declarative import declarative_base
from zope.sqlalchemy import ZopeTransactionExtension
from pyramid.config import Configurator
from pyramid.view import view_config
from pyramid.events import subscriber
from pyramid.httpexceptions import HTTPFound
from markupsafe import escape
here = os.path.dirname(__file__)
sa_url = 'sqlite:///%s/guestbook.dat' % here
engine = sa.create_engine(sa_url)
engine.echo = True
Base = declarative_base()
Session = orm.scoped_session(
orm.sessionmaker(extension=ZopeTransactionExtension()))
Session.configure(bind=engine)
class Greeting(Base):
"""投稿データのモデル
"""
__tablename__ = 'greetings'
query = Session.query_property()
id = sa.Column(sa.Integer, primary_key=True)
name = sa.Column(sa.Unicode(255))
comment = sa.Column(sa.UnicodeText)
create_at = sa.Column(sa.DateTime, default=datetime.now)
def create_table():
"""データベースファイルがなければデータベーステーブルを作成します
"""
Base.metadata.create_all(bind=Session.bind)
def save_data(name, comment):
"""投稿データを保存します
"""
return Greeting(name=name, comment=comment)
def load_data():
"""投稿されたデータを返します
"""
greeting_list = Greeting.query.order_by(Greeting.create_at.desc())
return greeting_list
@view_config(route_name='top', renderer='index.mako')
def index(request):
"""トップページ
テンプレートを使用してページを表示します
"""
greeting_list = load_data()
return dict(greeting_list=greeting_list)
@view_config(route_name='post', request_method="POST")
def post(request):
"""投稿用URL
"""
name = request.params['name']
comment = request.params['comment']
# データを保存します
greeting = save_data(name, comment)
Session.add(greeting)
return HTTPFound(location=request.route_url('top'))
def nl2br(s):
"""改行文字をbrタグに置き換える関数
"""
return unicode(escape(s)).replace('\n', '<br />')
@subscriber('pyramid.events.BeforeRender')
def register_globals(event):
event['nl2br'] = nl2br
event['format_datetime'] = format_datetime
settings = {
'pyramid.includes': [
'pyramid_tm',
'pyramid_mako',
],
'mako.directories': [
here,
],
}
def main():
config = Configurator(settings=settings)
config.add_route('top', '/')
config.add_route('post', '/post')
config.scan(".")
return config.make_wsgi_app()
if __name__ == '__main__':
create_table()
from waitress import serve
wsgiapp = main()
serve(wsgiapp, host='127.0.0.1', port=5000)
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-type" content="text/html; charset=utf-8" />
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css">
<title>ゲストブック</title>
</head>
<body>
<div id="main" class="container">
<h1>ゲストブック</h1>
<div id="form-area">
<p>書き込みをどうぞ。</p>
<form action="${request.route_url('post')}" method="post">
<table>
<tr>
<th>名前</th>
<td>
<input type="text" size="20" name="name" />
</td>
</tr>
<tr>
<th>コメント</th>
<td>
<textarea rows="5" cols="40" name="comment"></textarea>
</td>
</tr>
</table>
<p><button type="submit">送信</button></p>
</form>
</div>
<div id="entries-area">
<h2>これまでの書き込み</h2>
% for greeting in greeting_list:
<div class="entry">
<h3>${ greeting.name } さんの書き込み(${ format_datetime(greeting.create_at, format='full', locale='ja') }):</h3>
<p>${ nl2br(greeting.comment)|n }</p>
</div>
% endfor
</div>
</div>
</body>
</html>
Babel==1.3
Mako==0.9.0
MarkupSafe==0.18
PasteDeploy==1.5.0
SQLAlchemy==0.8.2
WebOb==1.2.3
pyramid==1.5a2
pyramid-mako==0.3.1
pyramid-tm==0.7
pytz==2013.7
repoze.lru==0.6
transaction==1.4.1
translationstring==1.1
venusian==1.0a8
waitress==0.8.7
zope.deprecation==4.0.2
zope.interface==4.0.5
zope.sqlalchemy==0.7.3
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment