title: Context manager to keep Django views clean?
body: <p>I have already asked similar question, but that was too broad and not Django-specific. Is a good practice to keep Django views clean with context managers to make a code DRY? This is example of code (a bit pseudocode):</p>
  
  <pre><code>class DjangoViewset():
      @action(method=['GET'])
      def custom_action1(request):
          a = get_data_from_somewhere1()
          b = get_data_from_somewhere2()
          if a&lt;b:
              raise 400
          if a==1:
              raise 404
          if a==2:
              raise 403 
          result = some_complicated_logic(a, b)
          return Response(result)
  
      @action(method=['GET'])
      def custom_action2(request):
          a = get_data_from_somewhere1()
          b = get_data_from_somewhere2()
          if a&lt;b:
              raise 400
          if a==1:
              raise 404
          if a==2:
              raise 403
          result = some_complicated_logic_another(a, b)
          return Response(result)
  
  </code></pre>
  
  <p>Can I refactor it with something like this or this is bad using of context manager?</p>
  
  <pre><code>@contextmanager
  def validate_data(a, b):
      if a&lt;b:
          raise 400
      if a==1:
         raise 404
      if a==2:
         raise 403
     yield
  
  class DjangoViewset():
      @action(method=['GET'])
      def custom_action1(request):
          a = get_data_from_somewhere1()
          b = get_data_from_somewhere2()
          with validate_data(a, b):
              result = some_complicated_logic(a, b)
          return Response(result)
  
      @action(method=['GET'])
      def custom_action2(request):
          a = get_data_from_somewhere1()
          b = get_data_from_somewhere2()
          with validate_data(a, b):
              result = some_complicated_logic_another(a, b)
          return Response(result)
  
  </code></pre>
  
  <p>With this refactor code looks much simpler, but I can't find information if I can use context manager this way, but is it not forbidden style?</p>