Example #1
0
def get_street(code):
    obj = Dictionary(STREET_CODE)
    find = {'identcode': code}
    try:
        result = obj.get_list(find)
    except ValueError, e:
        raise InvalidAPIUsage(e.message, status_code=404)
Example #2
0
 def document_details(self, code, document_id):
     obj = Dictionary(code)
     #TODO: учесть auth_token
     try:
         result = obj.get_document(dict(_id=document_id))
     except TypeError, e:
         raise InvalidAPIUsage(e.message, status_code=400)
Example #3
0
 def put(self, code, document_id):
     data = self.parse_request(request)
     obj = Dictionary(code)
     try:
         exists = obj.exists(dict(_id=document_id))
     except TypeError, e:
         raise InvalidAPIUsage(e.message, status_code=400)
Example #4
0
def get_data_hs(code, field, field_value):
    # TODO: try-except
    obj = Dictionary(code)
    obj_names = DictionaryNames()
    document = obj.get_document({str(field): field_value})
    origin_dict = obj_names.get_by_code(code)
    if 'oid' in origin_dict:
        # Работаем с НСИ справочником
        data = document
        oid = origin_dict['oid']
    else:
        try:
            try:
                linked_dict = _get_linked_dict(document, origin_dict)
            except AttributeError:
                raise InvalidAPIUsage(u'Not found', status_code=404)
            except KeyError:
                raise InvalidAPIUsage(u'Not found', status_code=404)
            if not document:
                return make_response(
                    vesta_jsonify(
                        dict(oid=linked_dict['oid'], message="not found")),
                    404)
        except TypeError, e:
            raise InvalidAPIUsage(e.message, status_code=400)
        except InvalidId, e:
            raise InvalidAPIUsage(e.message, status_code=404)
Example #5
0
 def post(self, code):
     data = self.parse_request(request)
     obj = Dictionary(code)
     try:
         _id = obj.add_documents(data)
     except TypeError, e:
         raise InvalidAPIUsage(e.message, status_code=400)
Example #6
0
def get_city(code):
    obj = Dictionary(CITY_CODE)
    find = {'identcode': code}
    try:
        cities = obj.get_list(find)
    except ValueError, e:
        raise InvalidAPIUsage(e.message, status_code=404)
Example #7
0
 def document_by_field(self, code, field, field_value):
     obj = Dictionary(code)
     if field == 'id':
         field_value = int(field_value)
     try:
         result = obj.get_document({str(field): field_value})
     except TypeError, e:
         raise InvalidAPIUsage(e.message, status_code=400)
Example #8
0
def find_data_hs(code):
    data = APIMixin().parse_request(request)
    obj = Dictionary(code)
    obj_names = DictionaryNames()
    try:
        _dict = obj_names.get_by_code(code)
        result = obj.get_document(prepare_find_params(data))
    except TypeError, e:
        raise InvalidAPIUsage(e.message, status_code=400)
Example #9
0
def search_city(value, limit=None):
    obj = Dictionary(CITY_CODE)
    find = {
        'is_actual': '1',
        '$or': [{
            'name': prepare_find_params(value)
        }, {
            'identcode': value
        }]
    }
    try:
        cities = obj.get_list(find, 'level', limit)
    except ValueError, e:
        raise InvalidAPIUsage(e.message, status_code=404)
Example #10
0
def get_linked_data(code, field, field_value):
    # TODO: try-except
    obj = Dictionary(code)
    obj_names = DictionaryNames()
    document = obj.get_document({str(field): field_value})
    try:
        origin_dict = obj_names.get_by_code(code)
        try:
            linked_dict = _get_linked_dict(document, origin_dict)
        except AttributeError:
            raise InvalidAPIUsage(u'Not found', status_code=404)
        except KeyError:
            raise InvalidAPIUsage(u'Not found', status_code=404)
        if not document:
            return make_response(
                vesta_jsonify(dict(oid=linked_dict['oid'], data={})), 200)
    except TypeError, e:
        raise InvalidAPIUsage(e.message, status_code=400)
