Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>You certainly don't have to type it twice, you can just create a <code>validate</code> function which takes a value and validates it:</p> <pre><code>def validate(argument): return re.match('^SOME_REGEX$', argument) </code></pre> <p>and then write a decorator which calls the <code>validate</code> function as needed:</p> <pre><code>def requires_valid(f): def _inner(request, argument=None): if argument is None: return HttpResponse(content="No argument given", status=400) elif not validate(argument): return HttpResponse(content="Invalid argument", status=400) else: return f(request, argument) return _inner </code></pre> <p>Obviously, I don't know your use case so you might want to move the check for <code>None</code> into <code>validate</code> but the point is, you don't have to repeat the same regex twice.</p> <p>And if you feel like delving into deeper magic and insist on using the same function both as a decorator and a verifier, you might try something like this:</p> <pre><code>def validate(f): if callable(f): def _inner(request, argument=None): if argument is None: return HttpResponse(content="No argument given", status=400) elif not validate(argument): return HttpResponse(content="Invalid argument", status=400) else: return f(request, argument) return _inner else: return re.match('^SOME_REGEX$', f) </code></pre> <p>But I'd advise against this, since you have one function that does two very different things, depending on the type of the parameter. This results in code that is much more difficult to understand. (“You decorate a view with this function which takes a string and returns bool?!”)</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload