Exemplo n.º 1
0
def index(session):
    form = bottle.request.form

    if form.is_valid():
        i = form.hydrate_entity(Item())
        #associate any uploaded files:
        em = EntityManager()
        for f in em.find('File', {'session_id': session['session_id']}):
            f.session_id = None
            em.save('File', f)
            i.files.append(f)

        save_item(i, form.get_value('newTag'))

        return bottle.redirect('/items')        

    for item in form.formitems:
        if item.name == 'tagIds':
            item.select_list_items = [(str(t._id), t.name) for t in get_tags()]

    vd = common_view_data(session)
    vd.update({
        'form': form.get_html(row_class='form-group', submit_btn_class='btn btn-primary')
    })    

    return bottle.template('item.tpl', vd=vd)
Exemplo n.º 2
0
Arquivo: apps.py Projeto: iamcm/shared
def register():
    form = bottle.request.form
    em = EntityManager()

    #check email
    if len(em.find('User',{'email':form.get_value('email')})) > 0:
        form.errors.append('The Email is already in use on this site, please select a different one')

    #check username
    if len(em.find('User',{'username':form.get_value('username')})) > 0:
        form.errors.append('The Username is already in use on this site, please select a different one')

    print form.errors

    if form.is_valid():
        auth_service = AuthService(em)

        user = auth_service.create_user(form.get_value('email'), form.get_value('password'), form.get_value('username'),True)

        em.save('User', user)

        if getattr(settings, 'REGISTER_SUCCESS_URL', None):
            url = settings.REGISTER_SUCCESS_URL
        else:
            url = '/'

        return bottle.redirect(url)

    viewdata = {
        'form':form.get_html(row_class='form-group', submit_btn_class="btn btn-primary", submit_btn_text='Register', submit_container_class='')
    }
    return bottle.template('register.tpl', vd=viewdata)
Exemplo n.º 3
0
def index(id):

    if bottle.request.POST.get('description'):
        i = EntityManager().find_one_by_id('Image', id)
        i.description = bottle.request.POST.get('description')
        EntityManager().save('Image', i)

    return bottle.redirect('/admin/images')
Exemplo n.º 4
0
def index(id, bool):
    em = EntityManager()
    i = em.find_one_by_id('Image', id)
    i.isHomepagePic = bool == '1'

    em.save('Image', i)

    return '1'
Exemplo n.º 5
0
def index(session, tagid):
    em = EntityManager()
    tag = em.find_one_by_id('Tag', tagid)

    vd = common_view_data(session)
    vd.update({
        'form': TagForm(entity=tag).get_html(action='/tag', row_class='form-group', submit_btn_class='btn btn-primary')
    })

    return bottle.template('tag.tpl', vd=vd)
Exemplo n.º 6
0
def index(session):
    em = EntityManager()

    items = em.find('Item', sort=[('added', -1)])

    if bottle.request.GET.get('apikey'):
        bottle.response.content_type = 'text/json'
        return json.dumps([em.entity_to_json_safe_dict(i) for i in items])
    else:
        vd = common_view_data(session)
        vd.update({'items':items})
        return bottle.template('index.tpl', vd=vd)
Exemplo n.º 7
0
def index(session, itemid):
    em = EntityManager()
    
    item = em.find_one_by_id('Item', itemid)

    tags_select_items = [(str(t._id), t.name) for t in get_tags()]

    vd = common_view_data(session)
    vd.update({
        'form': ItemForm(tags_select_items, entity=item).get_html(form_id='form-add-item', action='/item', row_class='form-group', submit_btn_class='btn btn-primary')
    })

    return bottle.template('item.tpl', vd=vd)
Exemplo n.º 8
0
def index():
    n = bottle.request.POST.name

    if n:
        processed_ids = []

        if bottle.request.POST.get('id'):
            scheme = EntityManager().find_one_by_id('PaymentScheme', bottle.request.POST.id)
            existing_options_ids = [str(o._id) for o in EntityManager().find('PaymentOption', objfilter={'scheme_id':str(scheme._id)})]
        else:
            scheme = PaymentScheme()
            existing_options_ids = []

        scheme.name = n

        s = EntityManager().save('PaymentScheme', scheme)

        for opt in bottle.request.POST.getall('option[]'):
            optid = opt.split(':::')[0]
            optname = opt.split(':::')[1]
            optprice = opt.split(':::')[2]

            if optid not in existing_options_ids:
                o = PaymentOption()
                o.scheme_id = str(s._id)
                o.name = optname
                o.price = optprice

                EntityManager().save('PaymentOption', o)

            processed_ids.append(optid)


        #remove any existing payment options that havent been posted (because it means they were removed by the user)
        for id in set(existing_options_ids).difference(set(processed_ids)):
            EntityManager().remove_one('PaymentOption', id)

        return bottle.redirect('/admin/paymentschemes')

    else:
        viewdata = commonViewDataAdmin()
        viewdata['error'] = 'Required data is missing'

        return bottle.template('admin_paymentscheme', vd=viewdata)
