當前位置: 首頁>>代碼示例>>Python>>正文


Python exc.DataError方法代碼示例

本文整理匯總了Python中sqlalchemy.exc.DataError方法的典型用法代碼示例。如果您正苦於以下問題:Python exc.DataError方法的具體用法?Python exc.DataError怎麽用?Python exc.DataError使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在sqlalchemy.exc的用法示例。


在下文中一共展示了exc.DataError方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: related_add

# 需要導入模塊: from sqlalchemy import exc [as 別名]
# 或者: from sqlalchemy.exc import DataError [as 別名]
def related_add(modelname, entry_id, colname, relmodelname, rel_id):
    klass = get_model(modelname)
    relklass = get_model(relmodelname)
    metadata = models.get_column_metadata(klass, colname)
    # fetch parent and related objects
    dbrow = webhelpers.get_row(klass, entry_id)
    reldbrow = webhelpers.get_row(relklass, rel_id)
    # now add using appropriate semantics
    if metadata.uselist:
        col = getattr(dbrow, colname)
        col.append(reldbrow)
    else:
        setattr(dbrow, colname, reldbrow)
    try:
        webhelpers.dbsession.commit()
    except (DataError, IntegrityError), err:
        webhelpers.dbsession.rollback()
        raise 
開發者ID:kdart,項目名稱:pycopia,代碼行數:20,代碼來源:webservice.py

示例2: related_remove

# 需要導入模塊: from sqlalchemy import exc [as 別名]
# 或者: from sqlalchemy.exc import DataError [as 別名]
def related_remove(modelname, entry_id, colname, relmodelname, rel_id):
    klass = get_model(modelname)
    relklass = get_model(relmodelname)
    metadata = models.get_column_metadata(klass, colname)
    # fetch parent and related objects
    dbrow = webhelpers.get_row(klass, entry_id)
    if metadata.uselist:
        reldbrow = webhelpers.get_row(relklass, rel_id)
        col = getattr(dbrow, colname)
        col.remove(reldbrow)
    else:
        if metadata.nullable:
            setattr(dbrow, colname, None)
        else:
            raise DataError("Removing non-nullable relation")
    try:
        webhelpers.dbsession.commit()
    except (DataError, IntegrityError), err:
        webhelpers.dbsession.rollback()
        raise 
開發者ID:kdart,項目名稱:pycopia,代碼行數:22,代碼來源:webservice.py

示例3: test_integer_incorrect_range

# 需要導入模塊: from sqlalchemy import exc [as 別名]
# 或者: from sqlalchemy.exc import DataError [as 別名]
def test_integer_incorrect_range(self):
        """A decimal is not an integer"""
        with self.assertRaises(DataError):
            with self.session.begin():
                creator, survey = self._create_blank_survey()
                survey.nodes = [
                    models.construct_survey_node(
                        node=models.construct_node(
                            type_constraint='integer',
                            title={'English': 'node'},
                        ),
                        sub_surveys=[
                            models.SubSurvey(
                                buckets=[
                                    models.construct_bucket(
                                        bucket_type='integer',
                                        bucket='(1.3, 2.3]'
                                    ),
                                ],
                            ),
                        ],
                    ),
                ]
                self.session.add(creator) 
開發者ID:SEL-Columbia,項目名稱:dokomoforms,代碼行數:26,代碼來源:test_model.py

示例4: handle_chosen_inline_result

# 需要導入模塊: from sqlalchemy import exc [as 別名]
# 或者: from sqlalchemy.exc import DataError [as 別名]
def handle_chosen_inline_result(bot, update, session, user):
    """Save the chosen inline result."""
    result = update.chosen_inline_result
    poll_id = result.result_id

    try:
        poll = session.query(Poll).get(poll_id)

    except DataError:
        # Possile if the poll has been shared too often and
        # the inline result is picked despite saying otherwise.
        return

    try:
        reference = Reference(
            poll, ReferenceType.inline.name, inline_message_id=result.inline_message_id,
        )
        session.add(reference)
        session.commit()
    except UniqueViolation:
        # I don't know how this can happen, but it happens.
        return

    update_reference(session, bot, poll, reference)
    increase_user_stat(session, user, "inline_shares") 
開發者ID:Nukesor,項目名稱:ultimate-poll-bot,代碼行數:27,代碼來源:inline_result_handler.py

示例5: post

