class BaseProjectContext(BaseContextMixin): __acl__ = [(Allow, Everyone, 'view'), (Allow, Authenticated, 'create')] __auth_template__ = "ufostart:templates/auth/login.html" canEdit = reify(canEdit) canApprove = reify(canApprove) @property def site_title(self): return [ self.displayName, self.company.display_name, self.request.globals.project_name ] @reify def company(self): return self.__parent__.company
class BaseContextMixin(object): __name__ = None __parent__ = None __auth_template__ = "ufostart:templates/auth/login.html" def __init__(self, parent, name): self.__parent__ = parent self.__name__ = name @property def settings(self): return self.__parent__.settings @property def request(self): return self.__parent__.request @property def user(self): return self.__parent__.user children = {} def __getitem__(self, item): return self.children[item](self, item) #=================================================== Hierarchy Helpers ============================================= @reify def __hierarchy__(self): result = [] p = self while p: result.append(p) p = p.__parent__ return result[::-1] def get_main_area(self): return self.__hierarchy__[1] if len(self.__hierarchy__)>1 else None main_area = reify(get_main_area) def get_area_url(self, *args, **kwargs): return self.request.resource_url(self.main_area, *args, **kwargs) def get_sub_area(self): return self.__hierarchy__[2] if len(self.__hierarchy__)>2 else None sub_area = reify(get_sub_area)
class BaseAdminContext(BaseContextMixin): app_label = 'admin' __acl__ = [(Allow, "AdminUser", ALL_PERMISSIONS), DENY_ALL] __auth_template__ = "ufostart:templates/auth/login.html" canEdit = reify(canEdit) user = reify(getUser) setUser = setUserF site_title = ['Admin Site'] workflow = None @reify def settings(self): return getattr(self.request.globals, self.app_label) @property def main_menu(self): return self.get_main_area().children.items()
def _set_property(request, name, callable, do_reify=False): func = lambda this: callable(this) func.__name__ = name if do_reify: func = reify(func) attrs = {name: func} parent = request.__class__ cls = type(parent.__name__, (parent, object), attrs) request.__class__ = cls
class BaseContext(object): children = {} workflow = None def __init__(self, parent, name): self.__name__ = name self.__parent__ = parent def __getitem__(self, item): return self.children[item](self, item) @reify def settings(self): return self.__parent__.settings @reify def request(self): return self.__parent__.request #=================================================== Hierarchy Helpers ============================================= @reify def __hierarchy__(self): result = [] p = self while p: result.append(p) p = p.__parent__ return result[::-1] def get_main_area(self): return self.__hierarchy__[1] if len(self.__hierarchy__) > 1 else None main_area = reify(get_main_area) def get_area_url(self, *args, **kwargs): return self.request.resource_url(self.main_area, *args, **kwargs) def get_sub_area(self): return self.__hierarchy__[2] if len(self.__hierarchy__) > 2 else None sub_area = reify(get_sub_area)
class SocialContext(BaseContextMixin): __acl__ = [(Allow, Everyone, 'view'), (Allow, Authenticated, 'proceed')] user = reify(getUser) setUser = setUserF @property def site_title(self): return [self.__name__.title(), self.request.globals.project_name] def __getitem__(self, item): if item in self.settings.networks: settings = self.settings.networks[item] return settings.module(self, item, settings) else: raise KeyError()
def model_property(sas, model_cls, **ancestors): """Return a property that checks ancestor IDs. If you are using SQLAlchemy, this function returns a model property that checks some ancestor ID(s) against its foreign key(s). Example usage:: class AddressResource(BaseResource): model = model_property(sas, Address, user=User) """ def wrapped(self): o = sas.query(model_cls).get(self.__name__) if o is None: raise HTTPNotFound() for key, cls in ancestors.items(): if not getattr(o, key) is ancestor_model(self, cls): raise HTTPNotFound() return o return reify(wrapped)
def model_property(sas, model_cls, **ancestors): '''If you are using SQLAlchemy, this function returns a model property that checks some ancestor ID(s) against its foreign key(s). Example usage:: class AddressResource(BaseResource): model = model_property(sas, Address, user=User) ''' def wrapped(self): o = sas.query(model_cls).get(self.__name__) if o is None: raise HTTPNotFound() for key, cls in ancestors: if not getattr(o, key) is ancestor_model(self, cls): raise HTTPNotFound() return o return reify(wrapped)
appstruct = self.finisher(appstruct) # if the finisher is a list, call each separate preparer elif is_nonstr_iter(self.finisher): for preparer in self.finisher: appstruct = preparer(self, appstruct) return appstruct my_deserialize.__name__ = 'deserialize' SchemaNode.deserialize = my_deserialize # Fix deform multiple form (on same page) fields errors def schemanode_oid(cls): return 'deformField-%s-%s' % (cls.name, cls._order) schemanode_oid.__name__ = 'oid' _SchemaNode.oid = reify(schemanode_oid) _original_SchemaMeta__init__ = _SchemaMeta.__init__ def _order_schemaMeta_nodes(cls, name, bases, clsattrs): _original_SchemaMeta__init__(cls, name, bases, clsattrs) if cls.__all_schema_nodes__: cls.__all_schema_nodes__.sort(key=lambda n: n._order) _order_schemaMeta_nodes.__name__ = '__init__' _SchemaMeta.__init__ = _order_schemaMeta_nodes # Propose this! def sequence_impl(self, node, value, callback, accept_scalar): if accept_scalar is None: accept_scalar = self.accept_scalar
def _makeOne(self, wrapped): from pyramid.decorator import reify return reify(wrapped)
class WebsiteRootContext(RootContext): __name__ = None __parent__ = None __acl__ = [(Allow, Everyone, 'view'), (Allow, Authenticated, 'apply'), (Allow, Authenticated, 'join')] @property def site_title(self): return [self.request.globals.project_name] app_label = 'website' user = reify(getUser) setUser = setUserF def logout(self): if USER_TOKEN in self.request.session: del self.request.session[USER_TOKEN] self.user = AnonUser() @reify def location(self): cache = self.request.globals.cache ip = self.request.client_addr location = cache.get('HOSTIP_{}'.format(ip)) if not location: try: response = urllib.urlopen( 'http://api.hostip.info/get_json.php?ip={}&position=true'. format(ip)).read() result = simplejson.loads(response) location = '{city}, {country_name}'.format(**result) cache.set('HOSTIP_{}'.format(self.request.client_addr), location) except: pass return location children = ROOT_NAVIGATION def __getitem__(self, item): if item in self.children: return self.children[item](self, item) elif item in self.settings.networks: settings = self.settings.networks[item] return settings.module(self, item, settings) else: ctxt_cls = getContextFromSlug( CheckSlugProc(self.request, {'slug': item})) return ctxt_cls(self, item) def admin_url(self, *args, **kwargs): return self.request.resource_url(self, 'admin', *args, **kwargs) def signup_url(self, *args, **kwargs): return self.request.resource_url(self, 'signup', *args, **kwargs) def logout_url(self, *args, **kwargs): return self.request.resource_url(self, 'logout', *args, **kwargs) def auth_url(self, network, furl=None): return self.request.resource_url( self, 'login', network, query=[('furl', self.request.url if furl is None else furl)]) @property def home_url(self): return self.request.resource_url(self) @property def template_select_url(self): return self.request.resource_url(self, 'template') def template_url(self, slug, *args, **kwargs): return self.request.resource_url(self, 'template', slug, *args, **kwargs) def profile_url(self, slug): return self.request.resource_url(self, slug) def company_url(self, slug, *args, **kwargs): return self.request.resource_url(self, slug, *args, **kwargs) def round_url(self, slug, round_no='1', *args, **kwargs): return self.request.resource_url(self, slug, round_no, *args, **kwargs) def need_url(self, company_slug, need_slug, *args, **kwargs): return self.request.resource_url(self, company_slug, 1, need_slug, *args, **kwargs) def product_url(self, slug, *args, **kwargs): return self.request.resource_url(self, slug, 1, 'product', *args, **kwargs) @property def angellist_url(self): return self.request.resource_url(self, 'angellist', query=[('furl', self.request.url)])
class FunctionalTests(unittest.TestCase): testdir = here / 'test-indexes' dummy = here / "dummypackage/dist/dummypackage-0.0dev.tar.gz" counter = count() index_parent = here / "test-indexes" pipcache = here / "pipcache" devini = here / 'development.ini' dummy = here / "dummypackage/dist/dummypackage-0.0dev.tar.gz" @classmethod def get_base(cls): return path(resource_spec(cls.index_parent)) base = reify(lambda self: self.get_base()) def setUp(self): self.count = next(self.counter) self.dummy.copy(self.testdir) self.dummypath = self.testdir / self.dummy.name def makeone(self, xtra=None, index_name='test-func-index', count=None): from cheeseprism.wsgiapp import main cp = ConfigParser(dict(here=self.base)) with open(resource_spec(self.devini)) as fp: cp.readfp(fp) defaults = dict((x, cp.get('DEFAULT', x)) for x in cp.defaults()) count = count is None and self.count or count self.idxpath = index_path = self.base / ("%s-%s" % (count, index_name)) settings = { 'cheeseprism.file_root': index_path, 'cheeseprism.data_json': 'data.json' } settings = xtra and dict(settings, **xtra) or settings app = main(defaults, **settings) self.executor = app.registry['cp.executor'] from webtest import TestApp return TestApp(app) def test_async_bulkupdate(self): idxname = 'async_bulk_up' idxpath = self.base / "0-" + idxname idxpath.mkdir_p() self.dummy.copy(idxpath) with patch('cheeseprism.index.async_bulk_update_at_start') as abuaas: testapp = self.makeone({'cheeseprism.async_restart': 'true'}, index_name=idxname, count=0) assert abuaas.called res = testapp.get('/index', status=200) assert res def test_root_thead_pip_sync(self): with patch.dict('os.environ', {'PIP_DOWNLOAD_CACHE': resource_spec(self.pipcache)}): testapp = self.makeone({ 'cheeseprism.futures': 'thread', 'cheeseprism.pipcache_mirror': 'true' }) res = testapp.get('/index', status=200) assert 'WUT' in res.body def test_root_thread(self): testapp = self.makeone() res = testapp.get('/', status=200) self.failUnless('Cheese' in res.body) def test_request_size_limit(self): testapp = self.makeone({ 'cheeseprism.temp_file_limit': 100 * 1024, 'pyramid.includes': __name__ + '.request_size_check' }) res = testapp.get('/sizetest', status=200) assert res.json.get('request_size', False) == 102400 def tearDown(self): logger.debug("teardown: %s", self.count) if self.base.exists(): dirs = self.base.dirs() logger.debug(pprint(dirs)) time.sleep(0.02) logger.debug(pprint([x.rmtree() for x in dirs])) if hasattr(self, 'executor'): self.executor.shutdown()