$ sudo apt-get install python-setuptools $ sudo easy_install -U pyramid
sudo apt-get install python-virtualenv virtualenv --no-site-packages myenv cd myenv $ sudo easy_install -U pyramid
$ vim test/helloworld.py from pyramid.config import Configurator from pyramid.response import Response from paste.httpserver import serve def hello_world(request): return Response('Hello world!') def goodbye_world(request): return Response('Goodbye world!') if __name__ == '__main__': config = Configurator() config.add_view(hello_world) config.add_view(goodbye_world, name='goodbye') app = config.make_wsgi_app() serve(app, host='0.0.0.0')
$ python test/helloworld.py serving on 0.0.0.0:8080 view at http://127.0.0.1:8080 $ curl http://127.0.0.1:8080/ Hello world! $ curl http://127.0.0.1:8080/goodbye Goodbye world!
$ sudo apt-get install python-pymongo python-gridfs
vim development.ini [app:test] # mongodb settings ... db_uri = mongodb://localhost/ db_name = test
測試
from pyramid.config import Configurator from pyramid.events import subscriber from pyramid.events import NewRequest from gridfs import GridFS import pymongo def main(global_config, **settings): config = Configurator(settings=settings) db_uri = settings['db_uri'] conn = pymongo.Connection(db_uri) config.registry.settings['db_conn'] = conn config.add_subscriber(add_mongo_db, NewRequest) config.add_route('dashboard', '/') # other routes and more config... config.scan('myapp') return config.make_wsgi_app() def add_mongo_db(event): settings = event.request.registry.settings db = settings['db_conn'][settings['db_name']] event.request.db = db event.request.fs = GridFS(db)
@view_config(route_name='dashboard', renderer="myapp:templates/dashboard.pt") def dashboard(request): vendors = request.db['vendors'].find() return {'vendors':vendors}
$ paster create -t pyramid_starter test $ cd test $ sudo python setup.py develop $ paster serve development.ini
vim development.ini [app:test] # mongodb settings ... mongodb_uri = mongodb://localhost/ mongodb_name = test
vim test/resources.py from gridfs import GridFS import pymongo mongo_conn = pymongo.Connection() def add_mongo(event): req = event.request req.db = mongo_conn['test'] req.fs = GridFS(req.db) class Root(object): def __init__(self, request): self.request = request
$ vim test/__init__.py def main(...): ... config.add_subscriber('foo.resources.add_mongo', 'pyramid.events.NewRequest') ...
例 8.1. __init__.py
from pyramid.config import Configurator from test.resources import Root def main(global_config, **settings): """ This function returns a Pyramid WSGI application. """ config = Configurator(root_factory=Root, settings=settings) config.add_subscriber('test.resources.add_mongo','pyramid.events.NewRequest') config.add_view('test.views.my_view', context='test:resources.Root', renderer='test:templates/mytemplate.pt') config.add_static_view('static', 'test:static') return config.make_wsgi_app()