# 需要導入模塊: from sqlalchemy import exc [as 別名]
# 或者: from sqlalchemy.exc import DataError [as 別名]
def post(self):
        results = []
        self.sg_entries = request.json

        self.check_permissions()
        self.prepare_import()

        for sg_entry in self.filtered_entries():
            try:
                data = self.extract_data(sg_entry)
                result_entry = self.import_entry(data)
                results.append(result_entry)
            except ShotgunEntryImportFailed as exception:
                current_app.logger.warning(exception)
            except KeyError as exception:
                current_app.logger.warning(exception)
                current_app.logger.error(
                    "Your data is not properly formatted: %s" % sg_entry
                )
            except IntegrityError as exception:
                current_app.logger.error(exception)
                current_app.logger.error(
                    "Data information are duplicated or wrong: %s" % sg_entry
                )
                raise
            except DataError as exception:
                current_app.logger.error(exception)
                current_app.logger.error(
                    "Data cannot be stored (schema error)" % sg_entry
                )
                raise

        self.post_processing()

        return fields.serialize_models(results), 200 
開發者ID:cgwire,項目名稱:zou,代碼行數:37,代碼來源:base.py

示例6: get_time_spents

# 需要導入模塊: from sqlalchemy import exc [as 別名]
# 或者: from sqlalchemy.exc import DataError [as 別名]
def get_time_spents(person_id, date):
    """
    Return time spents for given person and date.
    """
    try:
        time_spents = TimeSpent.query.filter_by(
            person_id=person_id, date=date
        ).all()
    except DataError:
        raise WrongDateFormatException
    return fields.serialize_list(time_spents) 
開發者ID:cgwire,項目名稱:zou,代碼行數:13,代碼來源:time_spents_service.py

示例7: create_or_update_time_spent

# 需要導入模塊: from sqlalchemy import exc [as 別名]
# 或者: from sqlalchemy.exc import DataError [as 別名]
def create_or_update_time_spent(task_id, person_id, date, duration, add=False):
    """
    Create a new time spent if it doesn't exist. If it exists, it update it
    with the new duratin and returns it from the database.
    """
    try:
        time_spent = TimeSpent.get_by(
            task_id=task_id, person_id=person_id, date=date
        )
    except DataError:
        raise WrongDateFormatException

    if time_spent is not None:
        if duration == 0:
            time_spent.delete()
        elif add:
            time_spent.update({"duration": time_spent.duration + duration})
        else:
            time_spent.update({"duration": duration})
        events.emit("time-spent:update", {"time_spent_id": str(time_spent.id)})
    else:
        time_spent = TimeSpent.create(
            task_id=task_id, person_id=person_id, date=date, duration=duration
        )
        events.emit("time-spent:new", {"time_spent_id": str(time_spent.id)})

    task = Task.get(task_id)
    task.duration = 0
    time_spents = TimeSpent.get_all_by(task_id=task_id)
    for time_spent in time_spents:
        task.duration += time_spent.duration
    task.save()
    clear_task_cache(task_id)
    events.emit("task:update", {"task_id": task_id})

    return time_spent.serialize() 
開發者ID:cgwire,項目名稱:zou,代碼行數:38,代碼來源:tasks_service.py

示例8: test_club_name_overflow

# 需要導入模塊: from sqlalchemy import exc [as 別名]
# 或者: from sqlalchemy.exc import DataError [as 別名]
def test_club_name_overflow(session):
    too_long_name = "blahblah" * 8
    too_long_club = mc.Clubs(name=too_long_name,
                             country=mco.Countries(name=u"foo", confederation=enums.ConfederationType.fifa))
    with pytest.raises(DataError):
        session.add(too_long_club)
        session.commit() 
開發者ID:soccermetrics,項目名稱:marcotti,代碼行數:9,代碼來源:test_club.py

示例9: test_country_name_overflow_error

# 需要導入模塊: from sqlalchemy import exc [as 別名]
# 或者: from sqlalchemy.exc import DataError [as 別名]
def test_country_name_overflow_error(session):
    """Country 003: Verify error if country name exceeds field length."""
    too_long_name = "blahblah" * 8
    too_long_country = mco.Countries(name=unicode(too_long_name), confederation=enums.ConfederationType.north_america)
    with pytest.raises(DataError):
        session.add(too_long_country)
        session.commit() 
開發者ID:soccermetrics,項目名稱:marcotti,代碼行數:9,代碼來源:test_overview.py

示例10: test_country_code_error

# 需要導入模塊: from sqlalchemy import exc [as 別名]
# 或者: from sqlalchemy.exc import DataError [as 別名]
def test_country_code_error(session):
    too_long_code = "BOGUS"
    country = mco.Countries(name=unicode("Fredonia"), code=too_long_code,
                            confederation=enums.ConfederationType.south_america)
    with pytest.raises(DataError):
        session.add(country)
        session.commit() 
開發者ID:soccermetrics,項目名稱:marcotti,代碼行數:9,代碼來源:test_overview.py

示例11: test_competition_name_overflow_error

