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)
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)
def delete(self, code): """Удаление справочника""" obj = DictionaryNames() try: obj.delete(code=code) except TypeError, e: raise InvalidAPIUsage(e.message, status_code=400)
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)
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)
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)
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())
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
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
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))
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)
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)
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))
def setUp(self): app.config['TESTING'] = True app.config['MONGODB_DB'] = TEST_DB self.app = app.test_client() self.obj = DictionaryNames()
class DictionaryNamesTestCase(unittest.TestCase): def setUp(self): app.config['TESTING'] = True app.config['MONGODB_DB'] = TEST_DB self.app = app.test_client() self.obj = DictionaryNames() def tearDown(self): db.drop_collection(self.obj.code) def test_get_list(self): with self.assertRaises(ValueError): result = self.obj.get_list() #self.assertEqual(result.count(), 0) #self.assertEqual(list(result), list()) def test_add(self): data = dict(code='test', name=u'Тестовый справочник') _id = self.obj.add(data) self.assertIsNotNone(_id) result = self.obj.get_by_id(_id) data.update(dict(_id=_id)) self.assertDictEqual(data, result) def test_update(self): data = dict(code='test2', name=u'Тестовый справочник2') _id = self.obj.add(data) self.assertIsNotNone(_id) update_data = dict(code='test2', name=u'Тестовый справочник2 (updated)', updated=datetime.now()) self.obj.update(_id, update_data) result = self.obj.get_by_id(_id) update_data.update(dict(_id=_id)) result.pop('updated') update_data.pop('updated') self.assertDictEqual(result, update_data) def test_delete(self): code = 'test3' data = dict(code=code, name=u'Тестовый справочник3') _id = self.obj.add(data) self.assertIsNotNone(_id) self.obj.delete(code) result = self.obj.get_by_code(code) self.assertIsNone(result) def test_update_by_code(self): code = 'test4' data = dict(code=code, name=u'Тестовый справочник4') _id = self.obj.add(data) self.assertIsNotNone(_id) update_data = dict(code=code, name=u'Тестовый справочник4 (updated)', updated=datetime.now()) self.obj.update_by_code(code, update_data) result = self.obj.get_by_code(code) update_data.update(dict(_id=_id)) result.pop('updated') update_data.pop('updated') self.assertDictEqual(result, update_data)