Beispiel #1
0
    def modify_blog(cls, blog_id, title, tag, category, hide, content):
        blog = cls.get(cls.id == blog_id)
        blog.title = title
        if hide == 'False':
            blog.hide = False
        else:
            blog.hide = True
        blog.content_md = content
        blog.content_html = md2html(content)
        blog.save()

        check_tag = Tags.has_tag(tag)
        blogtags = BlogTags.get(BlogTags.blog_id == blog.id)
        if check_tag:
            blogtags.tags_id = check_tag.id
        else:
            tag = Tags.create(tag=tag)
            blogtags.tags_id = tag.id
        blogtags.save()

        check_category = Category.has_category(category)
        blogcategory = BlogCategory.get(BlogCategory.blog_id == blog.id)
        if check_category:
            blogcategory.category_id = check_category.id
        else:
            category = Category.create(category=category)
            blogcategory.category_id = category.id
        blogcategory.save()
Beispiel #2
0
    def setUpClass(cls):
        try:
            cls.client = webdriver.Chrome('./chromedriver')
        except Exception:
            pass

        if not cls.client:
            return

        cls.app = create_app('test')
        cls.app_context = cls.app.app_context()
        cls.app_context.push()

        # 禁止日志
        import logging
        logger = logging.getLogger('werkzeug')
        logger.setLevel('ERROR')

        db.create_all()
        Role.insert_roles()
        Category.insert_categories()
        FakeUtil.generate_fake_users(10)
        FakeUtil.generate_fake_articles(10)

        admin_role = Role.query.filter_by(name='Administrator').first()
        admin = User(email='*****@*****.**',
                     username='******',
                     password='******',
                     role=admin_role,
                     confirmed=True)
        db.session.add(admin)
        db.session.commit()

        threading.Thread(target=cls.app.run).start()
Beispiel #3
0
def update(category_id):
    try:
        data = request.form.to_dict()
        temp_data = data
        ancestorpath = []
        data = dict((k, v) for (k, v) in data.iteritems() if len(str(v).strip()) > 0)
        category = Category.objects.get(id=str(category_id))  # cha
        if category is None:
            return abort(400)
        update_map = dict([("set__" + key, value) for key, value in data.items()])
        if update_map.has_key("set__parent"):
            if update_map["set__parent"] == category_id:
                return abort(400)
            parent = Category.objects(id=str(update_map["set__parent"])).first()  # con
            if parent is None:
                return abort(400)
            ancestorpath = parent.ancestors
            ancestorpath.append(parent)
            """
            Check category in child's ancestors when update a category with its parent is its descendant
            If category in child's ancestors return True
            else return False
            """

            def ancestors(parent, child):
                if parent.id == child.id:
                    return True
                if child.parent is None:
                    return False
                return ancestors(parent, child.parent)

            if ancestors(category, parent):
                return abort(400)

        if temp_data.has_key("parent"):
            if len(str(temp_data["parent"]).strip()) == 0:
                update_map["set__parent"] = None
        update_map["set__ancestors"] = ancestorpath
        category.update(**update_map)
        category.reload

        # get all child
        children = Category.objects(ancestors__contains=category.id)

        def getpath(path, child):
            if child.parent is None:
                return path
            path.insert(0, child.parent)
            return getpath(path, child.parent)

        # update ancestors in child
        for child in children:
            child_path = getpath([], child)
            child.ancestors = child_path
            child.save()
        rebuilt_category_product()
        return render.template("admin/category/detail.html", category=category.reload()), 200
    except Exception as e:
        print e
        abort(400)
Beispiel #4
0
    def post(self):
        screen = Screen_Layout()
        # screen.key=ndb.Key('Screen_Layout', int(request.form['id']))
        screen.name = request.form['name']
        screen.client_id = ndb.Key('Client', int(request.form['client_id']))
        screen.location = request.form['location']
        screen.max_rows = int(request.form['max_rows'])
        screen.max_columns = int(request.form['max_columns'])
        screen.seats = list(json.loads(request.form['seats'].decode('ascii','ignore')))
        # max_rows = int(request.form['max_rows'])
        # max_columns = int(request.form['max_columns'])
        # i = 1
        # j = 1
        # while (i <= max_rows):
        #     while (j <= max_columns):
        #         seats.append({'row': i, 'column': j})
        #         j = j + 1
        #     j = 1
        #     i = i + 1
        # screen.seats = seats
        result = screen.put()

        # the below paragraph should be deleted later
        category1 = Category(id=screen.key.id() + 23, seats=screen.seats, screen_id=screen.key,
                             name="something something")
        category1.put()
        # the above paragraph should be deleted later

        if result:
            client = screen.client_id.get()
            client.screen_list_id.append(result.id())
            client.put()
        return jsonify({'id': result.id(), 'seats': screen.seats, 'message': "Success"})
