当前位置: 首页>>代码示例>>Python>>正文


Python utils.OperationalError方法代码示例

本文整理汇总了Python中django.db.utils.OperationalError方法的典型用法代码示例。如果您正苦于以下问题:Python utils.OperationalError方法的具体用法?Python utils.OperationalError怎么用?Python utils.OperationalError使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在django.db.utils的用法示例。


在下文中一共展示了utils.OperationalError方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: healthcheck_view

# 需要导入模块: from django.db import utils [as 别名]
# 或者: from django.db.utils import OperationalError [as 别名]
def healthcheck_view(request):
    content_type = 'application/health+json'
    database_accessible = True

    try:
        connections['default'].cursor()
    except ImproperlyConfigured:
        # Database is not configured (DATABASE_URL may not be set)
        database_accessible = False
    except OperationalError:
        # Database is not accessible
        database_accessible = False

    if database_accessible:
        return JsonResponse({ 'status': 'ok' }, content_type=content_type)

    return JsonResponse({ 'status': 'fail' }, status=503, content_type=content_type) 
开发者ID:apiaryio,项目名称:polls-api,代码行数:19,代码来源:urls.py

示例2: ready

# 需要导入模块: from django.db import utils [as 别名]
# 或者: from django.db.utils import OperationalError [as 别名]
def ready(self):

        for field_name in self._get_all_workflow_fields():
            try:
                workflows = self.get_model('Workflow').objects.filter(field_name=field_name)
                if workflows.count() == 0:
                    LOGGER.warning("%s field doesn't seem have any workflow defined in database. You should create its workflow" % field_name)
            except (OperationalError, ProgrammingError):
                pass

        from river.config import app_config

        if app_config.INJECT_MODEL_ADMIN:
            for model_class in self._get_all_workflow_classes():
                self._register_hook_inlines(model_class)

        LOGGER.debug('RiverApp is loaded.') 
开发者ID:javrasya,项目名称:django-river,代码行数:19,代码来源:apps.py

示例3: actions_have_consistent_hashes

# 需要导入模块: from django.db import utils [as 别名]
# 或者: from django.db.utils import OperationalError [as 别名]
def actions_have_consistent_hashes(app_configs, **kwargs):
    errors = []
    try:
        Action = apps.get_model("recipes", "Action")
        actions = list(Action.objects.filter(implementation__isnull=False))
    except (ProgrammingError, OperationalError, ImproperlyConfigured) as e:
        errors.append(Info(f"Could not retrieve actions: {e}", id=INFO_COULD_NOT_RETRIEVE_ACTIONS))
    else:
        for action in actions:
            if action.compute_implementation_hash() != action.implementation_hash:
                msg = "Action '{action}' (id={action.id}) has a mismatched hash".format(
                    action=action
                )
                errors.append(Error(msg, id=ERROR_MISMATCHED_ACTION_HASH))

    return errors 
开发者ID:mozilla,项目名称:normandy,代码行数:18,代码来源:checks.py

示例4: remove_field

# 需要导入模块: from django.db import utils [as 别名]
# 或者: from django.db.utils import OperationalError [as 别名]
def remove_field(self, model, field):
        if isinstance(field, GeometryField) and field.spatial_index:
            qn = self.connection.ops.quote_name
            sql = self.sql_drop_spatial_index % {
                'index': qn(self._create_spatial_index_name(model, field)),
                'table': qn(model._meta.db_table),
            }
            try:
                self.execute(sql)
            except OperationalError:
                logger.error(
                    "Couldn't remove spatial index: %s (may be expected "
                    "if your storage engine doesn't support them)." % sql
                )

        super(MySQLGISSchemaEditor, self).remove_field(model, field) 
开发者ID:lanbing510,项目名称:GTDWeb,代码行数:18,代码来源:schema.py

示例5: process_request