# 需要導入模塊: from sqlalchemy import exc [as 別名]
# 或者: from sqlalchemy.exc import DataError [as 別名]
def test_competition_name_overflow_error(session):
    """Competition 003: Verify error if competition name exceeds field length."""
    too_long_name = "leaguename" * 9
    record = mco.Competitions(name=unicode(too_long_name), level=2)
    with pytest.raises(DataError):
        session.add(record)
        session.commit() 
開發者ID:soccermetrics,項目名稱:marcotti,代碼行數:9,代碼來源:test_overview.py

示例12: register_errors

# 需要導入模塊: from sqlalchemy import exc [as 別名]
# 或者: from sqlalchemy.exc import DataError [as 別名]
def register_errors(blueprint):
    @blueprint.errorhandler(InvalidEmailError)
    def invalid_format(error):
        # Please not that InvalidEmailError is re-raised for InvalidEmail or InvalidPhone,
        # work should be done in the utils app to tidy up these errors.
        current_app.logger.info(error)
        return jsonify(status_code=400,
                       errors=[{"error": error.__class__.__name__, "message": str(error)}]), 400

    @blueprint.errorhandler(InvalidRequest)
    def invalid_data(error):
        current_app.logger.info(error)
        response = jsonify(error.to_dict_v2()), error.status_code
        return response

    @blueprint.errorhandler(JsonSchemaValidationError)
    def validation_error(error):
        current_app.logger.info(error)
        return jsonify(json.loads(error.message)), 400

    @blueprint.errorhandler(JobIncompleteError)
    def job_incomplete_error(error):
        return jsonify(error.to_dict_v2()), 500

    @blueprint.errorhandler(NoResultFound)
    @blueprint.errorhandler(DataError)
    def no_result_found(e):
        current_app.logger.info(e)
        return jsonify(status_code=404,
                       errors=[{"error": e.__class__.__name__, "message": "No result found"}]), 404

    @blueprint.errorhandler(AuthError)
    def auth_error(error):
        current_app.logger.info('API AuthError, client: {} error: {}'.format(request.headers.get('User-Agent'), error))
        return jsonify(error.to_dict_v2()), error.code

    @blueprint.errorhandler(Exception)
    def internal_server_error(error):
        current_app.logger.exception(error)
        return jsonify(status_code=500,
                       errors=[{"error": error.__class__.__name__, "message": 'Internal server error'}]), 500 
開發者ID:alphagov,項目名稱:notifications-api,代碼行數:43,代碼來源:errors.py

示例13: test_data_errors

# 需要導入模塊: from sqlalchemy import exc [as 別名]
# 或者: from sqlalchemy.exc import DataError [as 別名]
def test_data_errors(app_for_test):
    with app_for_test.test_request_context():
        with app_for_test.test_client() as client:
            response = client.get(url_for('v2_under_test.raising_data_error'))
            assert response.status_code == 404
            error = response.json
            assert error == {"status_code": 404,
                             "errors": [{"error": "DataError", "message": "No result found"}]} 
開發者ID:alphagov,項目名稱:notifications-api,代碼行數:10,代碼來源:test_errors.py

示例14: test_get_user_invalid_id

# 需要導入模塊: from sqlalchemy import exc [as 別名]
# 或者: from sqlalchemy.exc import DataError [as 別名]
def test_get_user_invalid_id(notify_db_session):
    with pytest.raises(DataError):
        get_user_by_id(user_id="blah") 
開發者ID:alphagov,項目名稱:notifications-api,代碼行數:5,代碼來源:test_users_dao.py

示例15: test_reject_incorrect_answer_syntax

# 需要導入模塊: from sqlalchemy import exc [as 別名]
# 或者: from sqlalchemy.exc import DataError [as 別名]
def test_reject_incorrect_answer_syntax(self):
        with self.session.begin():
            creator = models.Administrator(name='creator')
            survey = models.Survey(
                title={'English': 'survey'},
                nodes=[
                    models.construct_survey_node(
                        node=models.construct_node(
                            type_constraint='integer',
                            title={'English': 'integer question'},
                        ),
                    ),
                ],
            )
            creator.surveys = [survey]

            self.session.add(creator)

        with self.assertRaises(DataError):
            with self.session.begin():
                the_survey = self.session.query(models.Survey).one()
                submission = models.PublicSubmission(
                    survey=the_survey,
                    answers=[
                        models.construct_answer(
                            survey_node=the_survey.nodes[0],
                            type_constraint='integer',
                            answer='not an integer',
                        ),
                    ],
                )

                self.session.add(submission) 
開發者ID:SEL-Columbia,項目名稱:dokomoforms,代碼行數:35,代碼來源:test_model.py


注:本文中的sqlalchemy.exc.DataError方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。