Beispiel #5
0
    def add_favorite_substitute(sql, message, category, product, substitute):
        """
        Method to save a favorite in the database
        arg : SQL - Global instance of the sql class
              message - Global instance of the Message object
              category of the product/substitute
              Instance of a product
              Instance of a substitute

        return an instance of the saved Favorite if save performed
        else None
        """
        id_product = ""
        id_category = ""

        # Retrieve the id of the category in the database
        category_from_db = sql.select_first_row_one_attribute_where(
            "category", "id", ("id", product.id_category))
        # if the category was not found in the database
        if category_from_db is None:
            message.not_in_db("category : " + category)
            category = Category(message, category)
            # save the category in the database
            id_category = category.save_in_db(sql)
        else:
            id_category = category_from_db[0]
        # Retrieve the id of the product in the database
        product_from_db = sql.select_first_row_one_attribute_where(
            "product", "id", ("name", product.name))
        # if the category was not found in the database
        if product_from_db is None:
            message.not_in_db("product : " + product.name)
            # save the product in the database
            id_product = product.save_product_in_db(sql, id_category)
        else:
            id_product = product_from_db[0]

        id_substitute = ""
        # Retrieve the id of the substitute in the database
        substitute_from_db = sql.select_first_row_one_attribute_where(
            "product", "id", ("name", substitute.name))
        # if the substitute was not found in the database
        if substitute_from_db is None:
            message.not_in_db("substitute : " + substitute.name)
            # save the substitute in the database
            id_substitute = substitute.save_product_in_db(sql, id_category)
        else:
            id_substitute = substitute_from_db[0]

        # Save the favorite in the database
        substitute_dic = {
            "id_product": id_product,
            "id_substitute": id_substitute
        }
        id_favorite = sql.insert("substitute", **substitute_dic)
        if id_favorite > 0:
            return Favorite(message, substitute.name, id_product,
                            id_substitute)
        else:
            return None
Beispiel #6
0
def doEdit(id):
    cat = Category()
    a = (request.form.get('name'), id)
    ret = cat.edit(a)
    if ret > 0:
        return redirect('/category')
    return "Failed"
Beispiel #7
0
def restaurant_add_update_category():
    user = get_user()

    if (user):
        restaurant = Restaurant.get_from_id(user.restaurant_id)

        if (restaurant):
            name = get_header("name")
            id = get_header_int("id")

            if (name and len(name) <= 50):
                if (is_int(id)):
                    category = Category.get_from_id(restaurant, id)

                    if (category):
                        if (get_header("remove")):
                            category.remove()
                        else:
                            category.name = name
                            get_session().commit()

                        return "true"
                    else:
                        abort(404)
                else:
                    Category.add(name, restaurant)

                    return "true"
            else:
                abort(400)

        else:
            abort(404)
    else:
        abort(404)
Beispiel #8
0
    def SetUp(self):
        """
		Запускается в начале каждого теста,
		создает пользователя для тестирования
		"""
        self.name, self.total_money = 'test Category', 1000000
        self.category = Category(self.name, self.total_money)
Beispiel #9
0
    def post(self, *args, **kwargs):
        category_list = self.get_angular_argument('category_list')

        if not category_list:
            return

        Category.update_position(category_list)
 def setUp(self):
     """
     Extend the BaseTest setUp method by setting up
     two categories and three questions
     """
     super(TestQuestion, self).setUp()
     with self.app_context:
         self.c_1 = Category(type="Test Category 1")
         self.c_1.insert_record()
         self.c_2 = Category(type="Test Category 2")
         self.c_2.insert_record()
         self.q_1 = Question(
             question="Test Question 1?",
             answer="Test Answer 1",
             difficulty=1,
             category_id=self.c_1.id,
         )
         self.q_1.insert_record()
         self.q_2 = Question(
             question="Test Question 2?",
             answer="Test Answer 2",
             difficulty=2,
             category_id=self.c_2.id,
         )
         self.q_2.insert_record()
         self.q_3 = Question(
             question="Test Question 3?",
             answer="Test Answer 3",
             difficulty=3,
             category_id=self.c_2.id,
         )
         self.q_3.insert_record()
Beispiel #11
0
 def get(self,key):
     user = User()
     
     categroy = Category()       
     user_keys = user.allKey()
     category_keys = categroy.allKey()
     
     _data_user =  user.all(user_keys)
     _data_category = categroy.all(category_keys)        
     data = {}
     if key:
         board = Board()
         board.data = board.get(key)
         data['title']       = board.data['title']
         data['key']         = board.data['key']
         data['user']        = board.data['user']
         data['category']    = board.data['category']
         data['createTime']    = board.data['createTime']
         data['follow']    = board.data['follow']
     else:            
         data['title']       = ''
         data['key']         = ''
         data['user']        = ''
         data['category']    = ''            
     
     self.render('manager/board_new.html',data = data,data_user = _data_user,data_category = _data_category)
