Sample

pyint-ce0844947702-I08

Select one of ten high-readability unrelated code templates per class

Matched original source

Lines118

Scores

MethodScoreScale
Posnett00–1; higher is more readable
Dorn0.4790–1; higher is more readable
Mi0.4080–1; higher is more readable
LLOC52Logical lines; fewer is more readable
DeepSeek V4 Pro160–20; mean of three runs
GPT-6.1 Sol160–20; mean of three runs
BTTF0.4690–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 """ remaining_steps = 3 while remaining_steps > 0: remaining_steps -= 1 # 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: view = match.func return getattr(view, "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.2786.314−91.948
Source linesThe number of non-empty source lines.118+47.2
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.502−6.753

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

Feature contributions

FeatureValueContribution
(log-odds)
Comment layout frequencyHow frequently the layout switches between lines containing only comments or whitespace and lines containing code.119−3.177
Indentation frequencyHow rapidly indentation changes from line to line.77+1.926
Number layout frequencyHow rapidly the number of numeric values per line changes through the code.77−1.346
Identifier layout (vertical)How rapidly the visual pattern of identifier characters changes from top to bottom.117.886+1.238
Operator visual areaThe share of the code’s visual area occupied by operators such as +, =, and *.0.032+0.635
Comment layout (horizontal)How rapidly the visual pattern of comment characters changes from left to right.86.252+0.587
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.933−0.017

Intercept 0.07 + feature contributions = -0.083 (log-odds).
Score = sigmoid(-0.083) = 0.479.

Score0.408
Score52
Run 1

The code is generally well-structured with clear sections for different middleware operations, good docstrings, and reasonable nesting. However, there are some issues: the 'remaining_steps' loop in process_request appears to be incomplete/dead code, which creates ambiguity. The should_redirect_with_slash method has deeper nesting (if/if/if/match) that could be simplified. Function names and docstrings clearly convey intent, and the code is mostly concise with good action granularity though process_request could be broken into smaller methods. Reading flow is natural with logical progression from request processing to response handling.

Run 2

The code is well-structured and highly readable. It uses clear docstrings, logical method separation, and consistent formatting. However, there is a confusing unused 'while' loop in process_request that adds unnecessary noise and reduces clarity. Nesting is mostly flat with only minor conditional levels. Intent is clearly communicated through descriptive method names and comments. Action granularity is appropriate, with one main action per line. The reading flow is natural, following a logical progression of checks and redirects. Minor improvements could include removing the dead loop and simplifying the PREPEND_WWW conditional block.

Run 3

The code is generally readable with clear docstrings explaining intent, logical separation of methods, and mostly flat nesting. It follows Django conventions and uses descriptive method names. However, there are issues: a useless while loop in process_request (lines 15-17) that does nothing, which harms clarity; some methods like should_redirect_with_slash have moderate nesting; and the regex import is unused. The overall structure is decent but could be improved by removing dead code and unnecessary imports. The action granularity is mostly one action per line, but the while loop and conditional logic in process_request feel congested. Reading flow is natural, though the dead loop interrupts it. Score reflects good readability with minor but noticeable flaws.

Run 1

Code Structure: Responsibilities are logically separated into request handling, slash validation, path construction, and response handling. Nesting: Mostly manageable, but user-agent checking and slash validation reach three nested levels and could use guard clauses. Clarity of intent: Descriptive method names, docstrings, and comments explain the middleware well; the pointless remaining_steps loop introduces ambiguity, and unused imports add noise. Code length: Generally appropriate, though some documentation repeats the implementation and the no-op loop is unnecessary. Action granularity: Statements generally perform one action each, with readable multiline expressions and error formatting. Reading flow: Methods follow a natural request-to-response progression, with helper methods placed coherently; the unexplained loop interrupts that flow.

Run 2

Code Structure: Well-organized middleware with focused methods separating request checks, slash handling, and response processing; unused imports add clutter. Nesting: Generally manageable, but user-agent checks and slash validation reach three nested levels and could be flatter. Clarity of intent: Descriptive names, docstrings, and comments explain the behavior well; the pointless remaining_steps loop introduces ambiguity. Code length: Mostly appropriate, though the no-op loop and some repetitive documentation add unnecessary length. Action granularity: Statements generally perform one action per line, and multiline expressions remain readable. Reading flow: Methods follow a natural request-to-response progression, with helper methods supporting the main logic; the unrelated loop interrupts that flow.

Run 3

Code Structure: Responsibilities are logically separated into request processing, redirect checks, path construction, and response processing. Nesting: Generally manageable, though user-agent checks and slash validation reach three nested levels and could use flatter control flow. Clarity of intent: Descriptive method names, docstrings, and comments explain behavior well; the purposeless remaining_steps loop introduces ambiguity, and unused imports add noise. Code length: Mostly appropriate, but the redundant loop and some repetitive documentation unnecessarily extend it. Action granularity: Statements generally perform one action per line, with readable formatting for longer expressions and error messages. Reading flow: Methods follow a natural request-to-response progression, and helper methods keep complex details localized; the unexplained loop interrupts that flow.