Пример #1
0
    def delete_smth(self, model=None, id=None):  # smth - something
        session = Session()
        models = {
            'pages': StaticPageModel,
            'redirect': UrlMapping,
            'catalog_section': CatalogSectionModel,
            'catalog_element': CatalogItemModel,
            'accounts': User
        }

        try:
            session.query(models[model]).filter_by(id=id).delete(
                synchronize_session=True)
            session.commit()
        except Exception as e:
            session.close()
            print('adm/AdminMainHandler.delete_smth(): '+\
             'cannot delete page by id #%s:\n' % str(id),\
             e, file=sys.stderr)
            return self.json_response({
                'status': 'error',
                'error_code': 'system_fail'
            })

        session.close()

        return self.json_response({'status': 'success'})
Пример #2
0
	def delete_smth(self, model=None, id=None): # smth - something
		session = Session()
		models = {
			'pages': StaticPageModel,
			'redirect': UrlMapping,
			'catalog_section': CatalogSectionModel,
			'catalog_element': CatalogItemModel,
			'accounts': User
		}
		
		try:
			session.query(
				models[model]
				).filter_by(id=id).delete(synchronize_session=True)
			session.commit()
		except Exception as e:
			session.close()
			print('adm/AdminMainHandler.delete_smth(): '+\
				'cannot delete page by id #%s:\n' % str(id),\
				e, file=sys.stderr)
			return self.json_response({
				'status': 'error',
				'error_code': 'system_fail'
			})
		
		session.close()
		
		return self.json_response({'status': 'success'})
Пример #3
0
	def wrap(*args, **kwargs):
		self = args[0]
		try:
			return fn(*args, **kwargs)
		except NoResultFound as e:
			print('route_except_handler(): NoResultFound exception:\n',\
				e, file=sys.stderr)
			self.set_status(404)
			session = Session()
			try:
				page = session.query(StaticPageModel)\
					.filter_by(alias=_404_page_alias).one()
			except Exception as e:
				session.close()
				print('route_except_handler(): cannot get 404 page'+\
					' by "%s" alias:\n' % str(_404_page_alias),\
					e, file=sys.stderr)
				self.set_status(500)
				return self.write('500: Internal server error')
			session.close()
			menu = self.getmenu()
			data = page.to_frontend
			data.update({
				'is_catalog': False,
				'is_catalog_item': False,
				'menu': menu,
				'is_debug': config('DEBUG')
			})
			data.update(self.get_nonrel_handlers())
			data.update(self.get_helpers())
			return self.render('client/error-404.jade', **data)
		except Exception as e:
			print(e, file=sys.stderr)
			self.set_status(500)
			return self.write('500: Internal server error')
Пример #4
0
	def to_frontend(self):
		vals = vars(self).copy()
		
		deprecated = ['_sa_instance_state', 'create_date', 'files', 'last_change']
		for item in deprecated:
			if item in vals:
				del vals[item]
		
		# get section alias
		session = Session()
		try:
			s = session.query(CatalogSectionModel.alias)\
				.filter_by(id=vals['section_id']).one()
		except Exception as e:
			session.close()
			print('CatalogItemModel.to_frontend():'+\
				' cannot find section by "section_id"'+\
				' for element #%d:\n' % int(vals['id']), e, file=sys.stderr)
			raise e
		session.close()
		
		vals['main_image'] = self._get_main_image(vals)
		vals['images']     = self._get_images(vals)
		
		vals['detail_link'] = '/catalog/{0}/{1}.html'.format(s[0], vals['alias'])
		
		return vals
Пример #5
0
	def post(self):
		session = Session()
		if self.get_current_user():
			# TODO : Change status to already auth
			return self.json_response({'status': 'success'})
		try:
			usr = session.query(User).filter_by(
				login=self.get_argument('user')
			).one()
		except Exception as e:
			session.close()
			print('adm/AuthHandler.post(): user not found:\n',\
				e, file=sys.stderr)
			return self.json_response({
				'status': 'error',
				'error_code': 'user_not_found'
			})
		session.close()

		compared = self.compare_password(
			hpasswd=usr.password,
			password=self.get_argument('pass'))

		if compared and usr.is_active:
			self.set_secure_cookie('user', usr.login)
			return self.json_response({'status': 'success'})
		elif not usr.is_active:
			return self.json_response({
				'status': 'error',
				'error_code': 'user_inactive'
			})
		return self.json_response({
			'status': 'error',
			'error_code': 'incorrect_password'})
Пример #6
0
	def get(self):
		data = {'is_debug': config('DEBUG')}
		urls = []

		session = Session()

		try:
			pages = session.query(StaticPageModel)\
				.filter_by(is_active=True)\
				.order_by(StaticPageModel.id.asc()).all()
			sections = session.query(CatalogSectionModel)\
				.filter_by(is_active=True)\
				.order_by(CatalogSectionModel.id.asc()).all()
			items = session.query(CatalogItemModel)\
				.filter_by(is_active=True)\
				.order_by(CatalogItemModel.id.asc()).all()
		except Exception as e:
			session.close()
			print('SiteMapRoute.get(): cannot get data from DB:\n',\
				e, file=sys.stderr)
			raise e

		session.close()

		for page in [x.item for x in pages]:
			if '404' in page['alias']:
				continue
			urls.append({
				'alias': quote(page['alias'], encoding='utf-8'),
				'lastmod': page['last_change']
			})

		for section in [x.item for x in sections]:
			url = '/catalog/{0}.html'.format(section['alias'])
			url = quote(url, encoding='utf-8')
			urls.append({
				'alias': url,
				'lastmod': section['last_change']
			})

		for item in [x.item for x in items]:
			section_alias = None
			for section in [x.item for x in sections]:
				if section['id'] == item['section_id']:
					section_alias = section['alias']
			if section_alias is None:
				e = Exception('SiteMapRoute: '+\
					'cannot find section for element #%d' % item['id'])
				print(e, file=sys.stderr)
				continue
			url = '/catalog/{0}/{1}.html'.format(section_alias, item['alias'])
			url = quote(url, encoding='utf-8')
			urls.append({
				'alias': url,
				'lastmod': section['last_change']
			})

		data.update({'urls': tuple(urls)})
		self.set_header('Content-Type', 'text/xml; charset="utf-8"')
		return self.render('client/sitemap.jade', **data)
Пример #7
0
	def get(self, alias, suffix):
		session = Session()
		alias = '/' + alias + suffix
		try:
			page = session\
				.query(StaticPageModel)\
				.filter_by(alias=alias, is_active=True)\
				.one()
		except Exception as e:
			session.close()
			print('StaticPageRoute.get(): cannot get static page or page is not active'+\
				' by "%s" alias:\n' % str(alias), e, file=sys.stderr)
			raise e
		session.close()
		menu = self.getmenu(page_alias=alias)
		data = page.to_frontend
		data.update({
			'is_catalog': False,
			'is_catalog_item': False,
			'menu': menu,
			'is_debug': config('DEBUG')
		})
		data.update(self.get_nonrel_handlers())
		data.update(self.get_helpers())
		return self.render('client/content-page.jade', **data)