Beispiel #12
0
    def _set_tabs(self):
        """
        Метод заполнения полей таблицы Тест
        """
        category_1 = Category(name='Полуфабрикаты', is_active=True)
        category_2 = Category(name='Бакалея', is_active=True)
        category_3 = Category(name='Мороженое', is_active=True)

        product_1 = Products(name='Вареники(Фирменные)', title='ТМ Геркулес 400 гр',
                             price=542.01, quantity=12, is_active=True, category=category_1)
        product_2 = Products(name='Пельмени(Домашние)', title='ТМ Вкуснотеево 450 гр',
                             price=322.5, quantity=23, is_active=True, category=category_1)
        product_3 = Products(name='Колбаса(Докторская)', title='ТМ Доброе 500 гр',
                             price=420, quantity=15, is_active=True, category=category_2)
        product_4 = Products(name='Сосиски(Молочные)', title='ТМ Веселые 700 гр',
                             price=312.56, quantity=36, is_active=True, category=category_2)
        product_5 = Products(name='Пьяная вишня', title='ТМ Молочный берег 50 гр',
                             price=75, quantity=102, is_active=True, category=category_3)
        product_6 = Products(name='Пломбир класический', title='ТМ Молочный берег 100 гр',
                             price=80, quantity=12, is_active=True, category=category_3)
        session = self.__session()
        session.add_all([category_1, category_2, category_3])
        session.add_all(
            [product_1, product_2, product_3, product_4, product_5, product_6])

        session.commit()
        session.close()
Beispiel #13
0
def index():
    #khoi tao lop:
    cat = Category()
    #goi ham

    a = cat.getCategories()

    return render_template('category/index.html', arr = a)
Beispiel #14
0
def delete(id):

    cat = Category()

    ret = cat.delete(id)
    if ret > 0:
        return redirect('/category')
    return 'Failed'
Beispiel #15
0
def index():
    cat = Category()
    brd = Brand()
    arr = Product()
    a = arr.getProducts()
    b = brd.getBrands()
    c = cat.getCategories()
    return render_template('home/index.html', arr=a, brr=b, crr=c)
Beispiel #16
0
def delall():
    a = request.form.getlist('a')
    cat = Category()
    b = []
    for i in a:
        b.append((i, ))
    ret = cat.deletes(b)
    return redirect('/category')
Beispiel #17
0
def add():
    cat = Category()
    id = randint(0, 999999)
    name = request.form.get("name")
    ret = cat.add((id, name))
    if ret > 0:
        return jsonify({"id": id, "name": name})
    return "Failed"
Beispiel #18
0
 def get(self,key):
     uri = self.request.uri
     request = {}
     pin = Pin()
     
     pin_keys = pin.getByKeyValues("board",key)
     pin_count = len(pin_keys)
     
     query = {}
     query['q']         = "board:%s" % key    
             
     query['start']  = "0"
     query['rows']   = globalSetting['max_index_pin_rows']
     query['sort']   = "createTime"
     
     if "page" in uri:
         request = urldecode(uri)
         page = int(request['page'])
         query['start']  = query['rows']*page
         if pin_count < query['rows']*page:
             return ''
     
     pin_data = pin.solr(query)
     print len(pin_data)
     
     marks_dict = pin.formatPins(pin_data)        
     
     if request:
         #print request['callback']
         #print request['page']            
         callback_result = {
                         'filter':'pin:index',
                         'pins':marks_dict
                         }
         
         callback_response = "%s(%s)" % (request['callback'],json.dumps(callback_result))
         self.set_header("Content-Type", "text/html; charset=utf-8")            
         return self.write(callback_response)
     else:
         marks = ''            
         for _mark_t in marks_dict:                
             marks = self.render_string('mark.html',mark=_mark_t)+marks
         board = Board()
         user = User()
         category = Category() 
  
         board_data = board.get(key)
         
         b_user = user.getDetail(board_data['user'])
         b_category = category.get(board_data['category'])
         b_keys = board.getByKeyValues("user", board_data['user'])
         
         if key in b_keys:
             b_keys.remove(key)
             
         b_boards = board.all(b_keys)
     
         self.render('board_pins_list.html',f_board = self.formatFollowBoardData(key), b_boards= b_boards,b_category = b_category,b_user=b_user,user=self.currentUserInfo(),board = board.get(key),marks=marks)
Beispiel #19
0
def detail(id):
    cat = Category()
    brand = Brand()
    pro = Product()
    a = pro.getProductById(id)
    b = brand.getBrands()
    c = cat.getCategories()
    d = pro.getProductsRelation(id)
    return render_template('home/detail.html', u=a, crr=c, brr=b, arr=d)
Beispiel #20
0
def brand(id):
    cat = Category()
    brand = Brand()
    pro = Product()
    a = pro.getProductsByBrand(id)
    b = brand.getBrands()
    c = cat.getCategories()
    d = brand.getBrandById(id)
    return render_template('home/brand.html', arr=a, crr=c, brr=b, title=d[1])
