Roy Hyunjin Han
Create and Run Tools for Analyzing Open Data
Tips and tricks for building web apps
with this versatile framework
Roy Hyunjin Han
pip install -U pyramid
pcreate -s starter whee
cd whee
python setup.py develop
pserve development.ini # Note pyramid_debugtoolbar
vim whee/__init__.py
vim whee/views.py
# Check routes
proutes production.ini
# Check view corresponding to URL
pviews production.ini /
mkdir whee/views
touch whee/views/__init__.py
vim whee/views/yummies.py
@view_config(route_name='index', renderer='json')
def index(request):
return dict(count=279) # Great for testing!
vim whee/views/yummies.py
def includeme(config):
config.scan(__name__)
config.add_route('index', '/')
vim whee/__init__.py
def main(global_config, **settings):
config = Configurator(settings=settings)
config.include('whee.views.yummies')
vim whee/views.py
@view_config(route_name='home', renderer='templates/mytemplate.pt')
def my_view(request):
return {'project': 'whee'}
vim development.ini
[app:main]
mako.directories = whee:templates
vim whee/templates/index.mako
<!doctype html>
<html lang="en">
<button>${project.capitalize()}!</button>
</html>
vim whee/views.py
@view_config(route_name='home', renderer='index.mako')
def index(request):
return {'project': 'whee'}
vim whee/__init__.py
from pyramid.events import BeforeRender
from pyramid.security import authenticated_userid
def main(global_config, **settings):
def add_renderer_globals(event):
request = event['request']
userID = authenticated_userid(request)
event.update(dict(
USER_ID=userID))
config = Configurator(settings=settings)
config.add_subscriber(add_renderer_globals, BeforeRender)
pcreate -s alchemy arrr
cd arrr
python setup.py develop
vim arrr/models.py
vim arrr/scripts/initializedb.py
pcreate
pserve
pshell
proutes
pviews
pcreate -s alchemy arrr
cd arrr
vim arrr/scripts/initializedb.py
vim arrr/scripts/update.py
import sys
from argparse import ArgumentParser
from pyramid.paster import get_appsettings
from sqlalchemy import engine_from_config
from ..models import DBSession
def main(argv=sys.argv):
argumentParser = ArgumentParser()
argumentParser.add_argument('configURL')
arguments = argumentParser.parse_args(argv[1:])
# Load settings
settings = get_appsettings(arguments.configURL)
print settings
# Configure database
engine = engine_from_config(settings, 'sqlalchemy.')
DBSession.configure(bind=engine)
vim setup.py
entry_points="""\
[console_scripts]
update_arrr = arrr.scripts.update:main""",
python setup.py develop
update_arrr development.ini
import socket
import sys
SOCKET = socket.socket()
if __name__ == '__main__':
try:
SOCKET.bind(('', 5000))
except socket.error:
sys.exit(1)
import pudb; pudb.set_trace()
import ipdb; ipdb.set_trace()
import IPython; IPython.embed()
pshell development.ini
from pyramid.authentication import AuthTktAuthenticationPolicy
from pyramid.authorization import ACLAuthorizationPolicy
from pyramid.config import Configurator
from pyramid.security import Allow, Deny, Authenticated, ALL_PERMISSIONS
def main(global_config, **settings):
def get_groups(userID, request):
groups = []
if userID == 'Tigger':
groups.append('special')
return groups
authenticationPolicy = AuthTktAuthenticationPolicy(
secret=settings['authtkt.secret'],
callback=get_groups,
hashalg='sha512')
config = Configurator(
authentication_policy=authenticationPolicy,
authorization_policy=ACLAuthorizationPolicy(),
default_permission='outside',
root_factory='whee.RootFactory',
settings=settings)
return config.make_wsgi_app()
class RootFactory(object):
__acl__ = [
(Deny, 'outside', ALL_PERMISSIONS),
(Allow, Authenticated, 'yummy_see'),
(Allow, 'special', 'yummy_eat'),
]
def __init__(self, request):
pass
pip install -U velruse
from gevent import wsgi, monkey; monkey.patch_all()
from pyramid.paster import get_app
class Proxy(object):
def __init__(self, app):
self.app = app
def __call__(self, environ, start_response):
environ['wsgi.url_scheme'] = environ.get('HTTP_X_FORWARDED_PROTOCOL', 'http')
return self.app(environ, start_response)
if '__main__' == __name__:
app = get_app('production.ini')
wsgi.WSGIServer(('0.0.0.0',w8000), Proxy(app)).serve_forever()
from socketio.server import SocketIOServer
from pyramid.paster import get_app
from gevent import monkey; monkey.patch_all()
if __name__ == '__main__':
app = get_app('production.ini')
SocketIOServer(('0.0.0.0', 8000), app).serve_forever()
npm install -g http-proxy
var https = require('https'),
httpProxy = require('http-proxy'),
fs = require('fs');
httpProxy.createServer(8888, 'localhost', {
https: {
key: fs.readFileSync('proxy.key', 'utf8'),
cert: fs.readFileSync('proxy.pem', 'utf8')
},
target: {
https: true
}
}).listen(443);
<!--[if lt IE 9]>
<script src="//html5shim.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
pip install -U dogpile.cache
from dogpile.cache import make_region
region = make_region().configure('dogpile.cache.memory')
@region.cache_on_arguments()
def compute(x, y):
print '...',
return x + y
print compute(1, 2)
print compute(1, 2)
compute.invalidate(1, 2)
print compute(1, 2)
pip install -U gevent-socketio
By Roy Hyunjin Han