Пример #8
0
    def to_frontend(self):
        vals = vars(self).copy()

        deprecated = [
            '_sa_instance_state', 'create_date', 'files', 'last_change'
        ]
        for item in deprecated:
            if item in vals:
                del vals[item]

        # get section alias
        session = Session()
        try:
            s = session.query(CatalogSectionModel.alias)\
             .filter_by(id=vals['section_id']).one()
        except Exception as e:
            session.close()
            print('CatalogItemModel.to_frontend():'+\
             ' cannot find section by "section_id"'+\
             ' for element #%d:\n' % int(vals['id']), e, file=sys.stderr)
            raise e
        session.close()

        vals['main_image'] = self._get_main_image(vals)
        vals['images'] = self._get_images(vals)

        vals['detail_link'] = '/catalog/{0}/{1}.html'.format(
            s[0], vals['alias'])

        return vals
Пример #9
0
    def get_nonrel_handlers(self):
        session = Session()
        try:
            data = session.query(NonRelationData).all()
        except Exception as e:
            session.close()
            print('NonRelationDataProvider.get_nonrel_handlers():'+\
             ' cannot get non-relation data:\n',\
             e, file=sys.stderr)
            raise e
        session.close()

        export = {}
        for item in [x.item for x in data]:
            data_list = tuple()
            try:
                data_list = json.loads(item['data_json'])
                if type(data_list) is not list and type(
                        data_list) is not tuple:
                    raise Exception('"data_json" must be a json-array')
            except Exception as e:
                print('NonRelationDataProvider.get_nonrel_handlers():'+\
                ' cannot get "data_json":\n', e, file=sys.stderr)
                data_list = tuple()
            export[item['code']] = data_list
        self.nonrel_list = export

        return {
            'get_nonrel_arr': self.get_nonrel_arr,
            'get_nonrel_val': self.get_nonrel_val
        }
Пример #10
0
    def post(self):
        session = Session()
        if self.get_current_user():
            # TODO : Change status to already auth
            return self.json_response({'status': 'success'})
        try:
            usr = session.query(User).filter_by(
                login=self.get_argument('user')).one()
        except Exception as e:
            session.close()
            print('adm/AuthHandler.post(): user not found:\n',\
             e, file=sys.stderr)
            return self.json_response({
                'status': 'error',
                'error_code': 'user_not_found'
            })
        session.close()

        compared = self.compare_password(hpasswd=usr.password,
                                         password=self.get_argument('pass'))

        if compared and usr.is_active:
            self.set_secure_cookie('user', usr.login)
            return self.json_response({'status': 'success'})
        elif not usr.is_active:
            return self.json_response({
                'status': 'error',
                'error_code': 'user_inactive'
            })
        return self.json_response({
            'status': 'error',
            'error_code': 'incorrect_password'
        })
Пример #11
0
	def get(self, alias, suffix):
		session = Session()
		alias = '/' + alias + suffix
		try:
			page = session\
				.query(StaticPageModel)\
				.filter_by(alias=alias, is_active=True)\
				.one()
		except Exception as e:
			session.close()
			print('StaticPageRoute.get(): cannot get static page or page is not active'+\
				' by "%s" alias:\n' % str(alias), e, file=sys.stderr)
			raise e
		session.close()
		menu = self.getmenu(page_alias=alias)
		data = page.to_frontend
		data.update({
			'is_catalog': False,
			'is_catalog_item': False,
			'menu': menu,
			'is_debug': config('DEBUG')
		})
		data.update(self.get_nonrel_handlers())
		data.update(self.get_helpers())
		return self.render('client/content-page.jade', **data)
Пример #12
0
def collect_handlers(*args):
    routes = []
    for item in args:
        routes += item
    duplicated = {x for x in routes if routes.count(x) > 1}
    if len(duplicated) > 0:
        raise CollectHandlersException(
            "Duplicate routes! {0}".format(duplicated))

    redirect_routes = []
    session = Session()
    try:
        _rr = session.query(UrlMapping).all()
    except Exception as e:
        session.close()
        print('collect_handlers(): cannot get data from UrlMapping model:\n',\
         e, file=sys.stderr)
        raise e
    for redirect in _rr:
        old_url = quote(redirect.old_url, encoding='utf-8')
        redirect_routes.append((old_url, UnicodeRedirectHandler, {
            'url': redirect.new_url,
            'status': int(redirect.status)
        }))
    session.close()
    return redirect_routes + routes
Пример #13
0
	def get_nonrel_handlers(self):
		session = Session()
		try:
			data = session.query(NonRelationData).all()
		except Exception as e:
			session.close()
			print('NonRelationDataProvider.get_nonrel_handlers():'+\
				' cannot get non-relation data:\n',\
				e, file=sys.stderr)
			raise e
		session.close()
		
		export = {}
		for item in [x.item for x in data]:
			data_list = tuple()
			try:
				data_list = json.loads(item['data_json'])
				if type(data_list) is not list and type(data_list) is not tuple:
					raise Exception('"data_json" must be a json-array')
			except Exception as e:
				print('NonRelationDataProvider.get_nonrel_handlers():'+\
				' cannot get "data_json":\n', e, file=sys.stderr)
				data_list = tuple()
			export[item['code']] = data_list
		self.nonrel_list = export
		
		return {
			'get_nonrel_arr': self.get_nonrel_arr,
			'get_nonrel_val': self.get_nonrel_val
		}
Пример #14
0
 def wrap(*args, **kwargs):
     self = args[0]
     try:
         return fn(*args, **kwargs)
     except NoResultFound as e:
         print('route_except_handler(): NoResultFound exception:\n',\
          e, file=sys.stderr)
         self.set_status(404)
         session = Session()
         try:
             page = session.query(StaticPageModel)\
              .filter_by(alias=_404_page_alias).one()
         except Exception as e:
             session.close()
             print('route_except_handler(): cannot get 404 page'+\
              ' by "%s" alias:\n' % str(_404_page_alias),\
              e, file=sys.stderr)
             self.set_status(500)
             return self.write('500: Internal server error')
         session.close()
         menu = self.getmenu()
         data = page.to_frontend
         data.update({
             'is_catalog': False,
             'is_catalog_item': False,
             'menu': menu,
             'is_debug': config('DEBUG')
         })
         data.update(self.get_nonrel_handlers())
         data.update(self.get_helpers())
         return self.render('client/error-404.jade', **data)
     except Exception as e:
         print(e, file=sys.stderr)
         self.set_status(500)
         return self.write('500: Internal server error')
Пример #15
0
def collect_handlers(*args):
	routes = []
	for item in args:
		routes += item
	duplicated = {x for x in routes if routes.count(x) > 1}
	if len(duplicated) > 0:
		raise CollectHandlersException("Duplicate routes! {0}".format(duplicated))

	redirect_routes = []
	session = Session()
	try:
		_rr = session.query(UrlMapping).all()
	except Exception as e:
		session.close()
		print('collect_handlers(): cannot get data from UrlMapping model:\n',\
			e, file=sys.stderr)
		raise e
	for redirect in _rr:
		old_url = quote(redirect.old_url, encoding='utf-8')
		redirect_routes.append((old_url, UnicodeRedirectHandler, {
			'url': redirect.new_url,
			'status': int(redirect.status)
		}))
	session.close()
	return redirect_routes + routes
