當前位置: 首頁>>代碼示例>>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;未經允許,請勿轉載。