Example #1
0
    def update(self, id):
        """Update a keyboard and return it.

        :URL: ``PUT /keyboards/id``
        :Request body: JSON object representing the keyboard with updated
            attribute values.
        :param str id: the ``id`` value of the keyboard to be updated.
        :returns: the updated keyboard model.

        """
        keyboard = Session.query(Keyboard).get(int(id))
        if keyboard:
            try:
                schema = KeyboardSchema()
                values = json.loads(unicode(request.body, request.charset))
                state = h.get_state_object(values)
                state.id = id
                data = schema.to_python(values, state)
                keyboard = update_keyboard(keyboard, data)
                # keyboard will be False if there are no changes (cf.
                # update_keyboard).
                if keyboard:
                    Session.add(keyboard)
                    Session.commit()
                    return keyboard
                else:
                    response.status_int = 400
                    return {'error': (u'The update request failed because the'
                        u' submitted data were not new.')}
            except h.JSONDecodeError:
                response.status_int = 400
                return h.JSONDecodeErrorResponse
            except Invalid, e:
                response.status_int = 400
                return {'errors': e.unpack_errors()}
Example #2
0
    def create(self):
        """Create a new user resource and return it.

        :URL: ``POST /users``
        :request body: JSON object representing the user to create.
        :returns: the newly created user.

        .. note::
        
            Only administrators are authorized to create users.

        """
        try:
            schema = UserSchema()
            values = json.loads(unicode(request.body, request.charset))
            data = schema.to_python(values)
            user = create_new_user(data)
            Session.add(user)
            Session.commit()
            return user.get_full_dict()
        except h.JSONDecodeError:
            response.status_int = 400
            return h.JSONDecodeErrorResponse
        except Invalid, e:
            response.status_int = 400
            return {'errors': e.unpack_errors()}
Example #3
0
File: pages.py Project: FieldDB/old
    def update(self, id):
        """Update a page and return it.
        
        :URL: ``PUT /pages/id``
        :Request body: JSON object representing the page with updated attribute values.
        :param str id: the ``id`` value of the page to be updated.
        :returns: the updated page model.

        """
        page = Session.query(Page).get(int(id))
        if page:
            try:
                schema = PageSchema()
                values = json.loads(unicode(request.body, request.charset))
                data = schema.to_python(values)
                page = update_page(page, data)
                # page will be False if there are no changes (cf. update_page).
                if page:
                    Session.add(page)
                    Session.commit()
                    return page
                else:
                    response.status_int = 400
                    return {'error':
                        u'The update request failed because the submitted data were not new.'}
            except h.JSONDecodeError:
                response.status_int = 400
                return  h.JSONDecodeErrorResponse
            except Invalid, e:
                response.status_int = 400
                return {'errors': e.unpack_errors()}
Example #4
0
def createForm(i, commit=False):
    f = model.Form()
    f.transcription = u'transcription'

    g1 = model.Gloss()
    g1.gloss = u'gloss'
    f.glosses.append(g1)
    if i % 2 == 0:
        g2 = model.Gloss()
        g2.gloss = u'gloss'
        f.glosses.append(g2)

    u = model.User()
    u.name = u'name'
    f.elicitor = u

    if i % 3 == 0:
        f1 = model.File()
        f1.filename = u'file%s-1.wav' % str(i)
        f2 = model.File()
        f2.filename = u'file%s-2.wav' % str(i)
        f3 = model.File()
        f3.filename = u'file%s-3.wav' % str(i)
        f.files = [f1, f2, f3]

    Session.add(f)
    if commit:
        Session.commit()
    return f
Example #5
0
def _create_test_form_searches(n=100):
    """Create n form searches with various properties.  A testing ground for searches!
    """
    users = h.get_users()
    contributor = [u for u in users if u.role == u'contributor'][0]

    for i in range(1, n + 1):
        fs = model.FormSearch()

        fs.enterer_id = contributor.id
        fs.search = unicode(json.dumps(
                {'query': {'filter': ['Form', 'transcription', 'regex', '%d' % i]}}))
        if i % 2 == 0:
            fs.name = u'Form Search %d' % i
        else:
            fs.name = u'form search %d' % i

        if i > 50:
            fs.description = u'I really like this search and my favourite number is %d' % i

        if i > 20:
            fs.datetime_modified = today_timestamp
        else:
            fs.datetime_modified = yesterday_timestamp

        Session.add(fs)
    Session.commit()
Example #6
0
    def update(self, id):
        """Update a user and return it.
        
        :URL: ``PUT /users/id``
        :Request body: JSON object representing the user with updated attribute values.
        :param str id: the ``id`` value of the user to be updated.
        :returns: the updated user model.

        """
        user = Session.query(User).get(int(id))
        if user:
            try:
                schema = UserSchema()
                values = json.loads(unicode(request.body, request.charset))
                state = h.get_state_object(values)
                state.user_to_update = user.get_full_dict()
                current_user = Session.query(User).get(session['user'].id)
                state.user = current_user.get_full_dict()
                data = schema.to_python(values, state)
                user = update_user(user, data)
                # user will be False if there are no changes (cf. update_user).
                if user:
                    Session.add(user)
                    Session.commit()
                    return user.get_full_dict()
                else:
                    response.status_int = 400
                    return {'error':
                        u'The update request failed because the submitted data were not new.'}
            except h.JSONDecodeError:
                response.status_int = 400
                return h.JSONDecodeErrorResponse
            except Invalid, e:
                response.status_int = 400
                return {'errors': e.unpack_errors()}