Exemplo n.º 9
0
def save_item(item, newtagname):
    em = EntityManager()

    if item._id:
        #recall existing files for this item
        existingItem = em.find_one_by_id('Item', item._id)
        if existingItem is not None:
            for f in existingItem.files:
                item.files.append(f)



    if newtagname:
        existingTag = em.find_one('Tag', {'name':newtagname})
        if existingTag:
            newTagId = existingTag._id
        else:
            t = Tag()
            t.name = newtagname
            t = em.save('Tag', t)
            newTagId = t._id

        if not item.tagIds:
            item.tagIds = []

        item.tagIds.append(str(newTagId))
    
    em.save('Item', item)
Exemplo n.º 10
0
def index(session):
    form = bottle.request.form

    if form.is_valid():
        em = EntityManager()

        t = form.hydrate_entity(Tag())

        if EntityManager().find_raw('Tag', objfilter={'name': t.name}, count=True) == 0:
            em.save('Tag', t)

            return bottle.redirect('/tags')

        else:
            form.errors.append('A Tag with that name already exists')

    vd = common_view_data(session)
    vd.update({
        'form': form.get_html(row_class='form-group', submit_btn_class='btn btn-primary')
    })

    return bottle.template('tag.tpl', vd=vd)
Exemplo n.º 11
0
def index(slug, session):
    em = EntityManager()

    tag = em.find_one('Tag', {'slug': slug})

    if tag:
        criteria = {
            'tagIds':{
                '$in':[str(tag._id)]
            }
        }
        items = em.find('Item', criteria, sort=[('added', -1)])

        if bottle.request.GET.get('apikey'):
            bottle.response.content_type = 'text/json'
            return json.dumps([em.entity_to_json_safe_dict(i) for i in items])
        else:
            vd = common_view_data(session)
            vd.update({'items':items})
            return bottle.template('index.tpl', vd=vd)
        
    else:
        return bottle.HTTPError(400)
Exemplo n.º 12
0
def index():
    n = bottle.request.POST.name
    d = bottle.request.POST.description
    s = bottle.request.POST.scheme

    if n:
        if bottle.request.POST.get('id'):
            cat = EntityManager().find_one_by_id('Category', bottle.request.POST.id)
        else:
            cat = Category()

        cat.name = n
        cat.description = d
        cat.payment_scheme_id = s

        EntityManager().save('Category', cat)

        return bottle.redirect('/admin/categories')

    else:
        viewdata = commonViewDataAdmin()
        viewdata['error'] = 'Required data is missing'

        return bottle.template('admin_category', vd=viewdata)
Exemplo n.º 13
0
def run_search(session, searchterm):
    em = EntityManager()

    raw_items = em.fuzzy_text_search('Item', searchterm, 'title')
    raw_items = raw_items + em.fuzzy_text_search('Item', searchterm, 'content')

    ids = [];
    items = []
    for i in raw_items:
        if i._id not in ids:
            ids.append(i._id)
            items.append(i)

    if bottle.request.GET.get('apikey'):
        bottle.response.content_type = 'text/json'
        return json.dumps([em.entity_to_json_safe_dict(i) for i in items])

    elif bottle.request.GET.get('ajax') == "1":
        return bottle.template('items.tpl', {'items':items})

    else:
        vd = common_view_data(session)
        vd.update({'items':items})
        return bottle.template('index.tpl', vd=vd)
Exemplo n.º 14
0
def index(session, itemid):
    em = EntityManager()
    
    item = em.find_one_by_id('Item', itemid)

    #delete any uploaded files for this item
    if item.files:
        for f in item.files:
            fullpath = os.path.join(settings.USERFILESPATH, f.sysname)
            #thumbpath = os.path.join(settings.USERFILESPATH, 'thumb_'+ f.sysname)

            os.system('rm '+ fullpath)
            #os.system('rm '+ thumbpath)

            em.remove_one('File', f._id)

    em.remove_one('Item', itemid)

    return bottle.redirect('/items')
Exemplo n.º 15
0
 def setUp(self):
     self.em = EntityManager()