Пример #16
0
    def get(self):
        data = {'is_debug': config('DEBUG')}
        urls = []

        session = Session()

        try:
            pages = session.query(StaticPageModel)\
             .filter_by(is_active=True)\
             .order_by(StaticPageModel.id.asc()).all()
            sections = session.query(CatalogSectionModel)\
             .filter_by(is_active=True)\
             .order_by(CatalogSectionModel.id.asc()).all()
            items = session.query(CatalogItemModel)\
             .filter_by(is_active=True)\
             .order_by(CatalogItemModel.id.asc()).all()
        except Exception as e:
            session.close()
            print('SiteMapRoute.get(): cannot get data from DB:\n',\
             e, file=sys.stderr)
            raise e

        session.close()

        for page in [x.item for x in pages]:
            if '404' in page['alias']:
                continue
            urls.append({
                'alias': quote(page['alias'], encoding='utf-8'),
                'lastmod': page['last_change']
            })

        for section in [x.item for x in sections]:
            url = '/catalog/{0}.html'.format(section['alias'])
            url = quote(url, encoding='utf-8')
            urls.append({'alias': url, 'lastmod': section['last_change']})

        for item in [x.item for x in items]:
            section_alias = None
            for section in [x.item for x in sections]:
                if section['id'] == item['section_id']:
                    section_alias = section['alias']
            if section_alias is None:
                e = Exception('SiteMapRoute: '+\
                 'cannot find section for element #%d' % item['id'])
                print(e, file=sys.stderr)
                continue
            url = '/catalog/{0}/{1}.html'.format(section_alias, item['alias'])
            url = quote(url, encoding='utf-8')
            urls.append({'alias': url, 'lastmod': section['last_change']})

        data.update({'urls': tuple(urls)})
        self.set_header('Content-Type', 'text/xml; charset="utf-8"')
        return self.render('client/sitemap.jade', **data)
Пример #17
0
    def get_static_page(self, id=None):
        session = Session()

        try:
            data = session.query(StaticPageModel).filter_by(id=id).one()
        except Exception as e:
            session.close()
            print('adm/AdminMainHandler.get_static_page(): '+\
             'cannot get static page by id #%s:\n' % str(id),\
             e, file=sys.stderr)
            raise e

        session.close()

        return self.json_response({'status': 'success', 'data': data.item})
Пример #18
0
	def post(self):
		session = Session()
		kwargs = {}
		passwrd = self.get_argument('password')
		login = self.get_argument('login')
		id = self.get_argument('id')
		is_active = True
		try:
			self.get_argument('is_active')
		except:
			is_active = False

		try:
			usr = session.query(User).filter_by(id=id).one()
		except Exception as e:
			session.close()
			print('adm/UpdateUser.post(): cannot get user'+\
				' by #%s id:\n' % str(id),\
				e, file=sys.stderr)
			raise e

		try:
			olds = [x[0] for x in session.query(User.login).all()]
		except Exception as e:
			session.close()
			print('adm/UpdateUser.post(): cannot get users logins:\n',\
				e, file=sys.stderr)
			raise e

		if login == '':
			return self.json_response({
				'status': 'error',
				'error_code': 'unique_key_exist'
			})
		elif usr.login != login and login in olds:
			return self.json_response({
				'status': 'error',
				'error_code': 'incorrect_data'
			})

		kwargs.update({'login': login, 'is_active': is_active})
		if passwrd != '':
			kwargs.update({'password': self.create_password(passwrd)})

		try:
			session.query(User).filter_by(id=id).update(kwargs)
			session.commit()
		except Exception as e:
			session.close()
			print('adm/UpdateUser.post(): cannot update '+\
				'user #%s data:\n' % str(id),\
				e, file=sys.stderr)
			raise e

		session.close()
		return self.json_response({'status': 'success'})
Пример #19
0
    def post(self):
        session = Session()
        kwargs = {}
        passwrd = self.get_argument('password')
        login = self.get_argument('login')
        id = self.get_argument('id')
        is_active = True
        try:
            self.get_argument('is_active')
        except:
            is_active = False

        try:
            usr = session.query(User).filter_by(id=id).one()
        except Exception as e:
            session.close()
            print('adm/UpdateUser.post(): cannot get user'+\
             ' by #%s id:\n' % str(id),\
             e, file=sys.stderr)
            raise e

        try:
            olds = [x[0] for x in session.query(User.login).all()]
        except Exception as e:
            session.close()
            print('adm/UpdateUser.post(): cannot get users logins:\n',\
             e, file=sys.stderr)
            raise e

        if login == '':
            return self.json_response({
                'status': 'error',
                'error_code': 'unique_key_exist'
            })
        elif usr.login != login and login in olds:
            return self.json_response({
                'status': 'error',
                'error_code': 'incorrect_data'
            })

        kwargs.update({'login': login, 'is_active': is_active})
        if passwrd != '':
            kwargs.update({'password': self.create_password(passwrd)})

        try:
            session.query(User).filter_by(id=id).update(kwargs)
            session.commit()
        except Exception as e:
            session.close()
            print('adm/UpdateUser.post(): cannot update '+\
             'user #%s data:\n' % str(id),\
             e, file=sys.stderr)
            raise e

        session.close()
        return self.json_response({'status': 'success'})
Пример #20
0
    def get_pages_list(self):
        session = Session()

        try:
            data = session.query(StaticPageModel).all()
        except Exception as e:
            session.close()
            print('adm/AdminMainHandler.get_pages_list(): '+\
             'cannot get static pages:\n',\
             e, file=sys.stderr)
            raise e

        session.close()
        return self.json_response({
            'status': 'success',
            'data_list': [x.static_list for x in data]
        })
Пример #21
0
    def get_data_list(self):
        session = Session()

        try:
            data = session.query(NonRelationData).all()
        except Exception as e:
            session.close()
            print('adm/AdminMainHandler.get_data_list(): '+\
             'cannot get non-relation data elements:\n',\
             e, file=sys.stderr)
            raise e

        session.close()
        return self.json_response({
            'status': 'success',
            'data_list': [x.item for x in data]
        })
Пример #22
0
	def get_pages_list(self):
		session = Session()
		
		try:
			data = session.query(StaticPageModel).all()
		except Exception as e:
			session.close()
			print('adm/AdminMainHandler.get_pages_list(): '+\
				'cannot get static pages:\n',\
				e, file=sys.stderr)
			raise e
		
		session.close()
		return self.json_response({
			'status': 'success',
			'data_list': [ x.static_list for x in data ]
		})
Пример #23
0
	def get_data_list(self):
		session = Session()
		
		try:
			data = session.query(NonRelationData).all()
		except Exception as e:
			session.close()
			print('adm/AdminMainHandler.get_data_list(): '+\
				'cannot get non-relation data elements:\n',\
				e, file=sys.stderr)
			raise e
		
		session.close()
		return self.json_response({
			'status': 'success',
			'data_list': [x.item for x in data]
		})
Пример #24
0
	def get_static_page(self, id=None):
		session = Session()
		
		try:
			data = session.query(StaticPageModel).filter_by(id=id).one()
		except Exception as e:
			session.close()
			print('adm/AdminMainHandler.get_static_page(): '+\
				'cannot get static page by id #%s:\n' % str(id),\
				e, file=sys.stderr)
			raise e
		
		session.close()
		
		return self.json_response({
			'status': 'success',
			'data': data.item
		})
Пример #25
0
    def get_redirect_list(self):
        session = Session()

        try:
            data = session.query(UrlMapping).all()
        except Exception as e:
            session.close()
            print('adm/AdminMainHandler.get_redirect_list(): '+\
             'cannot get data from UrlMapping model:\n',\
             e, file=sys.stderr)
            raise e

        session.close()

        return self.json_response({
            'status': 'success',
            'data_list': [x.item for x in data]
        })
Пример #26
0
	def get_redirect_list(self):
		session = Session()
		
		try:
			data = session.query(UrlMapping).all()
		except Exception as e:
			session.close()
			print('adm/AdminMainHandler.get_redirect_list(): '+\
				'cannot get data from UrlMapping model:\n',\
				e, file=sys.stderr)
			raise e
		
		session.close()
		
		return self.json_response({
			'status': 'success',
			'data_list': [x.item for x in data]
		})