Example #7
0
    def update(self, id):
        """Update a morpheme language model and return it.

        :URL: ``PUT /morphemelanguagemodels/id``
        :Request body: JSON object representing the morpheme language model with updated attribute values.
        :param str id: the ``id`` value of the morpheme language model to be updated.
        :returns: the updated morpheme language model model.

        """
        morpheme_language_model = h.eagerload_morpheme_language_model(Session.query(MorphemeLanguageModel)).get(int(id))
        if morpheme_language_model:
            try:
                schema = MorphemeLanguageModelSchema()
                values = json.loads(unicode(request.body, request.charset))
                state = h.get_state_object(values)
                state.id = id
                data = schema.to_python(values, state)
                morpheme_language_model_dict = morpheme_language_model.get_dict()
                morpheme_language_model = update_morpheme_language_model(morpheme_language_model, data)
                # morpheme_language_model will be False if there are no changes (cf. update_morpheme_language_model).
                if morpheme_language_model:
                    backup_morpheme_language_model(morpheme_language_model_dict)
                    Session.add(morpheme_language_model)
                    Session.commit()
                    return morpheme_language_model
                else:
                    response.status_int = 400
                    return {'error': u'The update request failed because the submitted data were not new.'}
            except h.JSONDecodeError:
                response.status_int = 400
                return h.JSONDecodeErrorResponse
            except Invalid, e:
                response.status_int = 400
                return {'errors': e.unpack_errors()}
Example #8
0
    def create(self):
        """Create a new collection resource and return it.

        :URL: ``POST /collections``
        :request body: JSON object representing the collection to create.
        :returns: the newly created collection.

        """
        try:
            unrestricted_users = h.get_unrestricted_users()
            user = session['user']
            schema = CollectionSchema()
            values = json.loads(unicode(request.body, request.charset))
            collections_referenced = get_collections_referenced(values['contents'],
                                                        user, unrestricted_users)
            values = add_contents_unpacked_to_values(values, collections_referenced)
            values = add_form_ids_list_to_values(values)
            state = h.get_state_object(values)
            data = schema.to_python(values, state)
            collection = create_new_collection(data, collections_referenced)
            Session.add(collection)
            Session.commit()
            return collection.get_full_dict()
        except h.JSONDecodeError:
            response.status_int = 400
            return h.JSONDecodeErrorResponse
        except InvalidCollectionReferenceError, e:
            response.status_int = 400
            return {'error': u'Invalid collection reference error: there is no collection with id %d' % e.args[0]}
Example #9
0
    def create(self):
        """Create a new user resource and return it.

        :URL: ``POST /users``
        :request body: JSON object representing the user to create.
        :returns: the newly created user.

        .. note::
        
            Only administrators are authorized to create users.

        """
        try:
            schema = UserSchema()
            values = json.loads(unicode(request.body, request.charset))
            data = schema.to_python(values)
            user = create_new_user(data)
            Session.add(user)
            Session.commit()
            return user.get_full_dict()
        except h.JSONDecodeError:
            response.status_int = 400
            return h.JSONDecodeErrorResponse
        except Invalid, e:
            response.status_int = 400
            return {'errors': e.unpack_errors()}
Example #10
0
    def update(self, id):
        """Update a speaker and return it.
        
        :URL: ``PUT /speakers/id``
        :Request body: JSON object representing the speaker with updated attribute values.
        :param str id: the ``id`` value of the speaker to be updated.
        :returns: the updated speaker model.

        """
        speaker = Session.query(Speaker).get(int(id))
        if speaker:
            try:
                schema = SpeakerSchema()
                values = json.loads(unicode(request.body, request.charset))
                data = schema.to_python(values)
                speaker = update_speaker(speaker, data)
                # speaker will be False if there are no changes (cf. update_speaker).
                if speaker:
                    Session.add(speaker)
                    Session.commit()
                    return speaker
                else:
                    response.status_int = 400
                    return {'error':
                        u'The update request failed because the submitted data were not new.'}
            except h.JSONDecodeError:
                response.status_int = 400
                return h.JSONDecodeErrorResponse
            except Invalid, e:
                response.status_int = 400
                return {'errors': e.unpack_errors()}
Example #11
0
    def create(self):
        """Create a new collection resource and return it.

        :URL: ``POST /collections``
        :request body: JSON object representing the collection to create.
        :returns: the newly created collection.

        """
        try:
            unrestricted_users = h.get_unrestricted_users()
            user = session['user']
            schema = CollectionSchema()
            values = json.loads(unicode(request.body, request.charset))
            collections_referenced = get_collections_referenced(
                values['contents'], user, unrestricted_users)
            values = add_contents_unpacked_to_values(values,
                                                     collections_referenced)
            values = add_form_ids_list_to_values(values)
            state = h.get_state_object(values)
            data = schema.to_python(values, state)
            collection = create_new_collection(data, collections_referenced)
            Session.add(collection)
            Session.commit()
            return collection.get_full_dict()
        except h.JSONDecodeError:
            response.status_int = 400
            return h.JSONDecodeErrorResponse
        except InvalidCollectionReferenceError, e:
            response.status_int = 400
            return {
                'error':
                u'Invalid collection reference error: there is no collection with id %d'
                % e.args[0]
            }
Example #12
0
    def update(self, id):
        """Update an elicitation method and return it.
        
        :URL: ``PUT /elicitationmethods/id``
        :Request body: JSON object representing the elicitation method with updated attribute values.
        :param str id: the ``id`` value of the elicitation method to be updated.
        :returns: the updated elicitation method model.

        """
        elicitation_method = Session.query(ElicitationMethod).get(int(id))
        if elicitation_method:
            try:
                schema = ElicitationMethodSchema()
                values = json.loads(unicode(request.body, request.charset))
                state = h.get_state_object(values)
                state.id = id
                data = schema.to_python(values, state)
                elicitation_method = update_elicitation_method(elicitation_method, data)
                # elicitation_method will be False if there are no changes (cf. update_elicitation_method).
                if elicitation_method:
                    Session.add(elicitation_method)
                    Session.commit()
                    return elicitation_method
                else:
                    response.status_int = 400
                    return {'error':
                        u'The update request failed because the submitted data were not new.'}
            except h.JSONDecodeError:
                response.status_int = 400
                return h.JSONDecodeErrorResponse
            except Invalid, e:
                response.status_int = 400
                return {'errors': e.unpack_errors()}
