Sample

pyint-a8e5471be73f-I12

Inline all eligible single-use intermediate local variables

Matched original source

Lines115

Scores

MethodScoreScale
Posnett00–1; higher is more readable
Dorn0.4890–1; higher is more readable
Mi0.4030–1; higher is more readable
LLOC48Logical lines; fewer is more readable
DeepSeek V4 Pro17.330–20; mean of three runs
GPT-6.1 Sol170–20; mean of three runs
BTTF0.4840–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_request(self, request): """ Check for denied User-Agents and rewrite the URL based on settings.APPEND_SLASH and settings.PREPEND_WWW """ # Check for denied User-Agents user_agent = request.META.get("HTTP_USER_AGENT") if user_agent is not None: for user_agent_regex in settings.DISALLOWED_USER_AGENTS: if user_agent_regex.search(user_agent): raise PermissionDenied("Forbidden user agent") # Check for a redirect based on settings.PREPEND_WWW host = request.get_host() if settings.PREPEND_WWW and host and not host.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_redirect_with_slash(request): path = self.get_full_path_with_slash(request) else: path = request.get_full_path() return self.response_redirect_class(f"{request.scheme}://www.{host}{path}") def should_redirect_with_slash(self, request): """ 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 request.path_info.endswith("/"): urlconf = getattr(request, "urlconf", None) if not is_valid_path(request.path_info, urlconf): match = is_valid_path("%s/" % request.path_info, urlconf) if match: return getattr((match.func), "should_append_slash", True) return False def get_full_path_with_slash(self, request): """ 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_path = request.get_full_path(force_append_slash=True) # Prevent construction of scheme relative urls. new_path = escape_leading_slashes(new_path) if settings.DEBUG and request.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": request.method, "url": request.get_host() + new_path, } ) return new_path def process_response(self, request, response): """ 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 response.status_code == 404 and self.should_redirect_with_slash(request): response = self.response_redirect_class( self.get_full_path_with_slash(request) ) # Add the Content-Length header to non-streaming responses if not # already set. if not response.streaming and not response.has_header("Content-Length"): response.headers["Content-Length"] = str(len(response.content)) return response

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.2665.702−87.968
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.505−6.757

Intercept 8.87 + feature contributions = -39.855 (log-odds).
Score = sigmoid(-39.855) = 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.932+1.197
Operator visual areaThe share of the code’s visual area occupied by operators such as +, =, and *.0.032+0.636
Comment layout (horizontal)How rapidly the visual pattern of comment characters changes from left to right.86.871+0.597
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.86.991−0.019

Intercept 0.07 + feature contributions = -0.046 (log-odds).
Score = sigmoid(-0.046) = 0.489.

Score0.403
Score48
Run 1

The code is well-structured and follows Django middleware conventions, with clear separation of concerns across methods. It demonstrates good action granularity, typically performing one logical action per line. Nesting is minimal and manageable, with early returns and guard-style conditions enhancing readability. The abundant docstrings and comments provide clear intent, explaining not just what the code does but why. Variable and method names are descriptive. The code length is appropriate for the functionality—concise without sacrificing clarity. The reading flow is natural, with request processing logic followed by response handling. Minor deductions: the method `should_redirect_with_slash` contains slightly more complex conditional logic, and the long RuntimeError message string interrupts flow somewhat, though it is necessary for user guidance. Overall, this is highly readable production-quality code.

Run 2

The code is highly readable due to its clear structure, minimal nesting, and natural reading flow. Each method has a single responsibility with descriptive names and docstrings explaining intent. Action granularity is mostly one action per line, and the code is concise without being overly brief. Nesting is shallow, with only small conditional blocks. The primary minor deductions are for a few multi-line statements (e.g., the RuntimeError message and the f-string redirect) that slightly interrupt reading flow, and one slightly long if-condition. Overall, the code closely follows clean code principles.

Run 3

The code is highly readable with clear class and method structure, good docstrings, and logical organization. Nesting is minimal with early returns and guard clauses. Each method has a single, well-defined purpose. Variable and method names effectively communicate intent. The code is concise, avoids unnecessary repetition, and maintains a consistent action-per-line style. Reading flow is natural, with comments explaining non-obvious decisions. Minor deductions for the slightly complex `should_redirect_with_slash` logic and the sparse comment in the middle of that method, which slightly interrupt flow.

Run 1

Code Structure: Well-organized middleware methods separate request checks, slash handling, and response processing. Nesting: Mostly shallow, though user-agent checks and slash validation reach three nested levels and could use guard clauses. Clarity of intent: Descriptive method names, docstrings, and comments clearly explain behavior and important redirect constraints. Code length: Generally proportionate to functionality, but lengthy documentation, some redundant comments, and unused imports add clutter. Action granularity: Statements generally perform one action per line; multiline expressions remain readable. Reading flow: Methods follow a natural request-to-helper-to-response progression, with consistent formatting. Minor distractions include an unnecessary blank line, redundant parentheses around match.func, and mixed string-formatting styles.

Run 2

Code Structure: Well-organized middleware with separate methods for request handling, slash validation, path construction, and response handling. Nesting: Generally moderate, but user-agent checks and slash validation reach three levels and could be flattened. Clarity of intent: Descriptive names, docstrings, and explanatory comments make behavior clear; unused imports introduce minor distraction. Code length: Mostly proportionate to functionality, though documentation is somewhat verbose and a few comments repeat the code. Action granularity: Statements generally perform one action per line, with readable multiline expressions and error construction. Reading flow: Methods follow a natural request-to-response sequence, and helpers isolate details effectively. Minor inconsistencies, including mixed string-formatting styles, redundant parentheses around match.func, and stray whitespace, slightly reduce polish.

Run 3

Code Structure: Well-organized middleware class with focused methods separating request checks, redirect decisions, path construction, and response handling. Nesting: Generally manageable, but user-agent validation and slash checks reach three nested levels and could benefit from guard clauses. Clarity of intent: Descriptive names, docstrings, and comments clearly explain behavior and important redirect constraints. Code length: Mostly proportionate to the functionality, though some comments repeat the code and several imports are unused. Action granularity: Statements generally perform one action per line; multiline expressions are formatted clearly. Reading flow: Methods follow a natural request-to-response progression, with helper methods placed logically. Minor distractions include an unnecessary blank line, redundant parentheses around match.func, and mixed string-formatting styles.