Beispiel #21
0
def deploy():
    """部署"""
    from flask_migrate import upgrade

    # 迁移数据库到最新版本
    upgrade()

    Role.insert_roles()
    Category.insert_categories()
Beispiel #22
0
    def setUp(self):
        self.app = create_app('test')
        self.app_context = self.app.app_context()
        self.app_context.push()
        self.client = self.app.test_client(use_cookies=True)

        db.create_all()
        Role.insert_roles()
        Category.insert_categories()
def create_category(data):
    name = data.get('name')
    category_id = data.get('id')

    category = Category(name)
    if category_id:
        category.id = category_id

    db.session.add(category)
    db.session.commit()
Beispiel #24
0
 def post(self):
     iKwargs = request.form.to_dict()
     categorys = CategoryModel.getAllData()
     names = [category['name'] for category in categorys]
     category = CategoryModel()
     if iKwargs['name'] in names:
         raise ModelRepeat(iKwargs['name'])
     data = {'name': iKwargs['name'], 'articleList': {}}
     category.create(data)
     return data
Beispiel #25
0
	def get(self,cat_key):	
		if cat_key == 'All':
			self.redirect('/')
		else:
			uri = self.request.uri
			request = {}
			pin = Pin()
			
			pin_keys = pin.getByCat(cat_key)
			pin_count = len(pin_keys)
			
			query = {}
			query['q'] 		= "category:%s" % cat_key
					
			query['start']  = "0"
			query['rows']   = globalSetting['max_index_pin_rows']
			query['sort']   = "createTime"
			
			if "page" in uri:
				request = urldecode(uri)
				print request
				page = int(request['page'])
				query['start']  = query['rows']*page
				if pin_count < query['rows']*page:
					return ''
			
			pin_data = pin.solr(query)
			#print len(pin_data)
			marks_dict = pin.formatPins(pin_data)	
			
			if request:
				#print request
				callback_result = {
								'filter':'pin:index',
								'pins':marks_dict
								}
				
				callback_response = "%s(%s)" % (request['callback'],json.dumps(callback_result))
				self.set_header("Content-Type", "text/html; charset=utf-8")			
				return self.write(callback_response)
			else:
				marks = ''			
				for _mark_t in marks_dict:				
					marks = self.render_string('mark.html',mark=_mark_t)+marks
				if marks == '':
					marks = """
					<div class="pin category wfc isotope-item" style="margin-bottom: 15px; position: absolute; left: 0px; top: 0px; -webkit-transform: translate3d(0px, 0px, 0px); ">
					NO PINS
					</div>
					"""
				category = Category()
				cats = category.getCats()
				
				self.render('index.html',user=self.currentUserInfo(),marks=marks,cats = cats,urlname = cat_key)		
Beispiel #26
0
    def fill_categories(self):
        records = self._parse_xml()
        categories = set()

        for record in records:
            category_names = record.getElementsByTagName('category')[0].firstChild.data
            for name in category_names.split(', '):
                if name not in categories:
                    categories.add(name)
                    category = Category(name=name)
                    category.save_to_db()
 def setUp(self):
     """
     Extend the BaseTest setUp method by setting up
     two categories
     """
     super(TestCategory, self).setUp()
     with self.app_context:
         self.c_1 = Category(type="Test Category 1")
         self.c_1.insert_record()
         self.c_2 = Category(type="Test Category 2")
         self.c_2.insert_record()
Beispiel #28
0
 def setUp(self):
     """
     Extend the BaseTest setUp method by inserting  two
     categories into the database.
     """
     super(TestCategoryResource, self).setUp()
     with self.app_context:
         self.c_1 = Category(type="Test Category 1")
         self.c_1.insert_record()
         self.c_2 = Category(type="Test Category 2")
         self.c_2.insert_record()
    def get_category(self):
        """Add the categories to the list"""
        all_category = []
        for category in liste_de_catégories:
            cat = Category()
            cat.name = category
            get_products = ProductDownloader()
            products = get_products.product_by_category(category)
            cat.products = get_products.filter_product(products)
            all_category.append(cat)

        return all_category
Beispiel #30
0
 def POST(self):
     category_name = web.input().get('category_name', None)
     if category_name:
         category_name = category_name.strip()
     category_id = web.input().get('category_id', None)
     category = Category()
     if category_id:
         category.id = category_id
     if category_name:
         category.name = category_name
     category.create_time = datetime.datetime.now()
     mu.update_category(category)
     raise web.seeother('/manage/category')
Beispiel #31
0
 def put(self, id):
     '''This method receives an ID from an category and updates the category'''
     if Commons.isValidId(id):
         category = Category.objects(id=id)
         if Commons.checkIfNotExists(category):
             return Commons.notFound('category')
         if auth.isAuthorized(category[0].userId):
             params = Commons.filterQueryParams(self.reqparse.parse_args())
             Category.objects(id=id).update_one(upsert=False,
                                                write_concern=None,
                                                **params)
             return make_response(jsonify({'data': 'Category updated'}),
                                  201)
     return auth.unauthorized()