Example #13
0
    def update(self, id):
        """Update an application settings and return it.
        
        :URL: ``PUT /applicationsettings/id``
        :Request body: JSON object representing the application settings with updated attribute values.
        :param str id: the ``id`` value of the application settings to be updated.
        :returns: the updated application settings model.

        """
        application_settings = h.eagerload_application_settings(
            Session.query(ApplicationSettings)).get(int(id))
        if application_settings:
            try:
                schema = ApplicationSettingsSchema()
                values = json.loads(unicode(request.body, request.charset))
                data = schema.to_python(values)
                # Try to create an updated ApplicationSetting object.
                application_settings = update_application_settings(application_settings, data)
                # application_settings will be False if there are no changes
                if application_settings:
                    Session.add(application_settings)
                    Session.commit()
                    app_globals.application_settings = h.ApplicationSettings()
                    return application_settings
                else:
                    response.status_int = 400
                    return {'error': 'The update request failed because the submitted data were not new.'}
            except h.JSONDecodeError:
                response.status_int = 400
                return h.JSONDecodeErrorResponse
            except Invalid, e:
                response.status_int = 400
                return {'errors': e.unpack_errors()}
Example #14
0
def createForm(i, commit=False):
    f = model.Form()
    f.transcription = u'transcription'

    g1 = model.Gloss()
    g1.gloss = u'gloss'
    f.glosses.append(g1)
    if i % 2 == 0:
        g2 = model.Gloss()
        g2.gloss = u'gloss'
        f.glosses.append(g2)

    u = model.User()
    u.name = u'name'
    f.elicitor = u

    if i % 3 == 0:
        f1 = model.File()
        f1.filename = u'file%s-1.wav' % str(i)
        f2 = model.File()
        f2.filename = u'file%s-2.wav' % str(i)
        f3 = model.File()
        f3.filename = u'file%s-3.wav' % str(i)
        f.files = [f1, f2, f3]

    Session.add(f)
    if commit:
        Session.commit()
    return f
Example #15
0
def _create_test_form_searches(n=100):
    """Create n form searches with various properties.  A testing ground for searches!
    """
    users = h.get_users()
    contributor = [u for u in users if u.role == u'contributor'][0]

    for i in range(1, n + 1):
        fs = model.FormSearch()

        fs.enterer_id = contributor.id
        fs.search = unicode(
            json.dumps({
                'query': {
                    'filter': ['Form', 'transcription', 'regex',
                               '%d' % i]
                }
            }))
        if i % 2 == 0:
            fs.name = u'Form Search %d' % i
        else:
            fs.name = u'form search %d' % i

        if i > 50:
            fs.description = u'I really like this search and my favourite number is %d' % i

        if i > 20:
            fs.datetime_modified = today_timestamp
        else:
            fs.datetime_modified = yesterday_timestamp

        Session.add(fs)
    Session.commit()
Example #16
0
def update_collection_by_deletion_of_referenced_form(collection,
                                                     referenced_form):
    """Update a collection based on the deletion of a form it references.

    This function is called in the :class:`FormsController` when a form is
    deleted.  It is called on each collection that references the deleted form
    and the changes to each of those collections are propagated through all of
    the collections that reference them, and so on.
    
    :param collection: a collection model object.
    :param referenced_form: a form model object.
    :returns: ``None``.

    """
    collection_dict = collection.get_full_dict()
    collection.contents = remove_references_to_this_form(
        collection.contents, referenced_form.id)
    collections_referenced = get_collections_referenced(collection.contents)
    collection.contents_unpacked = generate_contents_unpacked(
        collection.contents, collections_referenced)
    collection.html = h.get_HTML_from_contents(collection.contents_unpacked,
                                               collection.markup_language)
    collection.datetime_modified = datetime.datetime.utcnow()
    backup_collection(collection_dict)
    update_collections_that_reference_this_collection(
        collection,
        OldcollectionsController.query_builder,
        contents_changed=True)
    Session.add(collection)
    Session.commit()
Example #17
0
    def update(self, id):
        """Update a source and return it.
        
        :URL: ``PUT /sources/id``
        :Request body: JSON object representing the source with updated attribute values.
        :param str id: the ``id`` value of the source to be updated.
        :returns: the updated source model.

        """
        source = Session.query(Source).get(int(id))
        if source:
            try:
                schema = SourceSchema()
                values = json.loads(unicode(request.body, request.charset))
                state = h.get_state_object(values)
                state.id = id
                data = schema.to_python(values, state)
                source = update_source(source, data)
                # source will be False if there are no changes (cf. update_source).
                if source:
                    Session.add(source)
                    Session.commit()
                    return source
                else:
                    response.status_int = 400
                    return {'error':
                        u'The update request failed because the submitted data were not new.'}
            except h.JSONDecodeError:
                response.status_int = 400
                return h.JSONDecodeErrorResponse
            except Invalid, e:
                response.status_int = 400
                return {'errors': e.unpack_errors()}
Example #18
0
    def create(self):
        """Create a new corpus resource and return it.

        :URL: ``POST /corpora``
        :request body: JSON object representing the corpus to create.
        :returns: the newly created corpus.

        """
        try:
            schema = CorpusSchema()
            values = json.loads(unicode(request.body, request.charset))
            state = h.get_state_object(values)
            state.config = config
            data = schema.to_python(values, state)
            corpus = create_new_corpus(data)
            Session.add(corpus)
            Session.commit()
            create_corpus_dir(corpus)
            return corpus
        except h.JSONDecodeError:
            response.status_int = 400
            return h.JSONDecodeErrorResponse
        except Invalid, e:
            response.status_int = 400
            return {'errors': e.unpack_errors()}
