Beispiel #1
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)
Beispiel #2
0
def index():
    obj = DictionaryNames()
    data = obj.get_list({'code': {'$ne': 'dict_names'}}, sort=[('oid', 1), ('code', 1)])
    try:
        return render_template('{0}/index.html'.format(module.name), data=data)
    except TemplateNotFound:
        abort(404)
Beispiel #3
0
 def delete(self, code):
     """Удаление справочника"""
     obj = DictionaryNames()
     try:
         obj.delete(code=code)
     except TypeError, e:
         raise InvalidAPIUsage(e.message, status_code=400)
Beispiel #4
0
 def put(self, code):
     """Обновление информации о справочнике"""
     data = self.parse_request(request)
     obj = DictionaryNames()
     try:
         document = obj.get_by_code(code)
     except TypeError, e:
         raise InvalidAPIUsage(e.message, status_code=400)
Beispiel #5
0
 def post(self):
     """Заведение информации о справочнике"""
     data = self.parse_request(request)
     obj = DictionaryNames()
     try:
         _id = obj.add(data)
     except TypeError, e:
         raise InvalidAPIUsage(e.message, status_code=400)
Beispiel #6
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)
Beispiel #7
0
 def get(self, code):
     """Получение списка справочников или информации по конкретному справочнику"""
     collection = DictionaryNames()
     if code is None:
         # return list of Dictionaries
         try:
             result = collection.get_list()
         except TypeError, e:
             raise InvalidAPIUsage(e.message, status_code=400)
         except ValueError, e:
             return vesta_jsonify(dict())
Beispiel #8
0
def _get_linked_dict(document, collection):
    # Если в документе задана привязка к справочнику - используем её
    if document and 'linked_collection' in document:
        obj_names = DictionaryNames()
        linked_dict = obj_names.get_by_code(document['linked_collection'])
        return linked_dict

    # Иначе смотрим на привязку самого справочника
    try:
        linked_dict = collection['linked']['collection']
    except AttributeError:
        raise InvalidAPIUsage(u'Not found', status_code=404)
    except KeyError:
        raise InvalidAPIUsage(u'Not found', status_code=404)
    else:
        return linked_dict
Beispiel #9
0
def _get_linked_dict(document, collection):
    # Если в документе задана привязка к справочнику - используем её
    if 'linked_collection' in document:
        obj_names = DictionaryNames()
        linked_dict = obj_names.get_by_code(document['linked_collection'])
        return linked_dict

    # Иначе смотрим на привязку самого справочника
    try:
        linked_dict = collection['linked']['collection']
    except AttributeError:
        return None
    except KeyError:
        return None
    else:
        return linked_dict
Beispiel #10
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))
Beispiel #11
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)
Beispiel #12
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)
Beispiel #13
0
def dict_edit(_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)

    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))
Beispiel #14
0
 def setUp(self):
     app.config['TESTING'] = True
     app.config['MONGODB_DB'] = TEST_DB
     self.app = app.test_client()
     self.obj = DictionaryNames()