Пример #27
0
	def get_catalog_sections(self):
		session = Session()

		try:
			cats = session.query(CatalogSectionModel.id).all()
		except Exception as e:
			session.close()
			print('adm/AdminMainHandler.get_catalog_sections(): '+\
				'cannot get catalog sections:\n',\
				e, file=sys.stderr)
			raise e

		counts = []
		for i in cats:
			try:
				count = session.query(
					CatalogItemModel.id).filter_by(
						section_id=i[0]
					).all()
			except Exception as e:
				session.close()
				print('adm/AdminMainHandler.get_catalog_sections(): '+\
					'cannot get catalog items by section id #%s:\n' % str(i[0]),\
					e, file=sys.stderr)
				raise e
			counts.append((len(count),))

		try:
			data = session.query(
				CatalogSectionModel.title,
				CatalogSectionModel.id,
				CatalogSectionModel.is_active
			).all()
		except Exception as e:
			session.close()
			print('adm/AdminMainHandler.get_catalog_sections(): '+\
				'cannot get catalog sections:\n',\
				e, file=sys.stderr)
			raise e

		session.close()
		return self.json_response({
			'status': 'success',
			'data_list': [{
				'is_active': x[1][2] and True or False,
				'id': x[1][1],
				'title': x[1][0],
				'count': x[0][0]
			} for x in list(zip(counts, data))]
		})
Пример #28
0
	def get_catalog_sections(self):
		session = Session()
		
		try:
			cats = session.query(CatalogSectionModel.id).all()
		except Exception as e:
			session.close()
			print('adm/AdminMainHandler.get_catalog_sections(): '+\
				'cannot get catalog sections:\n',\
				e, file=sys.stderr)
			raise e
		
		counts = []
		for i in cats:
			try:
				count = session.query(
					CatalogItemModel.id).filter_by(
						section_id=i[0]
					).all()
			except Exception as e:
				session.close()
				print('adm/AdminMainHandler.get_catalog_sections(): '+\
					'cannot get catalog items by section id #%s:\n' % str(i[0]),\
					e, file=sys.stderr)
				raise e
			counts.append((len(count),))
		
		try:
			data = session.query(
				CatalogSectionModel.title,
				CatalogSectionModel.id,
				CatalogSectionModel.is_active
			).all()
		except Exception as e:
			session.close()
			print('adm/AdminMainHandler.get_catalog_sections(): '+\
				'cannot get catalog sections:\n',\
				e, file=sys.stderr)
			raise e
		
		session.close()
		return self.json_response({
			'status': 'success',
			'data_list': [{
				'is_active': x[1][2] and True or False,
				'id': x[1][1],
				'title': x[1][0],
				'count': x[0][0]
			} for x in list(zip(counts, data))]
		})
Пример #29
0
	def get_accounts_list(self):
		session = Session()
		
		try:
			data = session.query(User).all()
		except Exception as e:
			session.close()
			print('adm/AdminMainHandler.get_accounts_list(): '+\
				'cannot get users:\n',\
				e, file=sys.stderr)
			raise e
		
		session.close()
		
		return self.json_response({
			'status': 'success',
			'data_list': [{
				'id': x.id,
				'login': x.login,
				'is_active': x.is_active
				} for x in data ]
			})
Пример #30
0
	def getmenu(
		self,
		page_alias=None,
		catalog_section_alias=None,
		catalog_item_alias=None
	):
		menu = {
			'main': [],
			'catalog': []
		}
		
		session = Session()
		
		try:
			static_pages = session.query(StaticPageModel)\
				.filter_by(is_main_menu_item=True, is_active=True)\
				.order_by(StaticPageModel.id.asc()).all()
		except Exception as e:
			session.close()
			print('MenuProviderMixin.getmenu(): cannot get static pages:\n',\
				e, file=sys.stderr)
			raise e
		for page in [x.item for x in static_pages]:
			item = {
				'active': False,
				'link': page['alias'],
				'title': page['title']
			}
			if page_alias is not None:
				if page['alias'] == page_alias:
					item['active'] = True
			menu['main'].append(item)
		
		try:
			sections = session.query(CatalogSectionModel)\
				.filter_by(is_active=True)\
				.order_by(CatalogSectionModel.id.asc()).all()
		except Exception as e:
			session.close()
			print('MenuProviderMixin.getmenu(): cannot get catalog sections:\n',\
				e, file=sys.stderr)
			raise e
		for section in [x.item for x in sections]:
			item = {
				'active': False,
				'current': False,
				'link': '/catalog/' + section['alias'] + '.html',
				'title': section['title']
			}
			if catalog_section_alias is not None:
				if section['alias'] == catalog_section_alias:
					item['active'] = True
					item['current'] = True
					if catalog_item_alias is not None:
						item['current'] = False
			menu['catalog'].append(item)
		
		session.close()
		return menu
Пример #31
0
	def get_accounts_list(self):
		session = Session()

		try:
			data = session.query(User).all()
		except Exception as e:
			session.close()
			print('adm/AdminMainHandler.get_accounts_list(): '+\
				'cannot get users:\n',\
				e, file=sys.stderr)
			raise e

		session.close()

		return self.json_response({
			'status': 'success',
			'data_list': [{
				'id': x.id,
				'login': x.login,
				'is_active': x.is_active
				} for x in data ]
			})
Пример #32
0
	def create(self, **kwargs):
		section = kwargs['section']
		del kwargs['section']
		
		for item in (x for x
			in kwargs.keys()
				if x.startswith('is_')
					or x.startswith('has_')):
			kwargs[item] = True
		
		section_map = {
			'pages': StaticPageModel,
			'redirect': UrlMapping,
			'catalog_section': CatalogSectionModel,
			'catalog_element': CatalogItemModel,
			'data': NonRelationData
		}
		
		session = Session()
		
		page = section_map[section](**kwargs)
		
		try:
			session.add(page)
		except Exception as e:
			session.close()
			print('adm/AdminMainHandler.create(): '+\
				'cannot create page by "%s" section:\n' % str(section),\
				e, file=sys.stderr)
			raise e
		
		if section == 'redirect':
			permanent = (lambda: True if kwargs['status'] == '301' else False)()
			from app.app import application
			
			application.handlers[0][1][:0] = [
				URLSpec(
					kwargs['old_url'] + '$',
					RedirectHandler,
					kwargs={
						'url': kwargs['new_url'],
						'permanent': permanent
						},
					name=None)
			]
		
		try:
			session.commit()
		except Exception as e:
			session.close()
			print('adm/AdminMainHandler.create(): '+\
				'cannot commit create page by "%s" section:\n' % str(section),\
				e, file=sys.stderr)
			raise e
			
		session.close()
		
		return self.json_response({'status': 'success'})