Example #11
0
def dict_view(_id):
    obj = DictionaryNames()
    info = obj.get_by_id(_id)
    collections = Collections()
    if not info or 'code' not in info or info['code'] not in collections.get_list():
        flash(u'Коллекция не существует или пуста')
        abort(404)
    collection = Dictionary(info['code'])
    data = obj.get_list({'version': {'$exists': True}})
    fields = _get_fields(info['code'])
    try:
        return render_template('{0}/dict_view.html'.format(module.name),
                               info=info,
                               data=data,
                               fields=fields,
                               documents=collection.get_list(sort='id', limit=1000))
    except TemplateNotFound:
        abort(404)
Example #12
0
def _set_cities_parents(cities):
    obj = Dictionary(CITY_CODE)
    result = []
    for city in cities:
        city['parents'] = []
        identparent = city['identparent']
        parent = city.get('parent')
        if identparent or parent:
            level = int(city['level'])
            for i in xrange(level - 1, 0, -1):
                if parent:
                    parent_city = obj.get_document({'_id': parent})
                elif identparent:
                    parent_city = obj.get_document({'identcode': identparent})
                else:
                    break
                city['parents'].append(parent_city)
                parent = parent_city.get('parent')
                identparent = parent_city['identparent']
        result.append(city)
    return result
Example #13
0
def search_street(city_code, value, limit=None):
    obj = Dictionary(STREET_CODE)
    prepared = prepare_find_params(value)
    find = {
        'identparent':
        city_code,
        'is_actual':
        '1',
        '$or': [{
            'name': prepared
        }, {
            'fulltype': prepared
        }, {
            'shorttype': prepared
        }, {
            'identcode': value
        }]
    }
    try:
        result = obj.get_list(find, limit=limit)
    except ValueError, e:
        raise InvalidAPIUsage(e.message, status_code=404)
Example #14
0
def get_documents(code=None):
    if code:
        obj = Dictionary(code)
        data = obj.get_list()
        return vesta_jsonify(result=list(data))
Example #15
0
 def delete(self, code, document_id):
     obj = Dictionary(code)
     try:
         obj.delete(_id=document_id)
     except TypeError, e:
         raise InvalidAPIUsage(e.message, status_code=400)
Example #16
0
def _get_fields(code):
    obj = Dictionary(code)
    document = list(obj.get_list(limit=1))
    if document[0]:
        return sorted(document[0].keys())
    return []
Example #17
0
 def list_documents(self, code, find=None):
     obj = Dictionary(code)
     try:
         result = obj.get_list(find)
     except ValueError, e:
         raise InvalidAPIUsage(e.message, status_code=404)
Example #18
0
def doc_edit(code, _id):
    dict_names = DictionaryNames()
    current = dict_names.get_by_code(code)
    linked = None
    linked_code = None
    linked_docs = []
    linked_dict = dict()
    linked_dicts = dict_names.get_list({'version': {'$exists': True}})
    obj = Dictionary(code)
    document = obj.get_document({'_id': _id})

    linked_dict = _get_linked_dict(document, current)
    if linked_dict:
        linked_code = linked_dict['code']
        linked = Dictionary(linked_code)
        linked_docs = linked.get_list()

    if request.method == 'POST':
        data = dict()
        if request.form:
            for key, value in request.form.items():
                data[key] = value
        linked_id = data.pop('linked')
        _post_linked_code = data.pop('linked_collection')
        data.update({'_id': _id})
        if _post_linked_code:
            if _post_linked_code != linked_code:
                linked_code = _post_linked_code
                data.update({'linked_collection': linked_code})
            else:
                obj.unset_attr(_id, 'linked_collection')

            if linked_id:
                linked = Dictionary(linked_code)
                linked_document = linked.get_document({'_id': linked_id})
                data.update({linked_code: linked_document})
            else:
                obj.unset_attr(_id, linked_code)
                obj.unset_attr(_id, 'linked_collection')
        try:
            obj.add_document(data)
        except Exception, e:
            flash(e, 'error')
        else:
            flash(u'Документ сохранён', 'info')
            return redirect(url_for('.doc_edit', code=code, _id=_id))