Beispiel #32
0
    def post(self):
        # Got client ID from environ
        user_id = request.environ['USER_ID']
        client_id = user_id.get().detail_id

        print request.json['id']
        screen = Screen_Layout.get_by_id(request.json['id'])
        screen.name = request.json['name']
        prev_client_id = screen.client_id
        print client_id
        if prev_client_id != client_id:  # Later this is to be changed with token.
            return jsonify({"code": 400, "message": "Not authorized."})
        screen.location = request.json['location']

        prev_rows = screen.max_rows
        prev_cols = screen.max_columns

        if prev_rows != int(request.json['max_rows']) or prev_cols != int(
                request.json['max_columns']):
            screen.max_rows = int(request.json['max_rows'])
            screen.max_columns = int(request.json['max_columns'])
            # Deleting the categories of a seat after changing the screen structure.
            options = ndb.QueryOptions(keys_only=True)
            prev_categories = Category.query().filter(
                Category.screen_id == ndb.Key('Screen_Layout',
                                              request.json['id'])).fetch(
                                                  options=options)
            ndb.delete_multi(prev_categories)
            # We should add the new seat list for new seat grid and new categories for the updated Layout..
            seats = []
            categories = request.json['categories']
            print categories
            try:
                for each in categories:
                    category = Category()
                    category.screen_id = ndb.Key('Screen',
                                                 int(request.json['id']))
                    category.name = each['name']
                    category.seats = each['seats']
                    map(lambda seat: seats.append(seat), each['seats'])
                    category.put(
                    )  # Create categories for seat for a particular screen.
                # Adding seats for the screen fetched from categories
                screen.seats = seats
                res = screen.put()
                return jsonify({
                    "code":
                    200,
                    "id":
                    res.id(),
                    "message":
                    "Success changed layout and other informations."
                })
            except:
                return jsonify({"code": 500, "message": "server error"})
        return jsonify({
            "code": 200,
            "message": "Success changed some minor informations."
        })
Beispiel #33
0
def index(p=1):
    cat = Category()
    brand = Brand()
    pro = Product()
    a = pro.getProductsForHome(p, 8)
    b = brand.getBrands()
    c = cat.getCategories()
    total = pro.homeCount()
    n = ceil(total / 8)
    return render_template('home/index.html',
                           arr=a,
                           crr=c,
                           brr=b,
                           title="Mobile Store",
                           n=n)
def create_categories():
    category1 = Category(id=1, name="Balcony", screen_id=ndb.Key(Screen_Layout, 1),
                         seats=[{'row': 2, 'column': 1}, {'row': 2, 'column': 2}])
    category2 = Category(id=2, name="Normal", screen_id=ndb.Key(Screen_Layout, 1),
                         seats=[{'row': 1, 'column': 1}, {'row': 1, 'column': 2}])
    category3 = Category(id=3, name="Normal", screen_id=ndb.Key(Screen_Layout, 2),
                         seats=[{'row': 1, 'column': 1}, {'row': 1, 'column': 2}, {'row': 2, 'column': 1},
                                {'row': 2, 'column': 2}])
    category4 = Category(id=4, name="Normal", screen_id=ndb.Key(Screen_Layout, 3),
                         seats=[{'row': 1, 'column': 1}, {'row': 1, 'column': 2}, {'row': 2, 'column': 1},
                                {'row': 2, 'column': 2}])
    category5 = Category(id=5, name="Premium", screen_id=ndb.Key(Screen_Layout, 4),
                         seats=[{'row': 1, 'column': 1}, {'row': 1, 'column': 2}, {'row': 2, 'column': 1},
                                {'row': 2, 'column': 2}])
    ndb.put_multi([category1, category2, category3, category4, category5])
Beispiel #35
0
def update_item_in_category(new_item, category_id, item_id):
    # Check existences of category and item
    category = Category.find_by_id(category_id)
    if not category:
        raise RecordNotFoundError('category', category_id)
    item = category.items.filter_by(id=item_id).first()
    if not item:
        raise ItemNotFoundError(item_id)

    # Check permission
    if item.user.id != get_jwt_identity():
        raise ForbiddenError()

    # Save title of item for notification
    old_title = item.title

    # Check existences of item title
    title = new_item.title
    old_item = Item.find_by_title(title)
    if old_item and old_item.id != item_id:
        raise DuplicateValueError('item', 'title', title)

    # Update final result
    item.update_from_copy(new_item)
    item.save_to_db()
    return message('Item "{}" was updated.'.format(old_title))
