def view_query(request): conn = get_connection(request) root = conn.root() schema = Store_Number() myform = Form(schema, buttons=('submit',)) if 'submit' in request.POST: controls = request.POST.items() try: appstruct = myform.validate(controls) except ValidationFailure, e: return { 'project': 'Network Deployment Automation System', 'page': root['app_root'], 'form': e.render(), 'values': False, } values = { 'store_number': appstruct['store_number'], } return { 'project': 'Network Deployment Automation System', 'page': root['app_root'], 'form': myform.render(), 'values': values }
def __init__(self, context, request=None): """Initialize application for each request """ # Support initialization as a view class instance if issubclass(context.__class__, self.__class__): self.__dict__.update(context.__dict__) return # Continue initialization as a root object instance self.data = request # 'request' is either None or a mockup db like {} self.request = context # 'context' is the request for root_factory # Get database root from ZODB when no mockup db was given if self.data is None: self.data = get_connection(self.request).root() # Prepare database if not hasattr(self.data, "players"): self.data.players = Players() if not hasattr(self.data, "catalog"): self.data.catalog = Catalog() self.data.catalog["type"] = FieldIndex() self.data.catalog["size"] = FieldIndex() self.data.catalog["created"] = FieldIndex() self.data.catalog["player_id"] = FieldIndex() self.data.catalog["keywords"] = KeywordIndex() # Migrate data over possible schema changes migrate(self.data) # Set registered games (available games could be filtered here) self.games = dict(self.request.registry.getAdapters((self,), IGame))
def evolve_root_factory(request_or_connection): if isinstance(request_or_connection, (Request, DummyRequest)): conn = get_connection(request_or_connection) else: conn = request_or_connection zodb_root = conn.root() return zodb_root['repoze.evolution']
def default_root_factory(request_or_connection): if isinstance(request_or_connection, (Request, DummyRequest)): conn = get_connection(request_or_connection) else: conn = request_or_connection zodb_root = conn.root() return zodb_root
def go(root, request, zodb_path, queue): runner = None transaction.manager.explicit = True root._p_jar.explicit_transactions = True transaction.begin() try: poconn = get_connection(request, 'postoffice') runner = MailinRunner2(root, poconn.root(), zodb_path, queue) runner() transaction.commit() p_jar = getattr(root, '_p_jar', None) if p_jar is not None: # Attempt to fix memory leak p_jar.db().cacheMinimize() except ConflictError: transaction.abort() log.info('ZODB conflict error: retrying later') except: transaction.abort() raise finally: transaction.manager.explicit = False
def add_apartment(request): ret = dict() places = Places(get_connection(request)) if len(request.json_body) != 4: ret['error_code'] = 1 ret['error_message'] = "JSON request is not correctly encoded" else: errors = list() rq_addr,rq_contact, rq_info, rq_apt = request.json_body rq_addr, err = _get_address(rq_addr) errors.append(err) rq_contact, err = _get_contact(rq_contact) errors.append(err) rq_info = _get_info(rq_info) if rq_addr and rq_contact and rq_info: rq_apt = _get_apartment(rq_apt, rq_addr, rq_contact, rq_info) else: rq_apt = None errors = [item for item in errors if item] if not errors and rq_apt: places.add_apartment(rq_apt) places.commit() ret['error_code'] = 0 ret['error_message'] = 'Apartment has been added' else: ret['error_code'] = 2 ret['error_message'] = ', '.join(errors) return ret
def list_apartment(request): places = Places(get_connection(request)) ret = list() for apartment in places.list_apartments(): data = { 'address': { 'city': apartment.address.city, 'street': apartment.address.street, 'housenumber': apartment.address.housenumber, }, 'contact': { 'phone': apartment.contact.phone, 'nickname': apartment.contact.nickname, 'email': apartment.contact.email, 'person_name': apartment.contact.person_name, }, 'info': { 'memo': apartment.info.memo, 'price': apartment.info.price, 'available_since': str(apartment.info.available_since), 'rooms': apartment.info.rooms, 'sqm': apartment.info.sqm, }, } ret.append(data) return ret
def groupfinder(userid, request): conn = get_connection(request) app_root = conn.root()['cintra_root'] userslogininfo = app_root['security']['userslogininfo'] if userid in userslogininfo: return app_root['security']['groupsinfo'].get(userid, [])
def evolve_root_factory(request_or_connection): if isinstance(request_or_connection, (Request, DummyRequest)): conn = get_connection(request_or_connection) else: conn = request_or_connection zodb_root = conn.root() return zodb_root["repoze.evolution"]
def db(self): from pyramid_zodbconn import get_connection conn = get_connection(self.request) db = conn.db() return db
def site_factory(request): """Application site factory On application startup, this factory checks configuration to get application name and load it from the ZODB; if the application can't be found, configuration is scanned to get application factory, create a new one and create a local site manager. """ conn = get_connection(request) root = conn.root() application_key = request.registry.settings.get(PYAMS_APPLICATION_SETTINGS_KEY, PYAMS_APPLICATION_DEFAULT_NAME) application = root.get(application_key) if application is None: factory = request.registry.settings.get(PYAMS_APPLICATION_FACTORY_KEY) if factory: resolver = DottedNameResolver() factory = resolver.maybe_resolve(factory) else: factory = request.registry.queryUtility(ISiteRootFactory, default=BaseSiteRoot) application = root[application_key] = factory() if IPossibleSite.providedBy(application): lsm = LocalSiteManager(application, default_folder=False) application.setSiteManager(lsm) try: # if some components require a valid and complete registry # with all registered utilities, they can subscribe to # INewLocalSiteCreatedEvent event interface set_local_registry(application.getSiteManager()) get_current_registry().notify(NewLocalSiteCreatedEvent(application)) finally: set_local_registry(None) import transaction # pylint: disable=import-outside-toplevel transaction.commit() return application
def root_factory(request, name='site'): def finished(request): # closing the primary also closes any secondaries opened now = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S") elapsed = time.time() - before if elapsed > connstats_threshhold: loads_after, stores_after = connection.getTransferCounts() loads = loads_after - loads_before stores = stores_after - stores_before with open(connstats_file, 'a', 0) as f: f.write('"%s", "%s", "%s", %f, %d, %d\n' % (now, request.method, request.path_url, elapsed, loads, stores, ) ) f.flush() if connstats_file is not None: request.add_finished_callback(finished) # NB: Finished callbacks are executed in the order they've been added # to the request. pyramid_zodbconn's ``get_connection`` registers a # finished callback which closes the ZODB database. Because the # finished callback it registers closes the database, we need it to # execute after the "finished" function above. As a result, the above # call to ``request.add_finished_callback`` *must* be executed before # we call ``get_connection`` below. # Rationale: we want the call to getTransferCounts() above to happen # before the ZODB database is closed, because closing the ZODB database # has the side effect of clearing the transfer counts (the ZODB # activity monitor clears the transfer counts when the database is # closed). Having the finished callbacks called in the "wrong" order # will result in the transfer counts being cleared before the above # "finished" function has a chance to read their per-request values, # and they will appear to always be zero. connection = get_connection(request) if connstats_file is not None: before = time.time() loads_before, stores_before = connection.getTransferCounts() folder = connection.root() if name not in folder: bootstrapper = queryUtility(IBootstrapper, default=populate) bootstrapper(folder, name, request) # Use pgtextindex if 'pgtextindex.dsn' in settings: site = folder.get(name) index = lookup(KarlPGTextIndex)(get_weighted_textrepr) site.catalog['texts'] = index transaction.commit() return folder[name]
def groupfinder(userid, request): conn = get_connection(request) app_root = conn.root()['cintra_root'] users = app_root['users'] if userid in users: user = users[userid] return user.group
def _to_python(self,value,state): context = get_connection(state.request).root()['app_root'] if value in context['users']: raise Invalid( 'That username already exists.', value, state ) return value
def pack(self): conn = get_connection(self.request) try: days = int(self.request.POST["days"]) except: self.request.session.flash("Invalid number of days", "error") conn.db().pack(days=days) self.request.session.flash("Database packed to %s days" % days) return HTTPFound(location=self.request.mgmt_path(self.context, "@@manage_db"))
def gallery_root_factory(request): conn = get_connection(request) if 'user' in request.matchdict: username = request.matchdicht['user'] bootstrap = False else: username = None bootstrap = True return retrieve_gallery(conn.root(), username, bootstrap=bootstrap)
def user_root_factory(request_or_connection): if isinstance(request_or_connection, (Request, DummyRequest)): conn = get_connection(request_or_connection) else: conn = request_or_connection zodb_root = conn.root() if not '{}_root'.format(APP_NAME) in zodb_root: return None return zodb_root[APP_ROOT_NAME]['user']
def root_factory(request_or_registry): if isinstance(request_or_registry, Request): conn = get_connection(request_or_registry) else: conn = get_static_connection(request_or_registry) request_or_registry._temp_zodb_connection = conn root = bootstrap(conn.root()) return root
def user_root_factory(request_or_connection): if isinstance(request_or_connection, (Request, DummyRequest)): conn = get_connection(request_or_connection) else: conn = request_or_connection zodb_root = conn.root() if not "{}_root".format(APP_NAME) in zodb_root: return None return zodb_root[APP_ROOT_NAME]["user"]
def root_factory(request): conn = pyramid_zodbconn.get_connection(request) database = conn.root() if 'root' not in database: root = Root() database['root'] = root import transaction transaction.commit() return database['root']
def root_factory(request): connection = get_connection(request) root = connection.root() if not 'site' in root: root['site'] = site = Site(u'Sure, Bro!', front_page) site.upload_image('image/gif', pkg_resources.resource_stream('surebro', 'static/pyramid-ufo.gif')) site['example_page'] = Page('Example Page', example_page) transaction.commit() return root['site']
def root_factory(request): connection = get_connection(request) root = connection.root() if not "site" in root: root["site"] = site = Site(u"Sure, Bro!", front_page) site.upload_image("image/gif", pkg_resources.resource_stream("surebro", "static/pyramid-ufo.gif")) site["example_page"] = Page("Example Page", example_page) site.catalog = make_catalog() index_doc(site) index_doc(site["example_page"]) transaction.commit() return root["site"]
def appmaker(config): """ Create the application. Call this method from your main Pyramid setup """ initreq = InitRequest() initreq.registry = config.registry conn = get_connection(initreq) zodb_root = conn.root() if not 'app_root' in zodb_root: root_clazz_name = config.registry.settings.get( "pycms.rootclass", "w20e.pycms.models.site.Site") root_title = config.registry.settings.get( "pycms.roottitle", "Yet another w20e.pycms app!") root_clazz = class_from_string(root_clazz_name) app_root = root_clazz("root") app_root.__data__['name'] = root_title app_root.__parent__ = app_root.__name__ = None setattr(app_root, 'pycms_version', version) zodb_root['app_root'] = app_root transaction.commit() # create a globale images folder app_root = zodb_root['app_root'] IMAGES_ID = 'images' if not IMAGES_ID in app_root: images = ImageFolder(IMAGES_ID) images.__data__['name'] = 'Images' app_root.add_content(images) transaction.commit() # Do necessary updates update(zodb_root['app_root']) initreq.registry.notify(AppRootReady(app_root, config.registry)) transaction.commit() return zodb_root['app_root']
def external_login_complete(request): profile = request.context.profile email = '' if 'verifiedEmail' in profile: email = profile['verifiedEmail'] if 'emails' in profile: emails = profile['emails'] email = emails[0]['value'] came_from = request.session.get('came_from', request.application_url) connection = get_connection(request) site_root = connection.root()['app_root'] principals = find_service(site_root, 'principals') users = principals['users'] user = [user for user in users.values() if user.email == email] if not user or not email: return external_login_denied(request) headers = remember(request, oid_of(user[0])) request.session.flash('Welcome!', 'success') return HTTPFound(location=came_from, headers=headers)
def _to_python(self,value,state): context = get_connection(state.request).root()['app_root'] try: email = state.request.context.email except AttributeError: #there is no context email = None if email != None and email == value: # if we're editing user, we should # let the email pass if it's the same # as user already had return email for user in context['users']: if context['users'][user].email == value: raise Invalid( 'That email already exists.', value, state ) return value
def go(root, request, zodb_path, queue): runner = None try: poconn = get_connection(request, 'postoffice') runner = MailinRunner2(root, poconn.root(), zodb_path, queue) runner() transaction.commit() p_jar = getattr(root, '_p_jar', None) if p_jar is not None: # Attempt to fix memory leak p_jar.db().cacheMinimize() except ConflictError: transaction.abort() log.info('ZODB conflict error: retrying later') except: transaction.abort() raise
def undo_one(request): needle = 'hash:' + request.params['hash'] undo = None conn = get_connection(request) db = conn.db() for record in db.undoInfo(): # by default, the last 20 transactions description = record['description'] if needle in description: undo = dict(record) undo['clean_description'] = description.replace(needle, '') break if undo is None: request.session.flash('Could not undo, sorry', 'error') else: try: db.undo(undo['id']) msg = 'Undone: %s' % undo['clean_description'] request.session.flash(msg, 'success') except ZODB.POSException.POSError: msg = 'Could not undo, sorry' request.session.flash(msg, 'error') return HTTPFound(request.referrer or request.mgmt_path(request.context))
def root_factory(cls, request, transaction=transaction, get_connection=get_connection): """ A classmethod which can be used as a Pyramid ``root_factory``. It accepts a request and returns an instance of Site.""" # this is a classmethod so that it works when Site is subclassed. conn = get_connection(request) zodb_root = conn.root() if not 'app_root' in zodb_root: settings = request.registry.settings password = settings.get( 'substanced.initial_password') if password is None: raise ConfigurationError( 'You must set a substanced.initial_password ' 'in your configuration file') username = settings.get( 'substanced.initial_login', 'admin') email = settings.get( 'substanced.initial_email', '*****@*****.**') app_root = cls(username, email, password) zodb_root['app_root'] = app_root transaction.commit() return zodb_root['app_root']
def root_factory(request): conn = get_connection(request) return conn.root()['app_root']
def _callFUT(self, request): from pyramid_zodbconn import get_connection return get_connection(request)
def root_factory(request): # pragma: no cover conn = get_connection(request) return appmaker(conn.root())
def root_factory(request): conn = get_connection(request) return bootstrap(conn.root())
def view(request): conn = get_connection(request) return 'bar'
def _get_zodb_root(request): connection = get_connection(request) zodb_root = connection.root() return zodb_root
def root_factory(request): """ Returns root object for each request. See pyramid docs. """ conn = get_connection(request) return appmaker(conn.root())
def _get_product_collection(context): conn = get_connection(context) root = conn.root() return root['app_root']['products']
def root_factory(request, name='site'): connstats_file = request.registry.settings.get('connection_stats_filename') connstats_threshhold = float( request.registry.settings.get('connection_stats_threshhold', 0)) def finished(request): # closing the primary also closes any secondaries opened now = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S") elapsed = time.time() - before if elapsed > connstats_threshhold: loads_after, stores_after = connection.getTransferCounts() loads = loads_after - loads_before stores = stores_after - stores_before with open(connstats_file, 'a', 0) as f: f.write('"%s", "%s", "%s", %f, %d, %d\n' % ( now, request.method, request.path_url, elapsed, loads, stores, )) f.flush() # NB: Finished callbacks are executed in the order they've been added # to the request. pyramid_zodbconn's ``get_connection`` registers a # finished callback which closes the ZODB database. Because the # finished callback it registers closes the database, we need it to # execute after the "finished" function above. As a result, the above # call to ``request.add_finished_callback`` *must* be executed before # we call ``get_connection`` below. # Rationale: we want the call to getTransferCounts() above to happen # before the ZODB database is closed, because closing the ZODB database # has the side effect of clearing the transfer counts (the ZODB # activity monitor clears the transfer counts when the database is # closed). Having the finished callbacks called in the "wrong" order # will result in the transfer counts being cleared before the above # "finished" function has a chance to read their per-request values, # and they will appear to always be zero. if connstats_file is not None: request.add_finished_callback(finished) connection = get_connection(request) if connstats_file is not None: before = time.time() loads_before, stores_before = connection.getTransferCounts() folder = connection.root() if name not in folder: from karl.bootstrap.bootstrap import populate # avoid circdep bootstrapper = queryUtility(IBootstrapper, default=populate) bootstrapper(folder, name, request) # Use pgtextindex if 'pgtextindex.dsn' in request.registry.settings: site = folder.get(name) index = lookup(KarlPGTextIndex)(get_weighted_textrepr, drop_and_create=True) site.catalog['texts'] = index transaction.commit() request.registry.notify(RootCreated(request, folder)) return folder[name]
def root_factory(request): conn = get_connection(request) return StorageManager(connection=conn)
def _callFUT(self, request, dbname=None): from pyramid_zodbconn import get_connection return get_connection(request, dbname=dbname)
def getAppRoot(request): dbRoot = get_connection(request).root() if not 'djoser' in dbRoot: dbRoot['djoser'] = AppRoot() transaction.commit() return dbRoot['djoser']
def root_factory(request): conn = get_connection(request) return appmaker(conn.root())
def root_factory(request): conn = get_connection(request) return bootstrap(conn.root(), ZODB_APP_ROOT_ID, request)
def _get_user_collection(context): conn = get_connection(context) root = conn.root() return root['app_root']['users']
def root_factory(request): """Get root of database.""" conn = get_connection(request) return appmaker(conn.root())
def __init__(self, request): conn = get_connection(request) request.db = conn.root() appmaker(conn.root())
def root_factory(request): """ Data-base root factory """ conn = get_connection(request) return appmaker(conn.root())