Example #19
0
    def update(self, id):
        """Update a syntactic category and return it.
        
        :URL: ``PUT /syntacticcategorys/id``
        :Request body: JSON object representing the syntactic category with updated attribute values.
        :param str id: the ``id`` value of the syntactic category to be updated.
        :returns: the updated syntactic category model.

        """
        syntactic_category = Session.query(SyntacticCategory).get(int(id))
        if syntactic_category:
            try:
                old_name = syntactic_category.name
                schema = SyntacticCategorySchema()
                values = json.loads(unicode(request.body, request.charset))
                state = h.get_state_object(values)
                state.id = id
                data = schema.to_python(values, state)
                syntactic_category = update_syntactic_category(syntactic_category, data)
                # syntactic_category will be False if there are no changes (cf. update_syntactic_category).
                if syntactic_category:
                    Session.add(syntactic_category)
                    Session.commit()
                    if syntactic_category.name != old_name:
                        update_forms_referencing_this_category(syntactic_category)
                    return syntactic_category
                else:
                    response.status_int = 400
                    return {"error": u"The update request failed because the submitted data were not new."}
            except h.JSONDecodeError:
                response.status_int = 400
                return h.JSONDecodeErrorResponse
            except Invalid, e:
                response.status_int = 400
                return {"errors": e.unpack_errors()}
Example #20
0
    def update(self, id):
        """Update a form search and return it.
        
        :URL: ``PUT /formsearches/id``
        :Request body: JSON object representing the form search with updated
            attribute values.
        :param str id: the ``id`` value of the form search to be updated.
        :returns: the updated form search model.

        """
        form_search = h.eagerload_form_search(Session.query(FormSearch)).get(int(id))
        if form_search:
            try:
                schema = FormSearchSchema()
                values = json.loads(unicode(request.body, request.charset))
                state = h.get_state_object(values)
                state.id = id
                state.config = config
                data = schema.to_python(values, state)
                form_search = update_form_search(form_search, data)
                # form_search will be False if there are no changes (cf. update_form_search).
                if form_search:
                    Session.add(form_search)
                    Session.commit()
                    return form_search
                else:
                    response.status_int = 400
                    return {'error':
                        u'The update request failed because the submitted data were not new.'}
            except h.JSONDecodeError:
                response.status_int = 400
                return h.JSONDecodeErrorResponse
            except Invalid, e:
                response.status_int = 400
                return {'errors': e.unpack_errors()}
Example #21
0
File: tags.py Project: FieldDB/old
    def update(self, id):
        """Update a tag and return it.
        
        :URL: ``PUT /tags/id``
        :Request body: JSON object representing the tag with updated attribute values.
        :param str id: the ``id`` value of the tag to be updated.
        :returns: the updated tag model.

        """
        tag = Session.query(Tag).get(int(id))
        if tag:
            try:
                schema = TagSchema()
                values = json.loads(unicode(request.body, request.charset))
                state = h.get_state_object(values)
                state.id = id
                data = schema.to_python(values, state)
                tag = update_tag(tag, data)
                # tag will be False if there are no changes (cf. update_tag).
                if tag:
                    Session.add(tag)
                    Session.commit()
                    return tag
                else:
                    response.status_int = 400
                    return {'error':
                        u'The update request failed because the submitted data were not new.'}
            except h.JSONDecodeError:
                response.status_int = 400
                return h.JSONDecodeErrorResponse
            except Invalid, e:
                response.status_int = 400
                return {'errors': e.unpack_errors()}
Example #22
0
    def create(self):
        """Create a new corpus resource and return it.

        :URL: ``POST /corpora``
        :request body: JSON object representing the corpus to create.
        :returns: the newly created corpus.

        """
        try:
            schema = CorpusSchema()
            values = json.loads(unicode(request.body, request.charset))
            state = h.get_state_object(values)
            state.config = config
            data = schema.to_python(values, state)
            corpus = create_new_corpus(data)
            Session.add(corpus)
            Session.commit()
            create_corpus_dir(corpus)
            return corpus
        except h.JSONDecodeError:
            response.status_int = 400
            return h.JSONDecodeErrorResponse
        except Invalid, e:
            response.status_int = 400
            return {'errors': e.unpack_errors()}
Example #23
0
def update_collection_by_deletion_of_referenced_form(collection, referenced_form):
    """Update a collection based on the deletion of a form it references.

    This function is called in the :class:`FormsController` when a form is
    deleted.  It is called on each collection that references the deleted form
    and the changes to each of those collections are propagated through all of
    the collections that reference them, and so on.
    
    :param collection: a collection model object.
    :param referenced_form: a form model object.
    :returns: ``None``.

    """
    collection_dict = collection.get_full_dict()
    collection.contents = remove_references_to_this_form(collection.contents, referenced_form.id)
    collections_referenced = get_collections_referenced(collection.contents)
    collection.contents_unpacked = generate_contents_unpacked(
                                collection.contents, collections_referenced)
    collection.html = h.get_HTML_from_contents(collection.contents_unpacked,
                                              collection.markup_language)
    collection.datetime_modified = datetime.datetime.utcnow()
    backup_collection(collection_dict)
    update_collections_that_reference_this_collection(
        collection, OldcollectionsController.query_builder, contents_changed=True)
    Session.add(collection)
    Session.commit()
def add_default_application_settings():
    """Add the default application settings to the database."""
    orthography1 = h.generate_default_orthography1()
    orthography2 = h.generate_default_orthography2()
    contributor = Session.query(User).filter(User.role==u'contributor').first()
    application_settings = h.generate_default_application_settings([orthography1, orthography2], [contributor])
    Session.add(application_settings)
    Session.commit()
    return application_settings
Example #25
0
def backup_collection(collection_dict):
    """Backup a collection.

    :param dict form_dict: a representation of a collection model.
    :returns: ``None``

    """
    collection_backup = CollectionBackup()
    collection_backup.vivify(collection_dict)
    Session.add(collection_backup)
Example #26
0
def backup_morphology(morphology_dict):
    """Backup a morphology.

    :param dict morphology_dict: a representation of a morphology model.
    :returns: ``None``

    """
    morphology_backup = MorphologyBackup()
    morphology_backup.vivify(morphology_dict)
    Session.add(morphology_backup)