Example #19
0
class DictionaryTestCase(unittest.TestCase):

    def setUp(self):
        app.config['TESTING'] = True
        app.config['MONGODB_DB'] = TEST_DB
        self.app = app.test_client()
        self.collection = 'test_dictionary'
        self.obj = Dictionary(self.collection)

    def drop_collection(self):
        db.drop_collection(self.collection)

    def tearDown(self):
        db.drop_collection(self.collection)

    def test_get_list_empty(self):
        self.drop_collection()
        with self.assertRaises(ValueError):
            result = self.obj.get_list()
        #self.assertEqual(result.count(), 0)

    def test_add_document(self):
        data = dict(code='test', name=u'Тестовый документ')
        _id = self.obj.add_document(data)
        self.assertIsNotNone(_id)
        result = self.obj.get_document(dict(_id=_id))
        data.update(dict(_id=_id))
        self.assertDictEqual(data, result)

    def test_add_documents(self):
        self.drop_collection()
        data = [dict(name=u'Документ1', code='document1'),
                dict(name=u'Документ2'),
                dict(name=u'Документ3', alias='document2'),
                dict(name=u'Документ4', code='document4', created=datetime.now())]
        _ids = self.obj.add_documents(data)
        self.assertIsNotNone(_ids)
        self.assertIsInstance(_ids, list)
        result = list(self.obj.get_list())
        self.assertEqual(len(result), len(data))
        self.assertEqual(result[0]['code'], data[0]['code'])
        data_2 = data[2]
        data_2.update(dict(_id=_ids[2]))
        self.assertEqual(result[2], data_2)

    def test_get_document(self):
        data = dict(code='test5', name=u'Тестовый документ5')
        _id = self.obj.add_document(data)
        self.assertIsNotNone(_id)
        result = self.obj.get_document(dict(_id=_id))
        data.update(dict(_id=_id))
        self.assertDictEqual(data, result)

    def test_count_documents(self):
        self.drop_collection()
        data = [dict(name=u'Документ1', code='document1'),
                dict(name=u'Документ2'),
                dict(name=u'Документ3', alias='document2'),
                dict(name=u'Документ4', code='document4', created=datetime.now())]
        _ids = self.obj.add_documents(data)
        self.assertIsNotNone(_ids)
        self.assertIsInstance(_ids, list)
        result = self.obj.count()
        self.assertEqual(result, len(data))
        result = self.obj.count(dict(_id=_ids[0]))
        self.assertEqual(result, 1)
        result = self.obj.count(dict(_id='not_exists_id'))
        self.assertEqual(result, 0)

    def test_delete(self):
        data = dict(code='test_delete', name=u'Тестовый документ')
        _id = self.obj.add_document(data)
        self.assertIsNotNone(_id)
        self.obj.delete(_id)
        result = self.obj.get_document(dict(_id=_id))
        self.assertIsNone(result)

    def test_exists(self):
        self.drop_collection()
        data = [dict(name=u'Документ1', code='document1'),
                dict(name=u'Документ2'),
                dict(name=u'Документ3', alias='document2'),
                dict(name=u'Документ4', code='document4', created=datetime.now())]
        _ids = self.obj.add_documents(data)
        self.assertIsNotNone(_ids)
        self.assertIsInstance(_ids, list)
        result = self.obj.exists()
        self.assertTrue(result)
        result = self.obj.count(dict(_id=_ids[0]))
        self.assertTrue(result)
        result = self.obj.count(dict(_id='not_exists_id'))
        self.assertFalse(result)
Example #20
0
 def setUp(self):
     app.config['TESTING'] = True
     app.config['MONGODB_DB'] = TEST_DB
     self.app = app.test_client()
     self.collection = 'test_dictionary'
     self.obj = Dictionary(self.collection)
Example #21
0
    if request.method == 'POST':
        worker = Worker(info['code'])
        try:
            worker.link_collection(request.form.get('linked_collection'),
                                   request.form.get('origin_field'),
                                   request.form.get('linked_field'))
            info = obj.get_by_id(_id)
        except Exception, e:
            flash(e, 'error')
        else:
            flash(u'Справочник успешно обновлён', 'info')
            return redirect(url_for('.dict_edit', _id=_id))
    data = dict()
    fields = dict()
    documents = list()
    collection = Dictionary(info['code'])
    linked_dict = obj.get_list({'version': {'$exists': True}})
    if info['code'] in collections.get_list():
        fields = _get_fields(info['code'])
        documents = collection.get_list(sort=[('id', 1)])
    try:
        return render_template('{0}/dict_edit.html'.format(module.name),
                               info=info,
                               data=linked_dict,
                               fields=fields,
                               documents=documents)
    except TemplateNotFound:
        abort(404)


@module.route('/dict_view/<_id>/')