Пример #33
0
	def create(self, **kwargs):
		section = kwargs['section']
		del kwargs['section']

		for item in (x for x
			in kwargs.keys()
				if x.startswith('is_')
					or x.startswith('has_')):
			kwargs[item] = True

		section_map = {
			'pages': StaticPageModel,
			'redirect': UrlMapping,
			'catalog_section': CatalogSectionModel,
			'catalog_element': CatalogItemModel,
			'data': NonRelationData
		}

		session = Session()

		page = section_map[section](**kwargs)

		try:
			session.add(page)
		except Exception as e:
			session.close()
			print('adm/AdminMainHandler.create(): '+\
				'cannot create page by "%s" section:\n' % str(section),\
				e, file=sys.stderr)
			raise e

		if section == 'redirect':
			permanent = (lambda: True if kwargs['status'] == '301' else False)()
			from app.app import application

			application.handlers[0][1][:0] = [
				URLSpec(
					kwargs['old_url'] + '$',
					RedirectHandler,
					kwargs={
						'url': kwargs['new_url'],
						'permanent': permanent
						},
					name=None)
			]

		try:
			session.commit()
		except Exception as e:
			session.close()
			print('adm/AdminMainHandler.create(): '+\
				'cannot commit create page by "%s" section:\n' % str(section),\
				e, file=sys.stderr)
			raise e

		session.close()

		return self.json_response({'status': 'success'})
Пример #34
0
	def save_call(self, d):
		call = CallModel(
			name = d['name'],
			phone = d['phone'],
			date = datetime.utcnow()
		)
		session = Session()
		try:
			session.add(call)
			session.commit()
		except Exception as e:
			session.close()
			print('FormsHandler.save_call(): cannot save call to DB\n',\
				e, file=sys.stderr)
			raise e
		session.close()
		
		send_mail(
			msg='<h1>Заказ звонка</h1>' +
				'<dl><dt>Имя:</dt><dd>%s</dd>' % d['name'] +
				'<dt>Телефон:</dt><dd>%s</dd></dl>' % d['phone'],
			theme='АвтоЛюкс: заказ звонка'
		)
Пример #35
0
	def save_call(self, d):
		call = CallModel(
			name = d['name'],
			phone = d['phone'],
			date = datetime.utcnow()
		)
		session = Session()
		try:
			session.add(call)
			session.commit()
		except Exception as e:
			session.close()
			print('FormsHandler.save_call(): cannot save call to DB\n',\
				e, file=sys.stderr)
			raise e
		session.close()

		send_mail(
			msg='<h1>Заказ звонка</h1>' +
				'<dl><dt>Имя:</dt><dd>%s</dd>' % d['name'] +
				'<dt>Телефон:</dt><dd>%s</dd></dl>' % d['phone'],
			theme='АвтоЛюкс: заказ звонка'
		)
Пример #36
0
	def get(self):
		session = Session()
		try:
			page = session\
				.query(StaticPageModel)\
				.filter_by(alias='/', is_active=True)\
				.one()
		except Exception as e:
			session.close()
			print('MainRoute.get(): cannot get main page:\n', e, file=sys.stderr)
			raise e
		session.close()
		menu = self.getmenu(page_alias='/')
		data = page.to_frontend
		data.update({
			'is_catalog': False,
			'is_catalog_item': False,
			'menu': menu,
			'is_debug': config('DEBUG')
		})
		data.update(self.get_nonrel_handlers())
		data.update(self.get_helpers())
		return self.render('client/content-page.jade', **data)
Пример #37
0
	def get(self):
		session = Session()
		try:
			page = session\
				.query(StaticPageModel)\
				.filter_by(alias='/', is_active=True)\
				.one()
		except Exception as e:
			session.close()
			print('MainRoute.get(): cannot get main page:\n', e, file=sys.stderr)
			raise e
		session.close()
		menu = self.getmenu(page_alias='/')
		data = page.to_frontend
		data.update({
			'is_catalog': False,
			'is_catalog_item': False,
			'menu': menu,
			'is_debug': config('DEBUG')
		})
		data.update(self.get_nonrel_handlers())
		data.update(self.get_helpers())
		return self.render('client/content-page.jade', **data)
Пример #38
0
	def get(self, category, item):
		session = Session()
		
		# check for active element section
		try:
			section = session.query(CatalogSectionModel)\
				.filter_by(alias=category, is_active=True)\
				.one()
		except Exception as e:
			session.close()
			print('CatalogItemRoute.get(): cannot get catalog section or section is not active'+\
				' by "%s" code:\n' % str(category),\
				e, file=sys.stderr)
			raise e
		
		if item.endswith(".html"):
			item = item.replace('.html', '').replace('/', '')
		
		# get item
		try:
			page = session\
				.query(CatalogItemModel)\
				.filter_by(alias=item, is_active=True)\
				.one()
		except Exception as e:
			session.close()
			print('CatalogItemRoute.get(): cannot get catalog item or item is not active'+\
				' by "%s" code:\n' % str(item),\
				e, file=sys.stderr)
			raise e
		
		session.close()
		data = page.to_frontend
		
		# check for category
		if data['section_id'] != section.to_frontend['id']:
			e = NoResultFound()
			print('CatalogItemRoute.get(): mismatch catalog category of element and category in URL'+\
				' by "%s" code:\n' % str(item),\
				e, file=sys.stderr)
			raise e
		
		menu = self.getmenu(
			catalog_section_alias=category,
			catalog_item_alias=item)
		data.update({
			'is_catalog': True,
			'is_catalog_item': True,
			'catalog_item_id': data['id'],
			'is_main_page': False,
			'menu': menu,
			'is_debug': config('DEBUG')
		})
		data.update(self.get_nonrel_handlers())
		data.update(self.get_helpers())
		return self.render('client/catalog-detail.jade', **data)
Пример #39
0
    def get(self, category, item):
        session = Session()

        # check for active element section
        try:
            section = session.query(CatalogSectionModel)\
             .filter_by(alias=category, is_active=True)\
             .one()
        except Exception as e:
            session.close()
            print('CatalogItemRoute.get(): cannot get catalog section or section is not active'+\
             ' by "%s" code:\n' % str(category),\
             e, file=sys.stderr)
            raise e

        if item.endswith(".html"):
            item = item.replace('.html', '').replace('/', '')

        # get item
        try:
            page = session\
             .query(CatalogItemModel)\
             .filter_by(alias=item, is_active=True)\
             .one()
        except Exception as e:
            session.close()
            print('CatalogItemRoute.get(): cannot get catalog item or item is not active'+\
             ' by "%s" code:\n' % str(item),\
             e, file=sys.stderr)
            raise e

        session.close()
        data = page.to_frontend

        # check for category
        if data['section_id'] != section.to_frontend['id']:
            e = NoResultFound()
            print('CatalogItemRoute.get(): mismatch catalog category of element and category in URL'+\
             ' by "%s" code:\n' % str(item),\
             e, file=sys.stderr)
            raise e

        menu = self.getmenu(catalog_section_alias=category,
                            catalog_item_alias=item)
        data.update({
            'is_catalog': True,
            'is_catalog_item': True,
            'catalog_item_id': data['id'],
            'is_main_page': False,
            'menu': menu,
            'is_debug': config('DEBUG')
        })
        data.update(self.get_nonrel_handlers())
        data.update(self.get_helpers())
        return self.render('client/catalog-detail.jade', **data)