Exemplo n.º 16
0
class EntityManagerTest(unittest.TestCase):

    def setUp(self):
        self.em = EntityManager()

    def save_entity(self, _id=None, title='Test', items=[]):
        i = Item()
        if _id:
            i._id = _id
        i.title = title
        i.content = 'Some content'
        i.tagIds = [1,2,3]
        i.added = datetime.now()
        i.items = items

        return self.em.save('Item', i)

    def test_save(self):
        entity = self.save_entity()
        #test 'save' returns the saved entity
        self.assertIsInstance(entity, Item)

    def test_find(self):
        self.save_entity(title='Test1')
        sleep(1)
        self.save_entity(title='Test2')

        items = self.em.find('Item')

        self.assertEqual(len(items), 2)

        items = self.em.find('Item', sort=[('added',1)])

        self.assertEqual(items[0].title, 'Test1')
        self.assertEqual(items[1].title, 'Test2')

        items2 = self.em.find('Item', sort=[('added',-1)])

        self.assertEqual(items2[0].title, 'Test2')
        self.assertEqual(items2[1].title, 'Test1')


    def test_find_raw_count(self):
        self.save_entity(title='Test1')
        self.save_entity(title='Test2')

        item_count = self.em.find_raw('Item', count=True)

        self.assertEqual(item_count, 2)


    def test_find_one_by_id(self):
        _id = ObjectId()
        self.save_entity(_id=_id)

        item = self.em.find_one_by_id('Item', _id) #test that an ObjectId _id returns correctly
        self.assertIsInstance(item, Item)
        item = self.em.find_one_by_id('Item', str(_id)) #test that a string _id returns correctly
        self.assertIsInstance(item, Item)


    def test_find_one(self):
        self.save_entity(title='Test1')
        self.save_entity(title='Test2')

        item = self.em.find_one('Item', {'title':'Test2'})

        self.assertEqual(item.title, 'Test2')


    def test_nested_objects(self):
        self.save_entity(title='Test1', items = [Item(),Item(),Item()])

        item = self.em.find_one('Item', {'title':'Test1'})

        self.assertEqual(len(item.items), 3)

        for i in item.items:
            self.assertIsInstance(i, Item)


    def test_entity_to_json_safe_dict(self):
        i = Item()
        i.title = 'Nested Item'
        self.save_entity(title='Test1', items = [i,i,i])

        item = self.em.find_one('Item', {'title':'Test1'})

        jsondict = self.em.entity_to_json_safe_dict(item)

        self.assertIsInstance(jsondict, dict)

        self.assertEqual(jsondict['title'], 'Test1')

        #test nested object are still available
        self.assertEqual(jsondict['items'][0]['title'], 'Nested Item')

        #shouldnt be able to json serialise a datetime
        self.assertRaises(TypeError, json.dumps, item) 

        #should be able to json serialise Item after entity_to_json_safe_dict call
        self.assertIsInstance(json.dumps(jsondict), str) 


    def test_remove_one(self):
        self.save_entity(title='Test1')
        self.save_entity(title='Test2')
        self.save_entity(title='Test3')

        items = self.em.find('Item')

        self.assertEqual(len(items), 3)

        self.assertEqual(items[0].title, 'Test1')
        self.assertEqual(items[1].title, 'Test2')
        self.assertEqual(items[2].title, 'Test3')

        self.em.remove_one('Item', items[1]._id)

        items = self.em.find('Item')

        self.assertEqual(len(items), 2)

        self.assertEqual(items[0].title, 'Test1')
        self.assertEqual(items[1].title, 'Test3')


    def test_fuzzy_text_search(self):
        self.save_entity(title='These are some apples')
        self.save_entity(title='these are some pears')
        self.save_entity(title='theseare some bananas')

        # case insensitive
        items = self.em.fuzzy_text_search('Item', 'These', 'title')
        self.assertEqual(len(items), 3)

        items = self.em.fuzzy_text_search('Item', 'some apple', 'title')
        self.assertEqual(len(items), 3)

        items = self.em.fuzzy_text_search('Item', 'apples', 'title')
        self.assertEqual(len(items), 1)

        # spelling mistake
        items = self.em.fuzzy_text_search('Item', 'applss', 'title')
        self.assertEqual(len(items), 1)


    def tearDown(self):
        client = MongoClient(DBHOST, port=DBPORT)
        client[DBNAME].Item.drop()
Exemplo n.º 17
0
def index(session, itemid):
    em = EntityManager()
    
    item = em.find_one_by_id('Item', itemid)

    return item.content.replace('\n','<br />')
Exemplo n.º 18
0
def index(session, tagid):
    em = EntityManager()
    
    em.remove_one('Tag', tagid)

    return bottle.redirect('/tags')
Exemplo n.º 19
0
def index():
    homepagecontent = EntityManager().find('EditableContent', {'identifier':'homepage-content-box'})[0]
    homepagecontent.content = bottle.request.POST.content
    EntityManager().save('EditableContent', homepagecontent)

    return bottle.redirect('/admin')
Exemplo n.º 20
0
def index(session, itemid):
    em = EntityManager()
    
    em.remove_one('Item', itemid)

    return bottle.redirect('/items')