Example #27
0
def backup_corpus(corpus_dict):
    """Backup a corpus.

    :param dict corpus_dict: a representation of a corpus model.
    :returns: ``None``

    """
    corpus_backup = CorpusBackup()
    corpus_backup.vivify(corpus_dict)
    Session.add(corpus_backup)
Example #28
0
def backup_morphological_parser(morphological_parser_dict):
    """Backup a morphological parser.

    :param dict morphological_parser_dict: a representation of a morphological parser model.
    :returns: ``None``

    """
    morphological_parser_backup = MorphologicalParserBackup()
    morphological_parser_backup.vivify(morphological_parser_dict)
    Session.add(morphological_parser_backup)
Example #29
0
def backup_morphological_parser(morphological_parser_dict):
    """Backup a morphological parser.

    :param dict morphological_parser_dict: a representation of a morphological parser model.
    :returns: ``None``

    """
    morphological_parser_backup = MorphologicalParserBackup()
    morphological_parser_backup.vivify(morphological_parser_dict)
    Session.add(morphological_parser_backup)
Example #30
0
def backup_corpus(corpus_dict):
    """Backup a corpus.

    :param dict corpus_dict: a representation of a corpus model.
    :returns: ``None``

    """
    corpus_backup = CorpusBackup()
    corpus_backup.vivify(corpus_dict)
    Session.add(corpus_backup)
Example #31
0
def backup_morpheme_language_model(morpheme_language_model_dict):
    """Backup a morpheme language model.

    :param dict morpheme_language_model_dict: a representation of a morpheme language model model.
    :returns: ``None``

    """
    morpheme_language_model_backup = MorphemeLanguageModelBackup()
    morpheme_language_model_backup.vivify(morpheme_language_model_dict)
    Session.add(morpheme_language_model_backup)
Example #32
0
def backup_collection(collection_dict):
    """Backup a collection.

    :param dict form_dict: a representation of a collection model.
    :returns: ``None``

    """
    collection_backup = CollectionBackup()
    collection_backup.vivify(collection_dict)
    Session.add(collection_backup)
Example #33
0
def backup_morpheme_language_model(morpheme_language_model_dict):
    """Backup a morpheme language model.

    :param dict morpheme_language_model_dict: a representation of a morpheme language model model.
    :returns: ``None``

    """
    morpheme_language_model_backup = MorphemeLanguageModelBackup()
    morpheme_language_model_backup.vivify(morpheme_language_model_dict)
    Session.add(morpheme_language_model_backup)
Example #34
0
def backup_phonology(phonology_dict):
    """Backup a phonology.

    :param dict phonology_dict: a representation of a phonology model.
    :returns: ``None``

    """
    phonology_backup = PhonologyBackup()
    phonology_backup.vivify(phonology_dict)
    Session.add(phonology_backup)
Example #35
0
def _create_test_models(n=100):
    _add_test_models_to_session('Tag', n, ['name'])
    _add_test_models_to_session('Speaker', n, ['first_name', 'last_name', 'dialect'])
    _add_test_models_to_session('Source', n, ['author_first_name', 'author_last_name',
                                            'title'])
    _add_test_models_to_session('ElicitationMethod', n, ['name'])
    _add_test_models_to_session('SyntacticCategory', n, ['name'])
    _add_test_models_to_session('File', n, ['name'])
    restricted_tag = h.generate_restricted_tag()
    Session.add(restricted_tag)
    Session.commit()
Example #36
0
def _create_test_models(n=100):
    _add_test_models_to_session('Tag', n, ['name'])
    _add_test_models_to_session('Speaker', n,
                                ['first_name', 'last_name', 'dialect'])
    _add_test_models_to_session(
        'Source', n, ['author_first_name', 'author_last_name', 'title'])
    _add_test_models_to_session('ElicitationMethod', n, ['name'])
    _add_test_models_to_session('SyntacticCategory', n, ['name'])
    _add_test_models_to_session('File', n, ['name'])
    restricted_tag = h.generate_restricted_tag()
    Session.add(restricted_tag)
    Session.commit()
Example #37
0
    def update(self, id):
        """Update a collection and return it.
        
        :URL: ``PUT /collections/id``
        :Request body: JSON object representing the collection with updated attribute values.
        :param str id: the ``id`` value of the collection to be updated.
        :returns: the updated collection model.

        """
        collection = h.eagerload_collection(Session.query(Collection),
                                           eagerload_forms=True).get(int(id))
        if collection:
            unrestricted_users = h.get_unrestricted_users()
            user = session['user']
            if h.user_is_authorized_to_access_model(user, collection, unrestricted_users):
                try:
                    schema = CollectionSchema()
                    values = json.loads(unicode(request.body, request.charset))
                    collections_referenced = get_collections_referenced(
                                values['contents'], user, unrestricted_users, id)
                    values = add_contents_unpacked_to_values(values, collections_referenced)
                    values = add_form_ids_list_to_values(values)
                    state = h.get_state_object(values)
                    data = schema.to_python(values, state)
                    collection_dict = collection.get_full_dict()
                    collection, restricted, contents_changed = update_collection(
                        collection, data, collections_referenced)
                    # collection will be False if there are no changes (cf. update_collection).
                    if collection:
                        backup_collection(collection_dict)
                        update_collections_that_reference_this_collection(collection, self.query_builder,
                                            restricted=restricted, contents_changed=contents_changed)
                        Session.add(collection)
                        Session.commit()
                        return collection.get_full_dict()
                    else:
                        response.status_int = 400
                        return {'error':
                            u'The update request failed because the submitted data were not new.'}
                except h.JSONDecodeError:
                    response.status_int = 400
                    return h.JSONDecodeErrorResponse
                except CircularCollectionReferenceError, e:
                    response.status_int = 400
                    return {'error':
                        u'Circular collection reference error: collection %d references collection %d.' % (id, e.args[0])}
                except InvalidCollectionReferenceError, e:
                    response.status_int = 400
                    return {'error': u'Invalid collection reference error: there is no collection with id %d' % e.args[0]}
                except UnauthorizedCollectionReferenceError:
                    response.status_int = 403
                    return {'error': u'Unauthorized collection reference error: you are not authorized to access collection %d' % e.args[0]}