Пример #40
0
    def getmenu(self,
                page_alias=None,
                catalog_section_alias=None,
                catalog_item_alias=None):
        menu = {'main': [], 'catalog': []}

        session = Session()

        try:
            static_pages = session.query(StaticPageModel)\
             .filter_by(is_main_menu_item=True, is_active=True)\
             .order_by(StaticPageModel.id.asc()).all()
        except Exception as e:
            session.close()
            print('MenuProviderMixin.getmenu(): cannot get static pages:\n',\
             e, file=sys.stderr)
            raise e
        for page in [x.item for x in static_pages]:
            item = {
                'active': False,
                'link': page['alias'],
                'title': page['title']
            }
            if page_alias is not None:
                if page['alias'] == page_alias:
                    item['active'] = True
            menu['main'].append(item)

        try:
            sections = session.query(CatalogSectionModel)\
             .filter_by(is_active=True)\
             .order_by(CatalogSectionModel.id.asc()).all()
        except Exception as e:
            session.close()
            print('MenuProviderMixin.getmenu(): cannot get catalog sections:\n',\
             e, file=sys.stderr)
            raise e
        for section in [x.item for x in sections]:
            item = {
                'active': False,
                'current': False,
                'link': '/catalog/' + section['alias'] + '.html',
                'title': section['title']
            }
            if catalog_section_alias is not None:
                if section['alias'] == catalog_section_alias:
                    item['active'] = True
                    item['current'] = True
                    if catalog_item_alias is not None:
                        item['current'] = False
            menu['catalog'].append(item)

        session.close()
        return menu
Пример #41
0
	def save_order(self, d):
		dt = d['date'].split('.')
		session = Session()
		try:
			item = session.query(CatalogItemModel).filter_by(id=d['id']).one()
		except Exception as e:
			session.close()
			print('FormsHandler.save_order(): cannot get catalog item by id\n',\
				e, file=sys.stderr)
			raise e
		session.close()
		full_date = datetime.combine(
				date(int(dt[2]), int(dt[1]), int(dt[0])),
				time(int(d['hours']), int(d['minutes']))),
		order = OrderModel(
			name=d['name'],
			callback=d['callback'],
			date=full_date,
			item_id=item.id
		)
		
		session = Session()
		try:
			session.add(order)
			session.commit()
		except Exception as e:
			session.close()
			print('FormsHandler.save_order(): cannot save order to DB\n',\
				e, file=sys.stderr)
			raise e
		session.close()
		send_mail(
			msg='<h1>Заказ "%s"</h1>' % item.title +
				'<dl><dt>Имя:</dt><dd>%s</dd>' % d['name'] +
				'<dt>Контакты:</dt><dd>%s</dd>' % d['callback'] +
				'<dt>Дата заказа:</dt><dd>%s</dd></dl>' % (
					full_date[0].strftime('%d.%m.%Y %H:%M')),
			theme='АвтоЛюкс: заказ "%s"' % item.title
		)
Пример #42
0
	def save_order(self, d):
		dt = d['date'].split('.')
		session = Session()
		try:
			item = session.query(CatalogItemModel).filter_by(id=d['id']).one()
		except Exception as e:
			session.close()
			print('FormsHandler.save_order(): cannot get catalog item by id\n',\
				e, file=sys.stderr)
			raise e
		session.close()
		full_date = datetime.combine(
				date(int(dt[2]), int(dt[1]), int(dt[0])),
				time(int(d['hours']), int(d['minutes']))),
		order = OrderModel(
			name=d['name'],
			callback=d['callback'],
			date=full_date,
			item_id=item.id
		)

		session = Session()
		try:
			session.add(order)
			session.commit()
		except Exception as e:
			session.close()
			print('FormsHandler.save_order(): cannot save order to DB\n',\
				e, file=sys.stderr)
			raise e
		session.close()
		send_mail(
			msg='<h1>Заказ "%s"</h1>' % item.title +
				'<dl><dt>Имя:</dt><dd>%s</dd>' % d['name'] +
				'<dt>Контакты:</dt><dd>%s</dd>' % d['callback'] +
				'<dt>Дата заказа:</dt><dd>%s</dd></dl>' % (
					full_date[0].strftime('%d.%m.%Y %H:%M')),
			theme='АвтоЛюкс: заказ "%s"' % item.title
		)
Пример #43
0
	def post(self):
		session = Session()
		login = self.get_argument('login')
		passwd = self.get_argument('password')
		is_active = True

		try:
			olds = [x[0] for x in session.query(User.login).all()]
		except Exception as e:
			session.close()
			print('adm/CreateUser.post(): cannot get users logins:\n',\
				e, file=sys.stderr)
			raise e

		if login == '':
			return self.json_response({
				'status': 'error',
				'error_code': 'unique_key_exist'
			})
		elif login in olds:
			return self.json_response({
				'status': 'error',
				'error_code': 'incorrect_data'
			})
		try:
			self.get_argument('is_active')
		except:
			is_active = False

		usr = User(
			login=login,
			password=self.create_password(passwd),
			last_login=datetime.datetime.utcnow(),
			is_active=is_active
		)

		try:
			session.add(usr)
			session.commit()
		except Exception as e:
			session.close()
			print('adm/CreateUser.post(): cannot add user:\n',\
				e, file=sys.stderr)
			raise e

		session.close()
		return self.json_response({'status': 'success'})
Пример #44
0
    def post(self):
        session = Session()
        login = self.get_argument('login')
        passwd = self.get_argument('password')
        is_active = True

        try:
            olds = [x[0] for x in session.query(User.login).all()]
        except Exception as e:
            session.close()
            print('adm/CreateUser.post(): cannot get users logins:\n',\
             e, file=sys.stderr)
            raise e

        if login == '':
            return self.json_response({
                'status': 'error',
                'error_code': 'unique_key_exist'
            })
        elif login in olds:
            return self.json_response({
                'status': 'error',
                'error_code': 'incorrect_data'
            })
        try:
            self.get_argument('is_active')
        except:
            is_active = False

        usr = User(login=login,
                   password=self.create_password(passwd),
                   last_login=datetime.datetime.utcnow(),
                   is_active=is_active)

        try:
            session.add(usr)
            session.commit()
        except Exception as e:
            session.close()
            print('adm/CreateUser.post(): cannot add user:\n',\
             e, file=sys.stderr)
            raise e

        session.close()
        return self.json_response({'status': 'success'})
Пример #45
0
	def get_catalog_elements(self, id=None):
		session = Session()
		
		try:
			data = session.query(
				CatalogItemModel.id,
				CatalogItemModel.title,
				CatalogItemModel.is_active
			).filter_by(section_id=id).all()
		except Exception as e:
			session.close()
			print('adm/AdminMainHandler.get_catalog_elements(): '+\
				'cannot get catalog items by section id #%s:\n' % str(id),\
				e, file=sys.stderr)
			raise e
		
		try:
			title = session.query(
				CatalogSectionModel.title
			).filter_by(id=id).one()
		except Exception as e:
			session.close()
			print('adm/AdminMainHandler.get_catalog_elements(): '+\
				'cannot get catalog section by id #%s:\n' % str(id),\
				e, file=sys.stderr)
			raise e
		
		session.close()
		
		return self.json_response({
			'status': 'success',
			'section_title': title[0],
			'data_list': [{
				'is_active': x.is_active and True or False,
				'title': x.title,
				'id': x.id
			} for x in data]
		})
Пример #46
0
	def get_catalog_elements(self, id=None):
		session = Session()

		try:
			data = session.query(
				CatalogItemModel.id,
				CatalogItemModel.title,
				CatalogItemModel.is_active
			).filter_by(section_id=id).all()
		except Exception as e:
			session.close()
			print('adm/AdminMainHandler.get_catalog_elements(): '+\
				'cannot get catalog items by section id #%s:\n' % str(id),\
				e, file=sys.stderr)
			raise e

		try:
			title = session.query(
				CatalogSectionModel.title
			).filter_by(id=id).one()
		except Exception as e:
			session.close()
			print('adm/AdminMainHandler.get_catalog_elements(): '+\
				'cannot get catalog section by id #%s:\n' % str(id),\
				e, file=sys.stderr)
			raise e

		session.close()

		return self.json_response({
			'status': 'success',
			'section_title': title[0],
			'data_list': [{
				'is_active': x.is_active and True or False,
				'title': x.title,
				'id': x.id
			} for x in data]
		})