Beispiel #36
0
    def select_favorite_substitute(self, text):
        """
            Method used when cb_favorite_substitutes is activated
            Attributes :receive the Actual text in the combobox

            Select Database as source an retrieve :
            - category
            - product
            - substitute
            from the database.
            Set all combobox and table according to selected object
        """
        if len(self.favorite_substitutes) > 0:
            favorite_substitute = next(
                (x for x in self.favorite_substitutes if x.name == text), None)
            product, substitute = favorite_substitute.get_favorite(self.sql)

            if product is not None and substitute is not None:
                widgets.change_combobox_index_from_text(
                    self.ui.cb_source, "DataBase")
                self.select_source(self.ui.cb_source.currentText())

                category_name = Cat.get_name_from_id(self.sql,
                                                     product.id_category)
                widgets.change_combobox_index_from_text(
                    self.ui.cb_category, category_name)
                self.select_category()

                widgets.change_combobox_index_from_text(
                    self.ui.cb_product, product.name)
                self.select_product(product.name)

                widgets.change_combobox_index_from_text(
                    self.ui.cb_substitute, substitute.name)
                self.select_substitute(substitute.name)
    def get(self):
        loginTitle = ""
        loginURL = ""
        user = users.get_current_user()
        if user:
            loginTitle = "logout"
            loginURL= users.create_logout_url('/')
        else:
            loginTitle = "login"
            loginURL= users.create_login_url('/')

        photos = {}
        categories = Category.query().order(Category.categoryName)

        for category in categories:
            photos[category.key] = category.picture.get()

        templateVars = {
                        "title" : "Manage Categories",
                        "loginURL" : loginURL,
                        "loginTitle": loginTitle,
                        "categories": categories,
                        "photos": photos
                        }

        self.render_template("/templates/adminCategories.html", templateVars)
Beispiel #38
0
	def get(self):
		uri = self.request.uri
		request = {}
		pin = Pin()
		
		pin_keys = pin.getByCat('All')
		pin_count = len(pin_keys)
		
		query = {}
		query['q'] 		= "public:1"				
		query['start']  = "0"
		query['rows']   = globalSetting['max_index_pin_rows']
		query['sort']   = "createTime"
		
		if "page" in uri:
			request = urldecode(uri)
			page = int(request['page'])
			query['start']  = query['rows']*page
			#If pin_count < query['rows']*page:
			#	return ''
		
		pin_data = pin.solr(query)
		#print len(pin_data)		
		marks_dict = pin.formatPins(pin_data)
		
		if request:
			#print request				
			callback_result = {
							'filter':'pin:index',
							'pins':marks_dict
							}
			
			callback_response = "%s(%s)" % (request['callback'],json.dumps(callback_result))
			self.set_header("Content-Type", "text/html; charset=utf-8")			
			self.write(callback_response)
		else:			
			marks = ''			
			for _mark_t in marks_dict:				
				marks = self.render_string('mark.html',mark=_mark_t)+marks
			
			dump(marks)
			category = Category()
			cats = category.getCats()
			dump(cats)
			cat_key = 'All'
			
			self.render('index.html',user=self.currentUserInfo(),marks=marks,cats = cats,urlname = cat_key)		
Beispiel #39
0
def detail(category_id):
    try:
        category = Category.objects(id=str(category_id)).first()
        if category is None:
            return abort(404)
        return render.template("admin/category/detail.html", category=category)
    except Exception, e:
        abort(404)
Beispiel #40
0
def user_delete():
    try:
        id = request.form['id'].split(',')
    except KeyError:
        return error(400, u'参数错误')
    if not Category.delete(id):
        return error(10020, 'delete failed')
    return 'delete ok'
Beispiel #41
0
def category_retrieve():
    id = request.args.get('id', 0)
    if id:
        category = Category.get(id)
        if not category:
            return error(404, 'category not exist')
        return category

    # start = request.args.get('start', 0)
    # limit = int(request.args.get('limit', PAGE_LIMIT))
    # category还要start??, 
    data = {}
    data['start'] = 0
    data['data'] = Category.get_all()
    data['count'] = len(data['data'])

    return data
Beispiel #42
0
def rebuilt_category_product():
    Category_Product.objects().delete()
    categories = Category.objects()
    for category in categories:
        product_of_categorys = Product.objects(category=category.id)
        bulk = []
        for product_of_category in product_of_categorys:
            bulk.append(Category_Product(product=product_of_category.id, category=category.id))
        if len(bulk) > 0:
            Category_Product.objects.insert(bulk)
        children = Category.objects(ancestors__contains=category.id)
        for child in children:
            product_of_childs = Product.objects(category=child.id)
            bulk = []
            for product_of_child in product_of_childs:
                bulk.append(Category_Product(product=product_of_child.id, category=category.id))
            if len(bulk) > 0:
                Category_Product.objects.insert(bulk)
Beispiel #43
0
def category_create():
    try:
        name = request.form['name']
    except KeyError:
        return error(400, u'参数错误')
    category = Category.create(**locals())
    if not category:
        return error(100021, 'create category failed')
    return category