Example #38
0
def createCollection(i, forms=None, commit=False):
    c = model.Collection()
    c.title = u'title'
    if i % 3 == 0:
        c.forms = forms
    elif i % 2 == 0:
        c.forms = forms[::3]
    else:
        c.forms = forms[:10]
    Session.add(c)
    if commit:
        Session.commit()
    return c
Example #39
0
def createCollection(i, forms=None, commit=False):
    c = model.Collection()
    c.title = u'title'
    if i % 3 == 0:
        c.forms = forms
    elif i % 2 == 0:
        c.forms = forms[::3]
    else:
        c.forms = forms[:10]
    Session.add(c)
    if commit:
        Session.commit()
    return c
Example #40
0
    def update(self, id):
        """Update an orthography and return it.
        
        :URL: ``PUT /orthographies/id``
        :Request body: JSON object representing the orthography with updated attribute values.
        :param str id: the ``id`` value of the orthography to be updated.
        :returns: the updated orthography model.

        .. note::
        
            Contributors can only update orthographies that are not used in the
            active application settings.

        """
        orthography = Session.query(Orthography).get(int(id))
        user = session['user']
        if orthography:
            app_set = h.get_application_settings()
            if user.role == u'administrator' or orthography not in (
                    app_set.storage_orthography, app_set.input_orthography,
                    app_set.output_orthography):
                try:
                    schema = OrthographySchema()
                    values = json.loads(unicode(request.body, request.charset))
                    state = h.get_state_object(values)
                    state.id = id
                    result = schema.to_python(values, state)
                    orthography = update_orthography(orthography, result)
                    # orthography will be False if there are no changes (cf. update_orthography).
                    if orthography:
                        Session.add(orthography)
                        Session.commit()
                        return orthography
                    else:
                        response.status_int = 400
                        return {
                            'error':
                            u'The update request failed because the submitted data were not new.'
                        }
                except h.JSONDecodeError:
                    response.status_int = 400
                    return h.JSONDecodeErrorResponse
                except Invalid, e:
                    response.status_int = 400
                    return {'errors': e.unpack_errors()}
            else:
                response.status = 403
                return {
                    'error':
                    u'Only administrators are permitted to update orthographies that are used in the active application settings.'
                }
Example #41
0
    def update(self, id):
        """Update an orthography and return it.
        
        :URL: ``PUT /orthographies/id``
        :Request body: JSON object representing the orthography with updated attribute values.
        :param str id: the ``id`` value of the orthography to be updated.
        :returns: the updated orthography model.

        .. note::
        
            Contributors can only update orthographies that are not used in the
            active application settings.

        """
        orthography = Session.query(Orthography).get(int(id))
        user = session['user']
        if orthography:
            app_set = h.get_application_settings()
            if user.role == u'administrator' or orthography not in (
            app_set.storage_orthography, app_set.input_orthography, app_set.output_orthography):
                try:
                    schema = OrthographySchema()
                    values = json.loads(unicode(request.body, request.charset))
                    state = h.get_state_object(values)
                    state.id = id
                    result = schema.to_python(values, state)
                    orthography = update_orthography(orthography, result)
                    # orthography will be False if there are no changes (cf. update_orthography).
                    if orthography:
                        Session.add(orthography)
                        Session.commit()
                        return orthography
                    else:
                        response.status_int = 400
                        return {'error':
                            u'The update request failed because the submitted data were not new.'}
                except h.JSONDecodeError:
                    response.status_int = 400
                    return h.JSONDecodeErrorResponse
                except Invalid, e:
                    response.status_int = 400
                    return {'errors': e.unpack_errors()}
            else:
                response.status = 403
                return {'error': u'Only administrators are permitted to update orthographies that are used in the active application settings.'}
Example #42
0
    def email_reset_password(self):
        """Reset the user's password and email them a new one.

        :URL: ``POST /login/email_reset_password``
        :request body: a JSON object with a ``"username"`` attribute.
        :returns: a dictionary with ``'valid_username'`` and ``'password_reset'``
            keys whose values are booleans.

        """
        try:
            schema = PasswordResetSchema()
            values = json.loads(unicode(request.body, request.charset))
            result = schema.to_python(values)
            user = Session.query(User).filter(
                User.username == result['username']).first()
            if user:
                try:
                    new_password = h.generate_password()
                    h.send_password_reset_email_to(user,
                                                   new_password,
                                                   config=config)
                    user.password = unicode(
                        h.encrypt_password(new_password, str(user.salt)))
                    Session.add(user)
                    Session.commit()
                    if os.path.split(config['__file__'])[-1] == 'test.ini':
                        return {
                            'valid_username': True,
                            'password_reset': True,
                            'new_password': new_password
                        }
                    else:
                        return {'valid_username': True, 'password_reset': True}
                except:  # socket.error was too specific ...
                    response.status_int = 500
                    return {'error': 'The server is unable to send email.'}
            else:
                response.status_int = 400
                return {'error': 'The username provided is not valid.'}
        except h.JSONDecodeError:
            response.status_int = 400
            return h.JSONDecodeErrorResponse
        except Invalid, e:
            response.status_int = 400
            return {'errors': e.unpack_errors()}
Example #43
0
    def test_a_initialize(self):
        """Initialize the database for /rememberedforms tests."""
        h.clear_all_models()
        administrator = h.generate_default_administrator()
        contributor = h.generate_default_contributor()
        viewer = h.generate_default_viewer()
        Session.add_all([administrator, contributor, viewer])
        Session.commit()

        _create_test_data(self.n)
        self._add_SEARCH_to_web_test_valid_methods()

        # Create an application settings where the contributor is unrestricted
        viewer, contributor, administrator = get_users()
        application_settings = h.generate_default_application_settings()
        application_settings.unrestricted_users = [contributor]
        Session.add(application_settings)
        Session.commit()