# 需要导入模块: from django.db import utils [as 别名]
# 或者: from django.db.utils import OperationalError [as 别名]
def process_request(self, request):
        """Check before super."""
        connection.set_schema_to_public()

        if not is_no_auth(request):
            if hasattr(request, "user") and hasattr(request.user, "username"):
                username = request.user.username
                try:
                    if username not in USER_CACHE:
                        USER_CACHE[username] = User.objects.get(username=username)
                        LOG.debug(f"User added to cache: {username}")
                except User.DoesNotExist:
                    return HttpResponseUnauthorizedRequest()
                if not request.user.admin and request.user.access is None:
                    LOG.warning("User %s is does not have permissions for Cost Management.", username)
                    raise PermissionDenied()
            else:
                return HttpResponseUnauthorizedRequest()
        try:
            super().process_request(request)
        except OperationalError as err:
            LOG.error("Request resulted in OperationalError: %s", err)
            DB_CONNECTION_ERRORS_COUNTER.inc()
            return HttpResponseFailedDependency({"source": "Database", "exception": err}) 
开发者ID:project-koku,项目名称:koku,代码行数:26,代码来源:middleware.py

示例6: test_process_operational_error_return_424

# 需要导入模块: from django.db import utils [as 别名]
# 或者: from django.db.utils import OperationalError [as 别名]
def test_process_operational_error_return_424(self):
        """Test OperationalError causes 424 Reponse."""
        user_data = self._create_user_data()
        customer = self._create_customer_data()
        request_context = self._create_request_context(
            customer, user_data, create_customer=True, create_tenant=True, is_admin=True, is_cost_management=True
        )
        mock_request = request_context["request"]
        mock_request.path = "/api/v1/tags/aws/"
        mock_request.META["QUERY_STRING"] = ""

        with patch("koku.middleware.Customer.objects") as mock_customer:
            mock_customer.filter.side_effect = OperationalError

            middleware = IdentityHeaderMiddleware()
            response = middleware.process_request(mock_request)
            self.assertEqual(response.status_code, status.HTTP_424_FAILED_DEPENDENCY) 
开发者ID:project-koku,项目名称:koku,代码行数:19,代码来源:tests_middleware.py

示例7: retry_database_query

# 需要导入模块: from django.db import utils [as 别名]
# 或者: from django.db.utils import OperationalError [as 别名]
def retry_database_query(no_arg_func=None, max_tries=5, base_ms_delay=1000, max_ms_delay=30000):
    """Wraps the decorated function so that it is retried with exponential backoff if any operational database errors
    (disconnect, too many connections, etc) occurs. On the first retry, the delay is a random number of milliseconds
    between 0 and base_ms_delay. The upper bound is then doubled for each successive retry. A retry delay will not
    exceed max_ms_delay milliseconds.

    :param no_arg_func: The function to retry (only populated if decorator used without args)
    :type no_arg_func: function
    :param max_tries: The maximum number of times to call the function
    :type max_tries: int
    :param base_ms_delay: The base time to delay in milliseconds before retrying the function
    :type base_ms_delay: int
    :param max_ms_delay: The maximum time to delay in milliseconds
    :type max_ms_delay: int
    """

    return retry(no_arg_func=no_arg_func, ex_class=OperationalError, max_tries=max_tries, base_ms_delay=base_ms_delay,
                 max_ms_delay=max_ms_delay) 
开发者ID:ngageoint,项目名称:scale,代码行数:20,代码来源:retry.py

示例8: handle

# 需要导入模块: from django.db import utils [as 别名]
# 或者: from django.db.utils import OperationalError [as 别名]
def handle(self, *args, **options):
        changed = set()

        self.stdout.write("Checking...")
        for db in settings.DATABASES.keys():
            try:
                executor = MigrationExecutor(connections[db])
            except OperationalError:
                sys.exit("Unable to check migrations: cannot connect to database\n")

            autodetector = MigrationAutodetector(
                executor.loader.project_state(), ProjectState.from_apps(apps),
            )
            changed.update(autodetector.changes(graph=executor.loader.graph).keys())

        changed -= set(options["ignore"])

        if changed:
            sys.exit(
                "Apps with model changes but no corresponding migration file: %(changed)s\n"
                % {"changed": list(changed)}
            )
        else:
            sys.stdout.write("All migration files present\n") 
