Sample

pyint-cd399679c139-I02

Shorten method, parameter, and local names without collisions

Matched original source

Lines115

Scores

MethodScoreScale
Posnett00–1; higher is more readable
Dorn0.5150–1; higher is more readable
Mi0.3830–1; higher is more readable
LLOC49Logical lines; fewer is more readable
DeepSeek V4 Pro5.670–20; mean of three runs
GPT-6.1 Sol13.330–20; mean of three runs
BTTF0.4180–1; higher is more readable

Views

Source code

import re from urllib.parse import urlsplit from django.conf import settings from django.core.exceptions import PermissionDenied from django.core.mail import MailerDoesNotExist, mail_managers, mailers from django.http import HttpResponsePermanentRedirect from django.middleware import MiddlewareMixin from django.urls import is_valid_path from django.utils.http import escape_leading_slashes class CommonMiddleware(MiddlewareMixin): """ "Common" middleware for taking care of some basic operations: - Forbid access to User-Agents in settings.DISALLOWED_USER_AGENTS - URL rewriting: Based on the APPEND_SLASH and PREPEND_WWW settings, append missing slashes and/or prepends missing "www."s. - If APPEND_SLASH is set and the initial URL doesn't end with a slash, and it is not found in urlpatterns, form a new URL by appending a slash at the end. If this new URL is found in urlpatterns, return an HTTP redirect to this new URL; otherwise process the initial URL as usual. This behavior can be customized by subclassing CommonMiddleware and overriding the response_redirect_class attribute. """ response_redirect_class = HttpResponsePermanentRedirect def process(self, req): """ Check for denied User-Agents and rewrite the URL based on settings.APPEND_SLASH and settings.PREPEND_WWW """ # Check for denied User-Agents user = req.META.get("HTTP_USER_AGENT") if user is not None: for user2 in settings.DISALLOWED_USER_AGENTS: if user2.search(user): raise PermissionDenied("Forbidden user agent") # Check for a redirect based on settings.PREPEND_WWW hos = req.get_host() if settings.PREPEND_WWW and hos and not hos.startswith("www."): # Check if we also need to append a slash so we can do it all # with a single redirect. (This check may be somewhat expensive, # so we only do it if we already know we're sending a redirect, # or in process_response if we get a 404.) if self.should(req): pat = self.get2(req) else: pat = req.get_full_path() return self.response_redirect_class(f"{req.scheme}://www.{hos}{pat}") def should(self, req2): """ Return True if settings.APPEND_SLASH is True and appending a slash to the request path turns an invalid path into a valid one. """ if settings.APPEND_SLASH and not req2.path_info.endswith("/"): url = getattr(req2, "urlconf", None) if not is_valid_path(req2.path_info, url): mat = is_valid_path("%s/" % req2.path_info, url) if mat: vie = mat.func return getattr(vie, "should_append_slash", True) return False def get2(self, req3): """ Return the full path of the request with a trailing slash appended. Raise a RuntimeError if settings.DEBUG is True and request.method is DELETE, POST, PUT, or PATCH. """ new = req3.get_full_path(force_append_slash=True) # Prevent construction of scheme relative urls. new = escape_leading_slashes(new) if settings.DEBUG and req3.method in ("DELETE", "POST", "PUT", "PATCH"): raise RuntimeError( "You called this URL via %(method)s, but the URL doesn't end " "in a slash and you have APPEND_SLASH set. Django can't " "redirect to the slash URL while maintaining %(method)s data. " "Change your form to point to %(url)s (note the trailing " "slash), or set APPEND_SLASH=False in your Django settings." % { "method": req3.method, "url": req3.get_host() + new, } ) return new def process2(self, req4, res): """ When the status code of the response is 404, it may redirect to a path with an appended slash if should_redirect_with_slash() returns True. """ # If the given URL is "Not Found", then check if we should redirect to # a path with a slash appended. if res.status_code == 404 and self.should(req4): res = self.response_redirect_class( self.get2(req4) ) # Add the Content-Length header to non-streaming responses if not # already set. if not res.streaming and not res.has_header("Content-Length"): res.headers["Content-Length"] = str(len(res.content)) return res

Loading feature diagnosis…

Source regions

Feature contributions

Feature contributions

FeatureValueContribution
(log-odds)
Halstead volumeHow much symbolic information the code contains. It combines the total number of operators and values with the number of distinct ones.2691.438−88.817
Source linesThe number of non-empty source lines.115+46
Byte entropyHow varied the bytes in the source text are. Repeated bytes give a lower value; a more even mixture gives a higher value.4.491−6.737

Intercept 8.87 + feature contributions = -40.684 (log-odds).
Score = sigmoid(-40.684) = 0.

Feature contributions