Example #44
0
    def test_a_initialize(self):
        """Initialize the database for /rememberedforms tests."""
        h.clear_all_models()
        administrator = h.generate_default_administrator()
        contributor = h.generate_default_contributor()
        viewer = h.generate_default_viewer()
        Session.add_all([administrator, contributor, viewer])
        Session.commit()

        _create_test_data(self.n)
        self._add_SEARCH_to_web_test_valid_methods()

        # Create an application settings where the contributor is unrestricted
        viewer, contributor, administrator = get_users()
        application_settings = h.generate_default_application_settings()
        application_settings.unrestricted_users = [contributor]
        Session.add(application_settings)
        Session.commit()
Example #45
0
    def update(self, id):
        """Update a morpheme language model and return it.

        :URL: ``PUT /morphemelanguagemodels/id``
        :Request body: JSON object representing the morpheme language model with updated attribute values.
        :param str id: the ``id`` value of the morpheme language model to be updated.
        :returns: the updated morpheme language model model.

        """
        morpheme_language_model = h.eagerload_morpheme_language_model(
            Session.query(MorphemeLanguageModel)).get(int(id))
        if morpheme_language_model:
            try:
                schema = MorphemeLanguageModelSchema()
                values = json.loads(unicode(request.body, request.charset))
                state = h.get_state_object(values)
                state.id = id
                data = schema.to_python(values, state)
                morpheme_language_model_dict = morpheme_language_model.get_dict(
                )
                morpheme_language_model = update_morpheme_language_model(
                    morpheme_language_model, data)
                # morpheme_language_model will be False if there are no changes (cf. update_morpheme_language_model).
                if morpheme_language_model:
                    backup_morpheme_language_model(
                        morpheme_language_model_dict)
                    Session.add(morpheme_language_model)
                    Session.commit()
                    return morpheme_language_model
                else:
                    response.status_int = 400
                    return {
                        'error':
                        u'The update request failed because the submitted data were not new.'
                    }
            except h.JSONDecodeError:
                response.status_int = 400
                return h.JSONDecodeErrorResponse
            except Invalid, e:
                response.status_int = 400
                return {'errors': e.unpack_errors()}
Example #46
0
    def update(self, id):
        """Update a syntactic category and return it.
        
        :URL: ``PUT /syntacticcategorys/id``
        :Request body: JSON object representing the syntactic category with updated attribute values.
        :param str id: the ``id`` value of the syntactic category to be updated.
        :returns: the updated syntactic category model.

        """
        syntactic_category = Session.query(SyntacticCategory).get(int(id))
        if syntactic_category:
            try:
                old_name = syntactic_category.name
                schema = SyntacticCategorySchema()
                values = json.loads(unicode(request.body, request.charset))
                state = h.get_state_object(values)
                state.id = id
                data = schema.to_python(values, state)
                syntactic_category = update_syntactic_category(
                    syntactic_category, data)
                # syntactic_category will be False if there are no changes (cf. update_syntactic_category).
                if syntactic_category:
                    Session.add(syntactic_category)
                    Session.commit()
                    if syntactic_category.name != old_name:
                        update_forms_referencing_this_category(
                            syntactic_category)
                    return syntactic_category
                else:
                    response.status_int = 400
                    return {
                        'error':
                        u'The update request failed because the submitted data were not new.'
                    }
            except h.JSONDecodeError:
                response.status_int = 400
                return h.JSONDecodeErrorResponse
            except Invalid, e:
                response.status_int = 400
                return {'errors': e.unpack_errors()}
Example #47
0
    def create(self):
        """Create a new keyboard resource and return it.

        :URL: ``POST /keyboards``
        :request body: JSON object representing the keyboard to create.
        :returns: the newly created keyboard.

        """
        try:
            schema = KeyboardSchema()
            values = json.loads(unicode(request.body, request.charset))
            data = schema.to_python(values)
            keyboard = create_new_keyboard(data)
            Session.add(keyboard)
            Session.commit()
            return keyboard
        except h.JSONDecodeError:
            response.status_int = 400
            return h.JSONDecodeErrorResponse
        except Invalid, e:
            response.status_int = 400
            return {'errors': e.unpack_errors()}
Example #48
0
    def create(self):
        """Create a new orthography resource and return it.

        :URL: ``POST /orthographies``
        :request body: JSON object representing the orthography to create.
        :returns: the newly created orthography.

        """
        try:
            schema = OrthographySchema()
            values = json.loads(unicode(request.body, request.charset))
            data = schema.to_python(values)
            orthography = create_new_orthography(data)
            Session.add(orthography)
            Session.commit()
            return orthography
        except h.JSONDecodeError:
            response.status_int = 400
            return h.JSONDecodeErrorResponse
        except Invalid, e:
            response.status_int = 400
            return {'errors': e.unpack_errors()}
Example #49
0
    def create(self):
        """Create a new speaker resource and return it.

        :URL: ``POST /speakers``
        :request body: JSON object representing the speaker to create.
        :returns: the newly created speaker.

        """
        try:
            schema = SpeakerSchema()
            values = json.loads(unicode(request.body, request.charset))
            data = schema.to_python(values)
            speaker = create_new_speaker(data)
            Session.add(speaker)
            Session.commit()
            return speaker
        except h.JSONDecodeError:
            response.status_int = 400
            return h.JSONDecodeErrorResponse
        except Invalid, e:
            response.status_int = 400
            return {'errors': e.unpack_errors()}