开发者ID:vintasoftware,项目名称:django-react-boilerplate,代码行数:26,代码来源:has_missing_migrations.py

示例9: generate_part_thumbnails

# 需要导入模块: from django.db import utils [as 别名]
# 或者: from django.db.utils import OperationalError [as 别名]
def generate_part_thumbnails(self):
        from .models import Part

        print("InvenTree: Checking Part image thumbnails")

        try:
            for part in Part.objects.all():
                if part.image:
                    url = part.image.thumbnail.name
                    loc = os.path.join(settings.MEDIA_ROOT, url)
                    
                    if not os.path.exists(loc):
                        print("InvenTree: Generating thumbnail for Part '{p}'".format(p=part.name))
                        try:
                            part.image.render_variations(replace=False)
                        except FileNotFoundError:
                            print("Image file missing")
                            part.image = None
                            part.save()
        except (OperationalError, ProgrammingError):
            print("Could not generate Part thumbnails") 
开发者ID:inventree,项目名称:InvenTree,代码行数:23,代码来源:apps.py

示例10: generate_company_thumbs

# 需要导入模块: from django.db import utils [as 别名]
# 或者: from django.db.utils import OperationalError [as 别名]
def generate_company_thumbs(self):

        from .models import Company

        print("InvenTree: Checking Company image thumbnails")

        try:
            for company in Company.objects.all():
                if company.image:
                    url = company.image.thumbnail.name
                    loc = os.path.join(settings.MEDIA_ROOT, url)

                    if not os.path.exists(loc):
                        print("InvenTree: Generating thumbnail for Company '{c}'".format(c=company.name))
                        try:
                            company.image.render_variations(replace=False)
                        except FileNotFoundError:
                            print("Image file missing")
                            company.image = None
                            company.save()
        except (OperationalError, ProgrammingError):
            print("Could not generate Company thumbnails") 
开发者ID:inventree,项目名称:InvenTree,代码行数:24,代码来源:apps.py

示例11: check_database_connected

# 需要导入模块: from django.db import utils [as 别名]
# 或者: from django.db.utils import OperationalError [as 别名]
def check_database_connected(app_configs, **kwargs):
    """
    A Django check to see if connecting to the configured default
    database backend succeeds.
    """
    errors = []

    try:
        connection.ensure_connection()
    except OperationalError as e:
        msg = "Could not connect to database: {!s}".format(e)
        errors.append(checks.Error(msg, id=health.ERROR_CANNOT_CONNECT_DATABASE))
    except ImproperlyConfigured as e:
        msg = 'Datbase misconfigured: "{!s}"'.format(e)
        errors.append(checks.Error(msg, id=health.ERROR_MISCONFIGURED_DATABASE))
    else:
        if not connection.is_usable():
            errors.append(
                checks.Error(
                    "Database connection is not usable",
                    id=health.ERROR_UNUSABLE_DATABASE,
                )
            )

    return errors 
开发者ID:mozilla-services,项目名称:python-dockerflow,代码行数:27,代码来源:checks.py

示例12: create_profile

# 需要导入模块: from django.db import utils [as 别名]
# 或者: from django.db.utils import OperationalError [as 别名]
def create_profile(sender, **kwargs):
    user = kwargs["instance"]
    if kwargs["created"]:
        default_plan = Plan.objects.get(pk=Plan.DEFAULT_PK)
        up = Profile(user=user, plan=default_plan)
        up.save()
        try:
            for tg in TalkGroupAccess.objects.filter(default_group=True):
                up.talkgroup_access.add(tg)
        except OperationalError:
            pass
        try:
            new_user_email = SiteOption.objects.get(name='SEND_ADMIN_EMAIL_ON_NEW_USER')
            if new_user_email.value_boolean_or_string() == True:
                send_mail(
                      'New {} User {}'.format(settings.SITE_TITLE, user.username),
                      'New User {} {} Username {} Email {} just registered'.format(user.first_name, user.last_name, user.username, user.email),
                      settings.SERVER_EMAIL,
                      [ mail for name, mail in settings.ADMINS],
                      fail_silently=False,
                     )
        except (SiteOption.DoesNotExist, OperationalError):
            pass 
