在Pyramid游戏
我在Pyramid教程中尝试了一下。
http://docs.pylonsproject.org/projects/pyramid_tutorials/en/latest/single_file_tasks/single_file_tasks.html
为了增加趣味性,我将数据库改成了Mongodb。
只要将模板和样式表文件按照教程放置,就可以正常运行。
# -*- coding: utf-8
from paste.httpserver import serve
from pyramid.configuration import Configurator
from pyramid.response import Response
from pyramid.events import subscriber, ApplicationCreated, NewRequest
from pyramid.session import UnencryptedCookieSessionFactoryConfig
from pyramid.exceptions import NotFound
from pyramid.httpexceptions import HTTPFound
from mongoengine import connect, Document, StringField, \
BooleanField
from pyramid.view import view_config
import os
MONGODB_SERVER_HOST = 'localhost'
MONGODB_SERVER_PORT = 27017
MONGODB_SERVER_DATABASE = 'db'
here = os.path.dirname(os.path.abspath(__file__))
#
# Models
#
class Task(Document):
name = StringField(required=True, max_length=100)
closed = BooleanField(required=True, default=False)
#
# Views
#
@view_config(route_name='list', renderer='list.mako')
def list_view(request):
tasks = Task.objects(closed__ne=True)
return {'tasks': tasks}
@view_config(route_name='new', renderer='new.mako')
def new_view(request):
if request.method == 'POST':
if request.POST.get('name'):
task = Task()
task.name = request.POST['name']
task.save()
request.session.flash('New task was successfully added!')
return HTTPFound(location=request.route_url('list'))
else:
request.session.flash('Please enter a name for the task!')
return {}
@view_config(route_name='close')
def close_view(request):
task_id = unicode(request.matchdict['id'])
Task.objects(id=task_id).update(set__closed=True)
request.session.flash('Task was successfully closed!')
return HTTPFound(location=request.route_url('list'))
@view_config(context='pyramid.exceptions.NotFound', renderer='notfound.mako')
def notfound_view(self):
return {}
@subscriber(ApplicationCreated)
def application_created_subscriber(event):
connect(MONGODB_SERVER_DATABASE, host=MONGODB_SERVER_HOST, port=MONGODB_SERVER_PORT)
if __name__ == '__main__':
settings = {
'reload_all': True,
'debug_all': True,
'mako.directories': os.path.join(here, 'templates'),
}
session_factory = UnencryptedCookieSessionFactoryConfig('itsaseekreet')
config = Configurator(settings=settings, session_factory=session_factory)
config.add_route('list', '/')
config.add_route('new', '/new')
config.add_route('close', '/close/{id}')
config.add_static_view('static', os.path.join(here, 'static'))
config.scan()
app = config.make_wsgi_app()
serve(app, host='0.0.0.0')