def __init__(self, request): session = request.db_session self._log = logging.getLogger("{}.{}".format(__name__, self.__class__.__name__)) self.hostname = request.host.split(":")[0] self.address = Setting.get(session, 'proxy_address').value self.port = Setting.get(session, 'proxy_port').value self.timeout = Setting.get(session, 'proxy_purge_timeout').value
def list(self): """ List settings in the database. Result set can be ordered and/or paginated. Result set is filtered by Setting.ui_administrable when debug is True. """ response = copy.deepcopy(self._response) try: start = self.request.params.get('start') start = None if start is None else int(start) limit = self.request.params.get('limit') limit = None if limit is None else int(limit) sort_by = self.request.params.get('sort', 'name') sort_order = self.request.params.get('dir', 'asc').lower() if sort_by == 'value': sort_by = 'raw_value' response['dataset_len'] = Setting.count(self.session, self.request.user) log.debug('Start: %s.', start) log.debug('Limit: %s.', limit) log.debug('Sort by: %s.', sort_by) log.debug('Sort order: %s.', sort_order) log.debug("Collection count: %s.", response['dataset_len']) response['dataset'] = [] for setting in Setting.list(self.session, limit=limit, start=start, sort_by=sort_by, sort_order=sort_order, user=self.request.user): response['dataset'].append(setting.to_dict()) log.debug("Dataset length: %s.", len(response['dataset'])) self.request.response.status = 200 response['success'] = True response['message'] = 'Dataset retrieved.' except ValueError as e: self.request.response.status = 400 response['success'] = False response['message'] = 'Invalid start and/or limit' log.exception(response['message']) except Exception as e: log.exception('Unable to query on settings collection.') self.request.response.status = 500 response['success'] = False response['message'] = str(e) return response
def test_get_all(self): self.add_ex_setting() settings = Setting.all(self.session) for setting in (self.max_pages, self.site_title): self.assertIn(setting, settings)
def info(self): """ Get details of setting 'name'. """ response = copy.deepcopy(self._response) try: setting = Setting.get(self.session, self.request.params.get('name')) except (NoResultFound, TypeError) as e: log.exception('No setting found.') self.session.rollback() response['dataset'] = [] response['dataset_len'] = 0 response['success'] = False response['message'] = str(e) self.request.response.status = 400 except Exception as e: log.exception('Unknown error.') self.session.rollback() response['dataset'] = [] response['dataset_len'] = 0 response['success'] = False response['message'] = str(e) self.request.response.status = 500 else: response['dataset'] = [setting.to_dict()] response['dataset_len'] = 1 response['success'] = True response['message'] = 'Setting retrieved successfully.' self.request.response.status = 200 return response
def test_type(self): with self.assertRaises(ValueError): Setting(name=u'testtest', value=u'abcdefg', type=SettingType(name=u'boolean', raw_type=u'bool')) s = Setting(name=u'testok', raw_value=1, type=SettingType(name=u'integer', raw_type=u'int')) self.assertEqual(s.value, 1) self.assertEqual(s.raw_value, "1") with self.assertRaises(ValueError): s.value = 'abcdef' s.value = 4 self.assertEqual(s.value, 4) self.assertEqual(s.raw_value, "4")
def __getattr__(self, attr_name): try: return self._settings[attr_name].value except KeyError: try: self._settings[attr_name] = Setting.get(self.session, attr_name) return self._settings[attr_name].value except NoResultFound: msg = "Setting '%s' doesn't exist!" % attr_name log.error(msg) raise AttributeError(msg)
def test_get(self): self.add_ex_setting() max_pages = Setting.get(self.session, 'max_pages') self.assertEqual(max_pages, self.max_pages)
def __new__(cls, request): if not Setting.get(request.db_session, 'proxy_enabled').value: return DummyProxy(request) return HttpCachePurgerProxy(request)
def update(self): response = copy.deepcopy(self._response) response.pop('dataset') response.pop('dataset_len') response.pop('metaData') response.pop('message') response['errors'] = {} try: setting = json.loads(self.request.params['dataset']) except KeyError as e: log.exception('Unable to load JSON request.') setting = dict(name=self.request.params.get('name'), value=self.request.params.get('value')) except (TypeError, ValueError) as e: self.session.rollback() log.exception('Bad request.') response['success'] = False response['errors']['exception'] = e self.request.response.status = 400 try: value = setting['value'] setting = Setting.get(self.session, setting['name']) if setting.type.raw_type == 'bool' and value == 'on': value = 'True' elif setting.type.raw_type == 'bool': value = 'False' elif setting.type.raw_type == 'html': # add smartquotes to prevent bsoup from translating smart-quotes # and other windows-specific characters soup = BeautifulSoup(value, smartQuotesTo=None) soup = remove_target_attributes(soup) value = unicode(soup) setting.value = value self.session.flush() self.proxy.invalidate(pages=True) except (NoResultFound, TypeError) as e: log.exception('No setting found.') self.session.rollback() response['success'] = False response['errors']['exception'] = str(e) self.request.response.status = 400 except Exception as e: log.exception('Cannot update the setting') self.session.rollback() response['success'] = False response['errors']['exception'] = str(e) self.request.response.status = 500 else: response['success'] = True self.request.response.status = 200 self.session.commit() return response
def _populate_database(self, manager_session): session = self.create_database_session() try: init_core_session_events(session) source_ = pkg_resources.resource_stream('aybu.core.data', 'default_data.json') data = json.loads(source_.read()) self.log.debug("Calling add_default_data") aybu.core.models.add_default_data(session, data) # modify settings for instance: debug and proxy support AybuCoreSetting.get(session, 'debug').raw_value = 'False' AybuCoreSetting.get(session, 'proxy_enabled').raw_value = \ self.environment.settings['proxy.enabled'] AybuCoreSetting.get(session, 'proxy_port').raw_value = \ self.environment.settings['proxy.port'] AybuCoreSetting.get(session, 'proxy_address').raw_value = \ self.environment.settings['proxy.address'] # setup theme in aybu instance if self.theme: self.log.info("Using theme %s for instance", self.theme.name) for setting_name in ('banner_width', 'banner_height', 'logo_width', 'logo_height', 'main_menu_levels', 'template_levels', 'image_full_size'): setting = AybuCoreSetting.get(session, setting_name) setting.value = getattr(self.theme, setting_name) setting = AybuCoreSetting.get(session, "theme_name") setting.value = self.theme.name theme = session.query(AybuCoreTheme)\ .filter(not_(AybuCoreTheme.children.any())).one() while theme: parent = theme.parent self.log.debug("removing theme: %s", theme.name) theme.delete() theme = parent session.flush() themes = [] t = AybuCoreTheme(name=self.theme.name, parent_name=self.theme.parent_name) themes.insert(0, t) parent = self.theme.parent while parent: t = AybuCoreTheme(name=parent.name, parent_name=parent.parent_name) themes.insert(0, t) parent = parent.parent for theme in themes: session.add(theme) session.flush() except: session.rollback() raise else: session.commit() session.close() session = None self.stamp_schema("head") finally: source_.close() if not session is None: session.close()