def test_layout_preview(self): from ptah.manage.layout import layoutPreview class Context(object): """ """ __name__ = 'test' def View(context, request): request.response.text = text_('test body') return request.response self.init_ptah() self.config.add_view( name='', context=Context, wrapper=ptah.wrap_layout(), view=View,) self.config.ptah_layout( '', parent='page', context=Context, renderer='ptah.manage:tests/test_layout.pt') request = DummyRequest() res = layoutPreview(Context(), request).text self.assertIn('"python-module": "test_layout"', res) self.assertIn('"renderer": "ptah.manage:tests/test_layout.pt"', res)
def __call__(self): result = self.update() if result is None: result = {} if isinstance(result, Response): return result request = self.request result['view'] = self result['request'] = request request.wrapped_response = result request.wrapped_body = render( 'ptahcrowd:templates/forbidden.pt', result, request) name = ptah.wrap_layout('ptah-page') return render_view_to_response(self.__parent__, request, name)
from datetime import datetime from pyramid import security from pyramid.view import view_config from pyramid.httpexceptions import HTTPFound from ptah.password import PasswordSchema from ptah.events import ResetPasswordInitiatedEvent from ptah.events import PrincipalPasswordChangedEvent from ptahcrowd import const from ptahcrowd.settings import _ @view_config( route_name='ptah-resetpassword', wrapper=ptah.wrap_layout('ptah-page'), renderer='ptahcrowd:templates/resetpassword.pt') class ResetPassword(ptah.form.Form): fields = ptah.form.Fieldset( ptah.form.FieldFactory( 'text', 'login', title=const.LOGIN_TITLE, description=const.CASE_DESCR, missing='', default='')) def form_content(self): return {'login': self.request.params.get('login', '')}
roles.append([role.title, form.SimpleTerm(role.id, role.id, role.title)]) return form.SimpleVocabulary(*[term for _t, term in sorted(roles)]) def get_groups_vocabulary(context): groups = [] for grp in ptah.get_session().query(CrowdGroup).all(): groups.append((grp.title, form.SimpleTerm(grp.__uri__, grp.__uri__, grp.title))) groups.sort() return form.SimpleVocabulary(*[term for _t, term in sorted(groups)]) @view_config("create.html", context=CrowdModule, wrapper=ptah.wrap_layout()) class CreateUserForm(form.Form): csrf = True label = _("Create new user") fields = UserSchema @form.button(_("Back")) def back(self): return HTTPFound(location=".") @form.button(_("Create"), actype=form.AC_PRIMARY) def create(self): data, errors = self.extract() if errors:
import ptah from pyramid.view import view_config from pyramid.httpexceptions import HTTPFound @view_config( 'sharing.html', context=ptah.ILocalRolesAware, permission=ptah.cms.ShareContent, wrapper=ptah.wrap_layout(), renderer='templates/sharing.pt') class SharingForm(ptah.form.Form): csrf = True fields = ptah.form.Fieldset( ptah.form.FieldFactory( 'text', 'term', title='Search term', description='Searches users by login and email', missing='')) users = None bsize = 15 def form_content(self): return {'term': self.request.session.get('sharing-search-term', '')} def get_principal(self, id): return ptah.resolve(id)
class Folder1(object): def __getitem__(self, key): if key == 'content': content = Content1() content.__name__ = 'content' content.__parent__ = self return content raise KeyError(key) ################################## class Content1(object): pass @view_config(context=Content1, wrapper=ptah.wrap_layout(), renderer='__main__:templates/layoutexample.pt') def view(context, request): return {} @ptah.layout( 'workspace', Content1, parent='page', renderer='__main__:templates/layoutworkspace.pt') class WorkspaceLayout(ptah.View): """ same as PageLayout, it uses 'page' as parent layout """ ################################## class Folder2(object):
grp = ptah.get_settings(key, self.request.registry) if grp is not None and grp.__ttw__: return SettingsWrapper(grp, self) raise KeyError(key) class SettingsWrapper(object): def __init__(self, grp, mod): self.__name__ = grp.__name__ self.__parent__ = mod self.group = grp @view_config( context=SettingsModule, wrapper = ptah.wrap_layout(), renderer='ptah.manage:templates/settings.pt') class SettingsView(ptah.View): """ Settings manage module view """ grps = None def update(self): groups = ptah.get_cfg_storage(ID_SETTINGS_GROUP).items() data = [] for name, group in sorted(groups): if self.grps is not None and name not in self.grps: continue
def __getitem__(self, key): grp = ptah.get_settings(key, self.request.registry) if grp is not None and grp.__ttw__: return SettingsWrapper(grp, self) raise KeyError(key) class SettingsWrapper(object): def __init__(self, grp, mod): self.__name__ = grp.__name__ self.__parent__ = mod self.group = grp @view_config(context=SettingsModule, wrapper=ptah.wrap_layout(), renderer='ptah.manage:templates/settings.pt') class SettingsView(ptah.View): """ Settings manage module view """ def update(self): groups = ptah.get_cfg_storage(ID_SETTINGS_GROUP).items() data = [] for name, group in sorted(groups): title = group.__title__ or name description = group.__description__ schema = [] for field in group.__fields__.values(): schema.append(({ 'name': '{0}.{1}'.format(name, field.name),
# add ptah_ws.band=my band to .ini file, restart and render this view. @view_config('myview.html', context=SiteRoot, wrapper=ptah.layout()) def my_view(request): data = {'context' : request.root, 'happy' : settings.ptah_ws.happy, 'favband' : settings.ptah_ws.band, 'now' : datetime.now()} return str(data) @view_config( context=ptah.cms.Content, permission=ptah.cms.View, wrapper=ptah.wrap_layout(), renderer="ptah_ws:templates/contentview.pt") class DefaultContentView(ptah.form.DisplayForm): @property def fields(self): return self.context.__type__.fieldset def form_content(self): data = {} for name, field in self.context.__type__.fieldset.items(): data[name] = getattr(self.context, name, field.default) return data
self.__name__ = str(pid) self.__parent__ = parent self.pname = None self.pcolumn = None for cl in table.columns: if cl.primary_key: self.pname = cl.name self.pcolumn = cl self.data = Session.query(table).filter( self.pcolumn == pid).one() @view_config( context=SQLAModule, wrapper=ptah.wrap_layout(), renderer='ptah.manage:templates/sqla-index.pt') class MainView(ptah.View): __doc__ = "sqlalchemy tables listing page." def printTable(self, table): columns = [] for cl in table.columns: kwarg = [] if cl.key != cl.name: kwarg.append('key') # pragma: no cover if cl.primary_key: kwarg.append('primary_key') if not cl.nullable: kwarg.append('nullable')
form.TextField( 'login', title = _(u'Login Name'), description = _('Login names are case sensitive, '\ 'make sure the caps lock key is not enabled.'), default = u''), form.PasswordField( 'password', title = _(u'Password'), description = _('Case sensitive, make sure caps lock is not enabled.'), default = u'') ) @view_config(route_name='login', wrapper=ptah.wrap_layout('ploud-login')) class LoginForm(form.Form): fields = LoginSchema @form.button('Login', actype=form.AC_PRIMARY) def loginHandler(self): data, errors = self.extract() if errors: self.message(errors, 'form-error') return host = self.request.matchdict['site'] data = '%s::%s'%(data['login'], data['password']) tid = token.service.generate(TOKEN_TYPE, data)
""" login form """ import ptah from ptah import view, form from pyramid import security from pyramid.view import view_config from pyramid.httpexceptions import HTTPFound import ptahcrowd from ptahcrowd import const from ptahcrowd.settings import _, CFG_ID_CROWD @view_config( route_name='ptah-login', wrapper=ptah.wrap_layout('ptah-page'), renderer="ptahcrowd:templates/login.pt") class LoginForm(form.Form): """ Login form """ id = 'login-form' title = _('Login') fields = form.Fieldset( form.fields.TextField( 'login', title=const.LOGIN_TITLE, description=const.CASE_WARN, default=''), form.fields.PasswordField( 'password',
import ptah import ptahcms from pyramid.view import view_config class SiteRoot(ptahcms.ApplicationRoot): """ Application model which subclasses ptahcms.ApplicationRoot """ __type__ = ptahcms.Type( 'ptah_minicms-app', title='CMS Site Root', description='A root for the ptah_minicms Application') APP_FACTORY = ptahcms.ApplicationFactory( SiteRoot, '/', name='root', title='Ptah mini cms') @view_config(context=SiteRoot, wrapper=ptah.wrap_layout(), renderer='ptah_minicms:templates/homepage.pt') class RootView(ptah.View): def __call__(self): return {'user': ptah.auth_service.get_current_principal()}
""" Source code view """ import os.path import pkg_resources from pyramid.view import view_config from pyramid.httpexceptions import HTTPFound import ptah from ptah import view from ptah.manage.manage import PtahManageRoute @view_config( 'source.html', context=PtahManageRoute, wrapper=ptah.wrap_layout(), renderer='ptah.manage:templates/source.pt') class SourceView(ptah.View): __doc__ = 'Source introspection page.' source = None format = None def update(self): name = self.request.params.get('pkg') if name is None: return HTTPFound(location='.') dist = None pkg_name = name while 1: try: dist = pkg_resources.get_distribution(pkg_name)
from pyramid import security from pyramid.view import view_config from pyramid.httpexceptions import HTTPFound from pyramid.security import authenticated_userid import ptah from ptah import form @view_config(route_name='login', renderer='ptah_simpleauth:templates/login.pt', wrapper=ptah.wrap_layout()) def login_form(request): login_form = form.Form(None, request) login_form.title = 'Login' login_form.fields = form.Fieldset( form.TextField( 'login', title = u'Login Name', description = 'Login names are case sensitive, '\ 'make sure the caps lock key is not enabled.', default = u''), form.PasswordField( 'password', title = u'Password', description = 'Case sensitive, make sure caps '\ 'lock is not enabled.', default = u''), ) def loginAction(form):
title = 'Ploud errors' def __getitem__(self, key): try: eid = int(key) except: raise KeyError(key) error = ptah.get_session().query(Error).filter_by(id=eid).first() error.__parent__ = self error.__name__ = key return error @view_config( context=PloudErrors, wrapper=ptah.wrap_layout(), renderer='ploud.frontend:newui/errorsmod.pt') class ErrorsModuleView(ptah.View): def update(self): count = ptah.get_session().query(models.Error).count() self.errors = ptah.get_session().query(Error)\ .order_by(Error.time.desc()).slice(0,50) @view_config( context=Error, wrapper=ptah.wrap_layout(), renderer='ploud.frontend:newui/error.pt') class ErrorView(form.Form): def fixed(self):
def __init__(self, pid, tinfo, parent, request): self.__name__ = str(pid) self.__parent__ = parent self.pid = pid self.tinfo = tinfo self.cls = tinfo.cls self.request = request self.record = cms.Session.query(tinfo.cls)\ .filter(tinfo.cls.__id__ == pid).one() @view_config( context=ModelModule, wrapper=ptah.wrap_layout(), renderer='ptah.manage:templates/models.pt') class ModelModuleView(ptah.View): rst_to_html = staticmethod(ptah.rst_to_html) def update(self): cfg = ptah.get_settings(ptah.CFG_ID_PTAH, self.request.registry) types = [] for ti in cms.get_types().values(): if ti.__uri__ in cfg['disable_models']: continue types.append((ti.title, ti))
class Telephone(form.Regex): """ An example validator. See ptah.form.validators for more info.""" def __init__(self, msg=None): log.info('Constructing a Telephone field validator') if msg is None: msg = "Invalid telephone number" super(Telephone, self).__init__( u'^\(?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$', msg=msg) # This is a "class view", you do not need to use a class for your # view. You can use a Function view as provided below. @view_config(renderer='rackptahbles:templates/homepage.pt', wrapper=ptah.wrap_layout(), route_name='root') class HomepageView(object): """ Homepage view """ def __init__(self, request): self.request = request def __call__(self): return {'user': ptah.resolve(authenticated_userid(self.request))} # This is a "function view", you do not need to use a function for your # view. You can use a Class view as provided above. @view_config(wrapper=ptah.wrap_layout(), route_name='contact-us')
raise KeyError(key) class Introspector(object): def __init__(self, name, mod, request): self.__name__ = name self.__parent__ = mod self.name = name self.request = request @view_config( context=IntrospectModule, wrapper=ptah.wrap_layout(), renderer='ptah.manage:templates/introspect.pt') class MainView(ptah.View): __doc__ = 'Introspection module view.' def update(self): self.manage_url = '{0}/introspect'.format(get_manage_url(self.request)) self.renderers = sorted( (self.request.registry.adapters.lookupAll( (IIntrospectable, Interface), ISnippet)), key = lambda item: item[1].view.title) @view_config( context=Introspector, wrapper=ptah.wrap_layout(),
blob = ptah.resolve(context.data) if not blob: return ' ' response = request.response response.content_type = blob.mimetype.encode('utf-8') if blob.filename: response.headerlist = { 'Content-Disposition': 'filename="%s"' % blob.filename.encode('utf-8') } response.body = blob.read() return response @view_config('uploadfile.html', context=Theme, wrapper=ptah.wrap_layout()) class AddThemeFileForm(ptah.cms.AddForm): tinfo = ThemeFile.__type__ name_show = False def chooseName(self, **kw): filename = kw['data']['filename'] name = filename.split('\\')[-1].split('/')[-1] i = 1 n = name while n in self.container: i += 1 n = u'%s-%s' % (name, i)
from ptah.form.field import FIELD_ID, PREVIEW_ID from pyramid.view import view_config @ptah.manage.module('fields') class FieldsModule(ptah.manage.PtahModule): __doc__ = ('A preview and listing of all form fields in the ' 'application. This is useful to see what fields are available. ' 'You may also interact with the field to see how it works in ' 'display mode.') title = 'Field types' @view_config( context=FieldsModule, wrapper=ptah.wrap_layout(), renderer='ptah.manage:templates/fields.pt') class FieldsView(ptah.View): """ Fields manage module view """ def update(self): data = [] fields = ptah.get_cfg_storage(FIELD_ID) previews = ptah.get_cfg_storage(PREVIEW_ID) for name, cls in fields.items(): data.append({'name': name, 'doc': cls.__doc__, 'preview': previews.get(cls)})
# logger, check Debug Toolbar logging section or stdout log = logging.getLogger(__name__) @ptah.layout(context=DefaultRootFactory, renderer='ptah_simpleauth:templates/layout.pt', use_global_views=True) class Layout(ptah.View): """ simple layout """ links = {'sqlalchemy':'http://www.sqlalchemy.org/', 'pyramid':'http://docs.pylonsproject.org/', 'enfoldsystems':'http://www.enfoldsystems.com/', 'bootstrap':'http://twitter.github.com/bootstrap/', 'chameleon':'http://chameleon.repoze.org/', 'sqlite':'http://www.sqlite.org/'} def update(self): self.user = ptah.auth_service.get_current_principal() self.isAnon = self.user is None self.manage_url = ptah.manage.get_manage_url(self.request) @view_config(renderer='ptah_simpleauth:templates/homepage.pt', wrapper=ptah.wrap_layout(), route_name='root') class HomepageView(object): """ Homepage view """ def __init__(self, request): self.request = request def __call__(self): return {'user': ptah.resolve(authenticated_userid(self.request))}
ptah.uiaction( ThemeGallery, 'private', 'Private themes', action='private.html', permission = permissions.ManageGallery) ptah.uiaction( ThemeGallery, 'mythemes', 'My themes', action='mythemes.html', permission = permissions.AddTheme) ptah.uiaction( ThemeGallery, 'upload-theme', 'Upload new', action='newtheme.html', permission = permissions.AddTheme) @view_config(context=ThemeGallery, permission=ptah.cms.View, wrapper=ptah.wrap_layout(), renderer='ploud.themegallery:templates/themegallery.pt') class GalleryView(ptah.View): """ Main gallery view """ themes_tmpl = 'ploud.themegallery:templates/listthemes.pt' status = 'public' page = ptah.Pagination(8, 3, 3) def render_tmpl(self, themes, url): return render(self.themes_tmpl, {'themes': themes, 'url': url}) def getCurrent(self): id = 'gallery-batch-%s'%self.status
request.request_iface = request.registry.getUtility( IRouteRequest, name=MANAGE_APP_ROUTE) request.app_factory = factory app = factory() app.__parent__ = self app.__root_path__ = '/ptah-manage/apps/%s/'%app.__name__ return app raise KeyError(key) def available(self): return bool(cms.get_app_factories()) @view_config( context=ApplicationsModule, wrapper=ptah.wrap_layout(), renderer='ptah.manage:templates/apps.pt') class ApplicationsModuleView(ptah.View): """ Applications module default view """ def update(self): factories = [] for factory in cms.get_app_factories().values(): factories.append((factory.title, factory)) self.factories = [f for _t, f in sorted(factories)] @ptah.layout( 'ptah-manage', manage.PtahManageRoute,
from pyramid import security from pyramid.view import view_config from pyramid.httpexceptions import HTTPFound from pyramid.security import authenticated_userid import ptah from ptah import form @view_config(route_name="login", renderer="rackptahbles:templates/login.pt", wrapper=ptah.wrap_layout()) def login_form(request): login_form = form.Form(None, request) login_form.title = "Login" login_form.fields = form.Fieldset( form.TextField( "login", title=u"Login Name", description="Login names are case sensitive, " "make sure the caps lock key is not enabled.", default=u"", ), form.PasswordField( "password", title=u"Password", description="Case sensitive, make sure caps " "lock is not enabled.", default=u"", ), ) def loginAction(form): request = form.request
def update(self): self.user = ptah.resolve(self.context.userid) self.manage_url = get_manage_url(self.request) mod = self.request.context while not isinstance(mod, PtahModule): mod = getattr(mod, '__parent__', None) if mod is None: # pragma: no cover break self.module = mod @view_config( context=PtahManageRoute, wrapper = ptah.wrap_layout(), renderer = 'ptah.manage:templates/manage.pt') class ManageView(ptah.View): """List ptah modules""" rst_to_html = staticmethod(ptah.rst_to_html) def update(self): context = self.context request = self.request self.cfg = ptah.get_settings(ptah.CFG_ID_PTAH, request.registry) mods = [] for name, mod in ptah.get_cfg_storage(MANAGE_ID).items(): if name in self.cfg['disable_modules']:
import sqlalchemy as sqla from pyramid.view import view_config from pyramid.httpexceptions import HTTPFound import ptah import ptahcrowd from ptah import form from ptahcrowd.settings import _ from ptahcrowd.module import CrowdModule from ptahcrowd.provider import CrowdUser, CrowdGroup from ptahcrowd.providers import Storage @view_config(context=CrowdModule, wrapper=ptah.wrap_layout(), renderer="ptahcrowd:templates/users.pt") class CrowdModuleView(form.Form): __doc__ = "List/search users view" csrf = True fields = form.Fieldset( form.TextField( "term", title=_("Search term"), description=_("Ptah searches users by login and email"), missing="", default="", ) ) users = None external = {} pages = ()
""" membership """ import ptah from pyramid.view import view_config from pyramid.security import authenticated_userid from models import User @view_config( route_name='frontend-membership', wrapper=ptah.wrap_layout('page-frontend'), renderer='ploud.frontend:newui/membership.pt') class MembershipView(ptah.View): policy = 0 def update(self): uri = authenticated_userid(self.request) user = User.getByURI(uri) if user is not None: info = {'email': user.email, 'policy': getattr(user, 'type', 0)} self.policy = info['policy'] else: info = {'email': 'anonymous subscription', 'policy': 98} self.user = user self.isAnon = user is None return info
condition=lambda content, request: content.status != 'public') ptah.uiaction(Theme, 'retract', 'Retract', action='retract.html', permission=permissions.RetractTheme) ptah.uiaction(Theme, 'upload', 'Upload file', action='uploadfile.html', permission=permissions.AddThemeFile) @view_config('newtheme.html', context=ThemeGallery, wrapper=ptah.wrap_layout()) class AddThemeForm(ptah.cms.AddForm): tinfo = Theme.__type__ fields = form.Fieldset( ThemeSchema, form.Fieldset(ThemeFileSchema, name='theme-file', legend='Theme file')) def create(self, **data): theme = super(AddThemeForm, self).create(**data) # create theme file filedata = data.pop('theme-file') themefile = ptah.cms.wrap(theme).create( ThemeFile.__type__.__uri__, 'themfile-%s' % filedata['version'], **filedata)
renderer='ptah_simpleauth:templates/layout.pt', use_global_views=True) class Layout(ptah.View): """ simple layout """ links = { 'sqlalchemy': 'http://www.sqlalchemy.org/', 'pyramid': 'http://docs.pylonsproject.org/', 'enfoldsystems': 'http://www.enfoldsystems.com/', 'bootstrap': 'http://twitter.github.com/bootstrap/', 'chameleon': 'http://chameleon.repoze.org/', 'sqlite': 'http://www.sqlite.org/' } def update(self): self.user = ptah.auth_service.get_current_principal() self.isAnon = self.user is None self.manage_url = ptah.manage.get_manage_url(self.request) @view_config(renderer='ptah_simpleauth:templates/homepage.pt', wrapper=ptah.wrap_layout(), route_name='root') class HomepageView(object): """ Homepage view """ def __init__(self, request): self.request = request def __call__(self): return {'user': ptah.resolve(authenticated_userid(self.request))}
""" security ptah module """ import ptah from ptah.manage import get_manage_url from pyramid.view import view_config @ptah.manage.module('permissions') class PermissionsModule(ptah.manage.PtahModule): __doc__ = 'A listing of all permission sets and their definitions' title = 'Permissions' @view_config( context=PermissionsModule, wrapper=ptah.wrap_layout(), renderer='ptah.manage:templates/permissions.pt') class PermissionsView(ptah.View): """ Permissions module default view """ def update(self): self.manage = get_manage_url(self.request) self.permissions = sorted(ptah.get_permissions().values(), key = lambda p: p.title) acls = ptah.get_acls() self.acls = sorted([acl for acl in acls.values() if acl.id != ''], key = lambda a: a.title) self.acls.insert(0, ptah.DEFAULT_ACL) @view_config(