Example #50
0
    def create(self):
        """Create a new elicitation method resource and return it.

        :URL: ``POST /elicitationmethods``
        :request body: JSON object representing the elicitation method to create.
        :returns: the newly created elicitation method.

        """
        try:
            schema = ElicitationMethodSchema()
            values = json.loads(unicode(request.body, request.charset))
            result = schema.to_python(values)
            elicitation_method = create_new_elicitation_method(result)
            Session.add(elicitation_method)
            Session.commit()
            return elicitation_method
        except h.JSONDecodeError:
            response.status_int = 400
            return h.JSONDecodeErrorResponse
        except Invalid, e:
            response.status_int = 400
            return {'errors': e.unpack_errors()}
Example #51
0
File: pages.py Project: FieldDB/old
    def create(self):
        """Create a new page resource and return it.

        :URL: ``POST /pages``
        :request body: JSON object representing the page to create.
        :returns: the newly created page.

        """
        try:
            schema = PageSchema()
            values = json.loads(unicode(request.body, request.charset))
            data = schema.to_python(values)
            page = create_new_page(data)
            Session.add(page)
            Session.commit()
            return page
        except h.JSONDecodeError:
            response.status_int = 400
            return h.JSONDecodeErrorResponse
        except Invalid, e:
            response.status_int = 400
            return {'errors': e.unpack_errors()}
Example #52
0
    def create(self):
        """Create a new tag resource and return it.

        :URL: ``POST /tags``
        :request body: JSON object representing the tag to create.
        :returns: the newly created tag.

        """
        try:
            schema = TagSchema()
            values = json.loads(unicode(request.body, request.charset))
            data = schema.to_python(values)
            tag = create_new_tag(data)
            Session.add(tag)
            Session.commit()
            return tag
        except h.JSONDecodeError:
            response.status_int = 400
            return h.JSONDecodeErrorResponse
        except Invalid, e:
            response.status_int = 400
            return {'errors': e.unpack_errors()}
Example #53
0
    def create(self):
        """Create a new syntactic category resource and return it.

        :URL: ``POST /syntacticcategorys``
        :request body: JSON object representing the syntactic category to create.
        :returns: the newly created syntactic category.

        """
        try:
            schema = SyntacticCategorySchema()
            values = json.loads(unicode(request.body, request.charset))
            data = schema.to_python(values)
            syntactic_category = create_new_syntactic_category(data)
            Session.add(syntactic_category)
            Session.commit()
            return syntactic_category
        except h.JSONDecodeError:
            response.status_int = 400
            return h.JSONDecodeErrorResponse
        except Invalid, e:
            response.status_int = 400
            return {'errors': e.unpack_errors()}
Example #54
0
    def update(self, id):
        """Update a file and return it.
        
        :URL: ``PUT /files/id``
        :Request body: JSON object representing the file with updated attribute values.
        :param str id: the ``id`` value of the file to be updated.
        :returns: the updated file model.

        """
        file = h.eagerload_file(Session.query(File)).get(int(id))
        if file:
            unrestricted_users = h.get_unrestricted_users()
            user = session['user']
            if h.user_is_authorized_to_access_model(user, file, unrestricted_users):
                try:
                    if getattr(file, 'parent_file', None):
                        file = update_subinterval_referencing_file(file)
                    elif getattr(file, 'url', None):
                        file = update_externally_hosted_file(file)
                    else:
                        file = update_file(file)
                    # file will be False if there are no changes
                    if file:
                        Session.add(file)
                        Session.commit()
                        return file
                    else:
                        response.status_int = 400
                        return {'error':
                            u'The update request failed because the submitted data were not new.'}
                except h.JSONDecodeError:
                    response.status_int = 400
                    return h.JSONDecodeErrorResponse
                except Invalid, e:
                    response.status_int = 400
                    return {'errors': e.unpack_errors()}
            else:
                response.status_int = 403
                return h.unauthorized_msg
Example #55
0
    def update(self, id):
        """Update a form search and return it.
        
        :URL: ``PUT /formsearches/id``
        :Request body: JSON object representing the form search with updated
            attribute values.
        :param str id: the ``id`` value of the form search to be updated.
        :returns: the updated form search model.

        """
        form_search = h.eagerload_form_search(Session.query(FormSearch)).get(
            int(id))
        if form_search:
            try:
                schema = FormSearchSchema()
                values = json.loads(unicode(request.body, request.charset))
                state = h.get_state_object(values)
                state.id = id
                state.config = config
                data = schema.to_python(values, state)
                form_search = update_form_search(form_search, data)
                # form_search will be False if there are no changes (cf. update_form_search).
                if form_search:
                    Session.add(form_search)
                    Session.commit()
                    return form_search
                else:
                    response.status_int = 400
                    return {
                        'error':
                        u'The update request failed because the submitted data were not new.'
                    }
            except h.JSONDecodeError:
                response.status_int = 400
                return h.JSONDecodeErrorResponse
            except Invalid, e:
                response.status_int = 400
                return {'errors': e.unpack_errors()}
Example #56
0
    def update(self, id):
        """Update a corpus and return it.
        
        :URL: ``PUT /corpora/id``
        :Request body: JSON object representing the corpus with updated attribute values.
        :param str id: the ``id`` value of the corpus to be updated.
        :returns: the updated corpus model.

        """
        corpus = h.eagerload_corpus(Session.query(Corpus)).get(int(id))
        if corpus:
            try:
                schema = CorpusSchema()
                values = json.loads(unicode(request.body, request.charset))
                state = h.get_state_object(values)
                state.id = id
                state.config = config
                data = schema.to_python(values, state)
                corpus_dict = corpus.get_dict()
                corpus = update_corpus(corpus, data)
                # corpus will be False if there are no changes (cf. update_corpus).
                if corpus:
                    backup_corpus(corpus_dict)
                    Session.add(corpus)
                    Session.commit()
                    return corpus
                else:
                    response.status_int = 400
                    return {
                        'error':
                        u'The update request failed because the submitted data were not new.'
                    }
            except h.JSONDecodeError:
                response.status_int = 400
                return h.JSONDecodeErrorResponse
            except Invalid, e:
                response.status_int = 400
                return {'errors': e.unpack_errors()}