开发者ID:ScanOC,项目名称:trunk-player,代码行数:25,代码来源:models.py

示例13: hydrate_models_and_permissions

# 需要导入模块: from django.db import utils [as 别名]
# 或者: from django.db.utils import OperationalError [as 别名]
def hydrate_models_and_permissions(app_config):
    """
    Setup content types, base permissions and data source
    specific permission groups for use in the admin.
    """
    try:
        create_contenttypes(app_config, interactive=False, verbosity=4)
    except OperationalError as e:
        logger.error("Error creating content-types: %s" % e)

    try:
        create_permissions(app_config, interactive=False, verbosity=4)
    except OperationalError as e:
        logger.error("Error creating permissions: %s" % e)

    try:
        build_permission_groups(app_config.name)
    except (OperationalError, AppRegistryNotReady) as e:
        logger.error("Error creating permission groups: %s" % e)

    try:
        build_tag_permission_group()
    except (OperationalError, AppRegistryNotReady) as e:
        logger.error("Error creating tagging perm group: %s" % e) 
开发者ID:propublica,项目名称:django-collaborative,代码行数:26,代码来源:permissions.py

示例14: handle

# 需要导入模块: from django.db import utils [as 别名]
# 或者: from django.db.utils import OperationalError [as 别名]
def handle(self, *args, **options):
        max_retries = options['max_retries']
        poll_seconds = options['poll_seconds']

        for retry in range(max_retries):
            try:
                connection.ensure_connection()
            except OperationalError as ex:
                self.stdout.write(
                    'Database unavailable on attempt {attempt}/{max_retries}:'
                    ' {error}'.format(
                        attempt=retry + 1,
                        max_retries=max_retries,
                        error=ex))
                time.sleep(poll_seconds)
            else:
                break
        else:
            self.stdout.write(self.style.ERROR('Database unavailable'))
            sys.exit(1) 
开发者ID:doccano,项目名称:doccano,代码行数:22,代码来源:wait_for_db.py

示例15: process_exception

# 需要导入模块: from django.db import utils [as 别名]
# 或者: from django.db.utils import OperationalError [as 别名]
def process_exception(self, request, exception):
        if isinstance(exception, requests.exceptions.ConnectionError):
            logging.getLogger(ERROR_LOGGER).exception(exception)
            messages.error(request, "Could not connect to resource: {}. Please check if all the resources (Elasticsearch) are available!".format(exception.request.url))
            template_data = {'STATIC_URL': STATIC_URL, 'allowed_datasets': None, 'language_models': None}
            return redirect("/", context=template_data)

        if isinstance(exception, OperationalError):
            logging.getLogger(ERROR_LOGGER).exception(exception)
            messages.error(request, "Error, please refresh the page!".format(exception))
            template_data = {'STATIC_URL': STATIC_URL, 'allowed_datasets': None, 'language_models': None}
            return redirect("/", context=template_data)

        else:
            logging.getLogger(ERROR_LOGGER).exception(exception)
            messages.error(request, "Error, please try again or contact the developers: {}!".format(exception))
            template_data = {'STATIC_URL': STATIC_URL, 'allowed_datasets': None, 'language_models': None}
            return redirect("/", context=template_data) 
开发者ID:texta-tk,项目名称:texta,代码行数:20,代码来源:ExceptionHandlerMiddleware.py


注:本文中的django.db.utils.OperationalError方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。