Beispiel #44
0
def category_update():
    try:
        name = request.form['name']
        id = request.form['id']
    except KeyError:
        return error(400, u'参数错误')
    category = Category.update(**locals())
    if not category:
        return error(10022, 'update category failed')
    return category
Beispiel #45
0
	def put(self, cat_id):
		form = ApiCategoryForm(request.form)
		if form.validate():
			c = Category.get(cat_id)
			if c.user_id != session['user_id']:
				return jsonify({'code': 2, 'message': 'has no permission to modify the category'})
			else:
				form.fill_data_to_instance(c)
				return jsonify(code=0, data=c.json)
		return jsonify({'code': 1, 'message': form.errors})
Beispiel #46
0
    def get_blog_detail(cls, blog_id):
        blog = cls.get(cls.id == blog_id)

        blogtags = BlogTags.get(BlogTags.blog_id == blog.id)
        tag = Tags.get(Tags.id == blogtags.tags_id).tag

        blogcategory = BlogCategory.get(BlogCategory.blog_id == blog_id)
        category = Category.get(Category.id == blogcategory.category_id).category

        return blog, tag, category
Beispiel #47
0
 def get(self, cid):
     if not cid or not Category.get(cid):
         abort(404)
     if cid == 1:
         return redirect(url_for('main.home'))
     news_header = News.get_by_category(cid, order='create_time desc', start=0, limit=7)
     news_latest = News.get_by_category(cid, order='create_time desc', start=7)
     news_popular = News.get_by_category(cid, order='read_count desc', start=0)
     loginform = LoginForm()
     regform = RegisterForm()
     return render_template('index.html', **locals())
    def post(self):
        categoryName = self.request.get('categoryName')
        photoName = self.request.get('photoName')

        #get the photo specified by the user
        photo = File.query(File.file_name==photoName.upper()).get()

        #check to see if a category with that name already exists
        existingCategory = Category.query(Category.categoryName==categoryName).get()

        if existingCategory:
            #if an category with that name already exists, then update the information with the form data
            existingCategory.categoryName=categoryName
            existingCategory.picture=photo.key
            existingCategory.uploaded_by=users.get_current_user()

            existingCategory.put()
            existingCategory.add_to_search_index()
            message = "Successfully updated category record: " + existingCategory.categoryName

        else:
            #add a new category entry if no category with that name already exists
            category = Category(categoryName=categoryName, picture=photo.key, uploaded_by=users.get_current_user())
            category.put()
            category.add_to_search_index()
            message = "Successfully created category record: " + category.categoryName

        self.response.write(message)
    def post(self):
        categoryKeyString = self.request.get('deleteCategoryKey')

        #generate message
        category = Category.get_by_id(int(categoryKeyString))
        category.remove_from_search_index()
        message = "Successfully deleted category: " + category.categoryName

        #delete category
        categoryKey = category.key
        categoryKey.delete()

        self.response.write(message)
Beispiel #50
0
    def post(self, *args, **kwargs):
        """新建"""
        category_name = self.get_angular_argument('name')

        if not category_name:
            self.on_error(**ErrorCodeMessage.category_name_illegal)
            return

        category = Category.add(category_name)

        if not category:
            self.on_error(**ErrorCodeMessage.database_error)
            return

        self.on_success(category.to_dict())
    def get(self):
        template = JINJA_ENVIRONMENT.get_template('/templates/publicHome.html')

        photos = {}
        categories = Category.query().order(Category.categoryName)

        for category in categories:
            photos[category.key] = category.picture.get()

        templateVars = {
                        "title" : "Nick Michael's Fine Gallery",
                        "categories": categories,
                        "photos": photos}

        self.response.write(template.render(templateVars))
Beispiel #52
0
    def create_new_blog(cls, title, tag, category, hide, content):
        blog = cls.create(title=title,
                          content_md=content)

        if hide == 'False':
            blog.hide = False
        else:
            blog.hide = True
        blog.content_html = md2html(content)
        blog.save()

        check_tag = Tags.has_tag(tag)
        if check_tag:
            BlogTags.create(blog_id=blog.id, tags_id=check_tag.id)
        else:
            tag = Tags.create(tag=tag)
            BlogTags.create(blog_id=blog.id, tags_id=tag.id)

        check_category = Category.has_category(category)
        if check_category:
            BlogCategory.create(blog_id=blog.id, category_id=check_category.id)
        else:
            category = Category.create(category=category)
            BlogCategory.create(blog_id=blog.id, category_id=category.id)
Beispiel #53
0
    def post(self, *args, **kwargs):
        category_id = self.get_angular_argument('id')

        if not category_id:
            self.on_error(**ErrorCodeMessage.category_not_exists)
            return

        category = Category.init_from_category_id(category_id)

        if not category:
            self.on_error(**ErrorCodeMessage.category_not_exists)
            return

        if category.recover():
            self.on_success()
        else:
            self.on_error(**ErrorCodeMessage.database_error)