Пример #47
0
	def get(self, alias):
		session = Session()
		if alias.endswith(".html"):
			alias = alias.replace('.html', '').replace('/', '')
		try:
			page = session.query(CatalogSectionModel)\
				.filter_by(alias=alias, is_active=True)\
				.one()
		except Exception as e:
			session.close()
			print('CatalogSectionRoute.get(): cannot get catalog section or section is not active'+\
				' by "%s" code:\n' % str(alias),\
				e, file=sys.stderr)
			raise e
		try:
			items = session.query(CatalogItemModel)\
				.filter_by(section_id=page.id, is_active=True)\
				.order_by(CatalogItemModel.id.asc()).all()
		except Exception as e:
			session.close()
			print('CatalogSectionRoute.get(): cannot get catalog items'+\
				' by section #%d:\n' % int(page.id),\
				e, file=sys.stderr)
			raise e
		session.close()
		menu = self.getmenu(catalog_section_alias=alias)
		data = page.to_frontend
		data.update({
			'is_catalog': True,
			'is_catalog_item': False,
			'is_main_page': False,
			'items': [x.to_frontend for x in items],
			'menu': menu,
			'is_debug': config('DEBUG')
		})
		data.update(self.get_nonrel_handlers())
		data.update(self.get_helpers())
		return self.render('client/catalog-sections.jade', **data)
Пример #48
0
 def get(self, alias):
     session = Session()
     if alias.endswith(".html"):
         alias = alias.replace('.html', '').replace('/', '')
     try:
         page = session.query(CatalogSectionModel)\
          .filter_by(alias=alias, is_active=True)\
          .one()
     except Exception as e:
         session.close()
         print('CatalogSectionRoute.get(): cannot get catalog section or section is not active'+\
          ' by "%s" code:\n' % str(alias),\
          e, file=sys.stderr)
         raise e
     try:
         items = session.query(CatalogItemModel)\
          .filter_by(section_id=page.id, is_active=True)\
          .order_by(CatalogItemModel.id.asc()).all()
     except Exception as e:
         session.close()
         print('CatalogSectionRoute.get(): cannot get catalog items'+\
          ' by section #%d:\n' % int(page.id),\
          e, file=sys.stderr)
         raise e
     session.close()
     menu = self.getmenu(catalog_section_alias=alias)
     data = page.to_frontend
     data.update({
         'is_catalog': True,
         'is_catalog_item': False,
         'is_main_page': False,
         'items': [x.to_frontend for x in items],
         'menu': menu,
         'is_debug': config('DEBUG')
     })
     data.update(self.get_nonrel_handlers())
     data.update(self.get_helpers())
     return self.render('client/catalog-sections.jade', **data)
Пример #49
0
    def get_fields(self, model=None, edit=False, id=None):
        session = Session()

        models = {
            'pages': StaticPageModel,
            'redirect': UrlMapping,
            'catalog_section': CatalogSectionModel,
            'catalog_element': CatalogItemModel,
            'accounts': User,
            'data': NonRelationData
        }

        fields = db_inspector.get_columns(models[model].__tablename__)

        # TODO :: refactoring
        types_map = {
            'BOOLEAN': 'checkbox',
            'TEXT': 'html',
            'VARCHAR(4096)': 'text',
            'VARCHAR(8192)': 'text',
            'VARCHAR(1024)': 'text',
            'VARCHAR(5000)': 'password',
            'JSON': (lambda: 'data_fields' if model == 'data' else 'files')(),
            'INTEGER': 'text'
        }
        vidgets = []

        for field in fields:
            try:
                if 'id' in field['name']:
                    continue
                vidget = {
                    'name': field['name'],
                    'type': types_map[str(field['type'])],
                    'default_val': field['default']
                }
                vidgets.append(vidget)
            except KeyError:
                continue

        values = None
        if edit and id is not None:
            try:
                data = session.query(models[model]).filter_by(id=id).one()
            except Exception as e:
                session.close()
                print('adm/AdminMainHandler.get_fields(): '+\
                 'cannot get fields by "%s" model and id #%s:\n' % (model, id),\
                 e, file=sys.stderr)
                raise e
            values = data.item

            if model == 'catalog_element':
                values.update({'section_id': data.section_id})

        if model == 'catalog_element':
            try:
                sections = session.query(CatalogSectionModel).all()
            except Exception as e:
                session.close()
                print('adm/AdminMainHandler.get_fields(): '+\
                 'cannot get catalog sections list:\n',\
                 e, file=sys.stderr)
                raise e

            vidgets.append({
                'name':
                'section_id',
                'type':
                'select',
                'default_val':
                None,
                'list_values': [{
                    'title': x.title,
                    'value': x.id
                } for x in sections]
            })

        session.close()

        try:
            del values['create_date']
            del values['last_change']
            del values['_sa_instance_state']
            del values['password']
        except Exception:
            pass

        return self.json_response({
            'status': 'success',
            'fields_list': vidgets,
            'values_list': values
        })
Пример #50
0
    def to_frontend(self):
        vals = vars(self).copy()

        deprecated = [
            '_sa_instance_state', 'create_date', 'files', 'last_change'
        ]
        for item in deprecated:
            if item in vals:
                del vals[item]

        # get section alias
        session = Session()
        try:
            s = session.query(CatalogSectionModel.alias)\
             .filter_by(id=vals['section_id']).one()
        except Exception as e:
            session.close()
            print('CatalogItemModel.to_frontend():'+\
             ' cannot find section by "section_id"'+\
             ' for element #%d:\n' % int(vals['id']), e, file=sys.stderr)
            raise e
        session.close()

        # main image parse {{{

        main_image = None

        try:
            main_image = json.loads(vals['main_image'])
            if type(main_image) is not list:
                raise Exception('Must be an array')
        except Exception as e:
            main_image = None
            print('CatalogItemModel.to_frontend(): get "main_image" error:\n',\
             e, file=sys.stderr)

        if main_image and len(main_image) > 0 and 'filename' in main_image[0]:
            main_image = main_image[0]
            main_image[
                'filename'] = '/uploaded-files/%s' % main_image['filename']
        else:
            main_image = None

        vals['main_image'] = main_image

        # }}}

        # images parse {{{

        images = []

        try:
            images = json.loads(vals['images'])
            if type(images) is not list:
                raise Exception('Must be an array')
        except Exception as e:
            images = []
            print('CatalogItemModel.to_frontend(): get "images" error:\n',\
             e, file=sys.stderr)

        for item in images:
            if 'filename' not in item:
                continue
            item['filename'] = '/uploaded-files/%s' % item['filename']

        vals['images'] = images

        # }}}

        vals['detail_link'] = '/catalog/{0}/{1}.html'.format(
            s[0], vals['alias'])

        return vals