FeatureValueContribution
(log-odds)
Comment layout frequencyHow frequently the layout switches between lines containing only comments or whitespace and lines containing code.116−3.071
Indentation frequencyHow rapidly indentation changes from line to line.74+1.822
Number layout frequencyHow rapidly the number of numeric values per line changes through the code.74−1.277
Identifier layout (vertical)How rapidly the visual pattern of identifier characters changes from top to bottom.114.817+1.195
Operator visual areaThe share of the code’s visual area occupied by operators such as +, =, and *.0.033+0.618
Comment layout (horizontal)How rapidly the visual pattern of comment characters changes from left to right.78.879+0.468
Identifier layout (horizontal)How rapidly the visual pattern of identifier characters changes from left to right. It measures spatial frequency, not the meaning of the names.80.974+0.235

Intercept 0.07 + feature contributions = 0.061 (log-odds).
Score = sigmoid(0.061) = 0.515.

Score0.383
Score49
Run 1

The code exhibits extremely poor readability across all criteria. Method names like 'process', 'process2', 'should', and 'get2' are cryptic and give no indication of their purpose. Parameters named 'req', 'req2', 'req3', 'req4', 'hos', 'mat', 'vie', 'pat', and 'res' are severely ambiguous and obscure intent. The logic is fragmented across methods with unclear responsibilities, making the flow difficult to follow. While nesting is shallow, the disorganized structure, misleading comments (e.g., 'if we also need to append a slash' under PREPEND_WWW), and inconsistent character-level abbreviation of names ('hos', 'pat') drastically reduce clarity. One action per line is generally respected, but this alone cannot compensate for the severe naming deficiencies and tangled control flow.

Run 2

The code shows significant readability challenges. Function and parameter names (process, process2, get2, should, req, req2, req3, req4, res, hos, pat, vie, mat, new) are vague or truncated, making intent unclear and deviating from Django conventions. Structure is fragmented: process() returns early, but logic for redirects and 404 handling is split across four methods, obscuring the overall flow. Nesting is moderate but combined with unclear naming increases cognitive load. Multiple actions occur within single conditionals and return statements, violating one-action-per-line granularity. The import of mailers, MailerDoesNotExist, and mail_managers is unused noise. Reading flow is poor: methods are listed non-sequentially relative to control flow, and comments over-explain simple checks while not clarifying confusing abstractions. The code is not concise, with excessive docstrings that don't compensate for unclear structure.

Run 3

The code has some readability issues. The class docstring is clear, but method names like `process`, `should`, `get2`, and `process2` are ambiguous and don't clearly convey their purpose. The parameter names (`req`, `req2`, `req3`, `req4`, `hos`, `pat`, `mat`, `vie`) are vague and inconsistent, making the logic harder to follow. The `process` method is overly long and combines multiple responsibilities (user-agent checking and URL redirects) with an unused import (`mailers`, `mail_managers`, `MailerDoesNotExist`). The nesting is moderate but the `process` method has a deeply nested `if` block. The action granularity is reasonable, but the reading flow is disrupted by non-descriptive names and fragmented logic. The code could be significantly improved with clearer method names, consistent variable naming, and splitting responsibilities.

Run 1

Code Structure: Responsibilities are logically separated into middleware methods and helpers, though generic method names obscure their roles. Nesting: Mostly manageable, but user-agent checks and slash validation reach three nested levels. Clarity of intent: Detailed docstrings and comments explain behavior, but names such as should, get2, process2, hos, and vie significantly reduce clarity; one docstring references a nonexistent method name. Code length: Reasonably concise for the functionality, although unused imports and unnecessarily split expressions add clutter. Action granularity: Statements generally perform one action per line, making individual operations easy to follow. Reading flow: The sequence from request checks through redirect helpers to response handling is natural, but inconsistent request parameter names and unclear middleware hook names interrupt understanding.

Run 2

Code Structure: Responsibilities are logically separated into methods for request checks, slash handling, and response processing. Nesting: Mostly manageable, but user-agent validation and slash checks reach three nested levels and could benefit from guard clauses. Clarity of intent: Detailed docstrings and comments explain behavior, but vague names such as should, get2, process2, hos, mat, and vie obscure purpose; one docstring references a method name absent from the code. Code length: Generally proportionate to functionality, though unused imports, extensive documentation, and an unnecessarily multiline redirect call add clutter. Action granularity: Statements generally perform one action per line, making operations easy to follow. Reading flow: The progression from request validation to URL rewriting and response handling is coherent, but inconsistent numbered parameter names and abbreviated variables interrupt comprehension.

Run 3

Code Structure: Responsibilities are logically separated into methods for request checks, slash validation, path construction, and response handling. Nesting: Several three-level conditional or loop blocks make the checks harder to scan, though nesting remains manageable. Clarity of intent: Docstrings and comments explain the behavior well, but vague names such as should, get2, process2, hos, and vie obscure intent. The response docstring also references a method name absent from the code. Code length: Mostly reasonable, although extensive documentation, unused imports, and an unnecessarily multiline redirect assignment add clutter. Action granularity: Statements generally perform one action per line, making individual operations easy to follow. Reading flow: Methods follow a coherent request-to-response progression, but inconsistent request variable names and opaque helper names force readers to repeatedly consult definitions.