Beispiel #54
0
def add_category():
    status_code = 0
    error_msg = 'error'
    try:
        ins = Category()
        ins.title = getparms('title','new category')
        ins.sort_num = int(getparms('sort_num','0'))
        ins.join_date = datetime.now()
        ins.status = 1
        ins.save()
        status_code = 1
        error_msg = '成功'
    except Exception as e:
        error_msg = '出错了 %r' % e
    result = {'status_code':status_code,'msg':error_msg }
    return  jsonify(result)
Beispiel #55
0
    def delete(self, category_id=0, *args, **kwargs):
        """删除"""
        category_id = category_id

        if not category_id:
            self.on_error(**ErrorCodeMessage.category_not_exists)
            return

        category = Category.init_from_category_id(category_id)

        if not category:
            self.on_error(**ErrorCodeMessage.category_not_exists)
            return

        if category.delete():
            self.on_success()
        else:
            self.on_error(**ErrorCodeMessage.database_error)
Beispiel #56
0
def delete(category_id):
    try:
        category = Category.objects.get(id=category_id)
        children = Category.objects(ancestors__contains=category.id)
        num = category.delete()

        def getpath(path, child):
            if child.parent is None:
                return path
            path.insert(0, child.parent)
            return getpath(path, child.parent)

        # update ancestors in child
        for child in children:
            child_path = getpath([], child)
            child.ancestors = child_path
            child.save()
        return render.template("admin/category/detail.html", category=category)
    except Exception:
        abort(404)
    def post(self):
        categoryKeyString = self.request.get('editCategoryKey')
        categoryID = int(categoryKeyString)
        categoryName = self.request.get('editCategoryName')
        photoName = self.request.get('editCategoryPhotoName')

        #get the photo specified by the user
        photo = File.query(File.file_name==photoName.upper()).get()

        #get the category based on the key and update all fields
        category = Category.get_by_id(categoryID)

        category.categoryName=categoryName
        category.picture=photo.key
        category.uploaded_by=users.get_current_user()

        category.put()
        category.add_to_search_index()

        message = "Successfully updated category record: " + category.categoryName
        self.response.write(message)
    def get(self):
        photos = {}
        categories = Category.query().order(Category.categoryName)

        for category in categories:
            photos[category.key] = category.picture.get()
        html = ""
        for category in categories:
            html+="""<tr>
                        <td>""" + category.categoryName + """</td>
                        <td>""" + photos[category.key].file_name + """</td>
                        <td>
                            <a data-toggle="modal"  href="#editCategoryModal" onclick="fillCategoryEditModalDefaults(""" + str(category.key.id()) + ", '" + category.categoryName + "', '" + photos[category.key].file_name + """');" class="btn btn-medium">
                                <span class="glyphicon icon-edit"></span>
                            </a>
                            <a data-toggle="modal" data-id=\"""" + str(category.key.id()) + """\" href="#deleteCategoryModal" class="open-deleteCategoryModal btn btn-medium">
                                <span class="glyphicon icon-remove"></span>
                            </a>
                        </td>
                    </tr>"""

        self.response.write(html)
Beispiel #59
0
def edit(category_id):
    try:
        category = Category.objects.get(id=category_id)
        categories = Category.objects()

        def is_can_be_parent(can_be_parent, can_be_child):
            def get_ancestors(list, child):
                if child is None:
                    return list
                if child.parent is not None:
                    list.append(child.parent.id)
                return get_ancestors(list, child.parent)

            """
            to check can_be_parent is child of can_be_child much get all child of can_be_child
            to get all child of can_be_child much check all category with each category as c has ancestors, 
            which has can_be_child => c is child of can_be_child
            if can_be_parent in list child of can_be_child return false
            """
            list_child_of_child = []
            for c in categories:
                list = []
                list = get_ancestors(list, c)
                if can_be_child.id in list:
                    list_child_of_child.append(c.id)
            if can_be_parent.id in list_child_of_child:
                return False
            if can_be_child.parent is not None:
                if can_be_child.parent.id == can_be_parent.id:
                    return True
            if can_be_child.id == can_be_parent.id:
                return False
            return True

        categories = filter(lambda can_be_parent: is_can_be_parent(can_be_parent, category), categories)
        return render.template("admin/category/edit.html", category=category, categories=categories)
    except Exception:
        abort(404, "404 does not exist")
Beispiel #60
0
    def put(self, *args, **kwargs):
        """改名"""
        category_name = self.get_angular_argument('name')
        category_id = self.get_angular_argument('id')

        if not category_id:
            self.on_error(**ErrorCodeMessage.category_not_exists)
            return

        category = Category.init_from_category_id(category_id)

        if not category:
            self.on_error(**ErrorCodeMessage.category_not_exists)
            return

        if not category_name:
            self.on_error(**ErrorCodeMessage.category_name_illegal)
            return

        if category.edit_name(category_name):
            self.on_success()
        else:
            self.on_error(**ErrorCodeMessage.database_error)