Пример #51
0
    def update_page(self, **kwargs):
        section = kwargs['section']
        del kwargs['section']
        id = kwargs['id']
        del kwargs['id']

        section_map = {
            'pages': StaticPageModel,
            'redirect': UrlMapping,
            'catalog_section': CatalogSectionModel,
            'catalog_element': CatalogItemModel,
            'data': NonRelationData
        }

        fields = db_inspector.get_columns(section_map[section].__tablename__)

        for item in (x for x in fields
                     if x['name'].startswith('is_') or x['name'].startswith(
                         'has_') or x['name'].startswith('inherit_seo_')):
            if item['name'] not in kwargs.keys():
                kwargs.update({item['name']: False})
            else:
                kwargs[item['name']] = True

        session = Session()

        try:
            data = session.query(section_map[section]).filter_by(id=id)
        except Exception as e:
            session.close()
            print('adm/AdminMainHandler.update_page(): '+\
             'cannot update page by "%s" section:\n' % str(section),\
             e, file=sys.stderr)
            raise e

        if section == 'redirect':
            permanent = (lambda: True
                         if kwargs['status'] == '301' else False)()
            from app.app import application
            counter = 0
            hndlr = application.handlers[0][1]
            for item in range(len(hndlr)):
                try:
                    if (hndlr[item].__dict__['kwargs']['url'] ==
                            data.one().new_url):
                        hndlr[item] = URLSpec(kwargs['old_url'] + '$',
                                              RedirectHandler,
                                              kwargs={
                                                  'url': kwargs['new_url'],
                                                  'permanent': permanent
                                              },
                                              name=None)
                except KeyError:
                    continue
        data.update(kwargs)

        try:
            session.commit()
        except Exception as e:
            session.close()
            print('adm/AdminMainHandler.update_page(): '+\
             'cannot commit update page by "%s" section:\n' % str(section),\
             e, file=sys.stderr)
            raise e

        session.close()

        return self.json_response({'status': 'success'})
Пример #52
0
	def to_frontend(self):
		vals = vars(self).copy()

		deprecated = ['_sa_instance_state', 'create_date', 'files', 'last_change']
		for item in deprecated:
			if item in vals:
				del vals[item]

		# get section alias
		session = Session()
		try:
			s = session.query(CatalogSectionModel.alias)\
				.filter_by(id=vals['section_id']).one()
		except Exception as e:
			session.close()
			print('CatalogItemModel.to_frontend():'+\
				' cannot find section by "section_id"'+\
				' for element #%d:\n' % int(vals['id']), e, file=sys.stderr)
			raise e
		session.close()

		# main image parse {{{

		main_image = None

		try:
			main_image = json.loads(vals['main_image'])
			if type(main_image) is not list:
				raise Exception('Must be an array')
		except Exception as e:
			main_image = None
			print('CatalogItemModel.to_frontend(): get "main_image" error:\n',\
				e, file=sys.stderr)

		if main_image and len(main_image) > 0 and 'filename' in main_image[0]:
			main_image = main_image[0]
			main_image['filename'] = '/uploaded-files/%s' % main_image['filename']
		else:
			main_image = None

		vals['main_image'] = main_image

		# }}}

		# images parse {{{

		images = []

		try:
			images = json.loads(vals['images'])
			if type(images) is not list:
				raise Exception('Must be an array')
		except Exception as e:
			images = []
			print('CatalogItemModel.to_frontend(): get "images" error:\n',\
				e, file=sys.stderr)

		for item in images:
			if 'filename' not in item:
				continue
			item['filename'] = '/uploaded-files/%s' % item['filename']

		vals['images'] = images

		# }}}

		vals['detail_link'] = '/catalog/{0}/{1}.html'.format(s[0], vals['alias'])

		return vals
Пример #53
0
	def get_fields(self, model=None, edit=False, id=None):
		session = Session()
		
		models = {
			'pages': StaticPageModel,
			'redirect': UrlMapping,
			'catalog_section': CatalogSectionModel,
			'catalog_element': CatalogItemModel,
			'accounts': User,
			'data': NonRelationData
		}
		
		fields = db_inspector.get_columns(
			models[model].__tablename__
		)
		
		# TODO :: refactoring
		types_map = {
			'BOOLEAN': 'checkbox',
			'TEXT': 'html',
			'VARCHAR(4096)': 'text',
			'VARCHAR(8192)': 'text',
			'VARCHAR(1024)': 'text',
			'VARCHAR(5000)': 'password',
			'JSON': (
				lambda: 'data_fields'
					if model == 'data'
					else 'files'
				)(),
			'INTEGER': 'text'
		}
		vidgets = []
		
		for field in fields:
			try:
				if 'id' in field['name']:
					continue
				vidget = {
					'name': field['name'],
					'type': types_map[str(field['type'])],
					'default_val': field['default']
				}
				vidgets.append(vidget)
			except KeyError:
				continue
		
		values = None
		if edit and id is not None:
			try:
				data = session.query(
					models[model]).filter_by(id=id).one()
			except Exception as e:
				session.close()
				print('adm/AdminMainHandler.get_fields(): '+\
					'cannot get fields by "%s" model and id #%s:\n' % (model, id),\
					e, file=sys.stderr)
				raise e
			values = data.item
			
			if model == 'catalog_element':
				values.update({'section_id': data.section_id})
		
		if model == 'catalog_element':
			try:
				sections = session.query(CatalogSectionModel).all()
			except Exception as e:
				session.close()
				print('adm/AdminMainHandler.get_fields(): '+\
					'cannot get catalog sections list:\n',\
					e, file=sys.stderr)
				raise e
			
			vidgets.append({
				'name': 'section_id',
				'type': 'select',
				'default_val': None,
				'list_values': [{
					'title': x.title,
					'value': x.id} for x in sections]
				})
		
		session.close()
		
		try:
			del values['create_date']
			del values['last_change']
			del values['_sa_instance_state']
			del values['password']
		except Exception:
			pass
		
		return self.json_response({
			'status': 'success',
			'fields_list': vidgets,
			'values_list': values
		})
Пример #54
0
	def update_page(self, **kwargs):
		section = kwargs['section']
		del kwargs['section']
		id = kwargs['id']
		del kwargs['id']
		
		section_map = {
			'pages': StaticPageModel,
			'redirect': UrlMapping,
			'catalog_section': CatalogSectionModel,
			'catalog_element': CatalogItemModel,
			'data': NonRelationData
		}
		
		fields = db_inspector.get_columns(
			section_map[section].__tablename__
			)
		
		for item in (x for x
			in fields
				if x['name'].startswith('is_')
					or x['name'].startswith('has_')
						or x['name'].startswith('inherit_seo_')):
			if item['name'] not in kwargs.keys():
				kwargs.update({ item['name']: False })
			else:
				kwargs[item['name']] = True
		
		session = Session()
		
		try:
			data = session.query(
				section_map[section]
			).filter_by(id=id)
		except Exception as e:
			session.close()
			print('adm/AdminMainHandler.update_page(): '+\
				'cannot update page by "%s" section:\n' % str(section),\
				e, file=sys.stderr)
			raise e
		
		if section == 'redirect':
			permanent = (
				lambda: True if kwargs['status'] == '301' else False
				)()
			from app.app import application
			counter = 0
			hndlr = application.handlers[0][1]
			for item in range(len(hndlr)):
				try:
					if(hndlr[item].__dict__['kwargs']['url'] == data.one().new_url):
						hndlr[item] = URLSpec(
							kwargs['old_url'] + '$',
							RedirectHandler,
							kwargs={
								'url': kwargs['new_url'],
								'permanent': permanent
								},
							name=None)
				except KeyError:
					continue
		data.update(kwargs)
		
		try:
			session.commit()
		except Exception as e:
			session.close()
			print('adm/AdminMainHandler.update_page(): '+\
				'cannot commit update page by "%s" section:\n' % str(section),\
				e, file=sys.stderr)
			raise e
		
		session.close()
		
		return self.json_response({'status': 'success'})