Beispiel #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'})
Beispiel #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'})
Beispiel #3
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'})
Beispiel #4
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'})
Beispiel #5
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'})
Beispiel #6
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'})
Beispiel #7
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'})
Beispiel #8
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'})
Beispiel #9
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
		)
Beispiel #10
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
		)
Beispiel #11
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='АвтоЛюкс: заказ звонка'
		)
Beispiel #12
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='АвтоЛюкс: заказ звонка'
		)
Beispiel #13
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'})
Beispiel #14
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'})