5

So I have added a command to manage.py in my django app that basically takes the results from a view and emails them out to specific users. This command will run on a cron schedule - basically this is done as an automated, emailed report.

I've figured out how to add in the command but I want to call the view now. The problem is that I have no HttpRequest object and whenever I read the django docs on HttpRequest, my eyes glaze over and I struggle to follow it. I'm not sure exactly how to create an HttpRequest object that will satisfy my needs nor if there's another way to get this done. I also tried passing 'None' in as the request object but that didn't lead anywhere.

Help?

1
  • 3
    It would be non-trivial to build HttpRequest. Rather separate out your code into another function that does not depend upon request and call it from command as well as view. Commented Dec 23, 2013 at 9:59

3 Answers 3

5

I think your situation is as follows:

def superDuperView(request, params,...): 
   # The logic lies here which is intended to be reused.
   ......
   ......
   return HttpResponse('template.html', {somedata}) 

You would like to reuse your view's logic in a management command. But calling a view is without request response lifecycle seems not to be possible. Thus segregation of logic and your view would help you:

def superDuberBusinessLogic(user, params,...): 
   #implement your logic here without a need of any request.
   ......
   return result

The you view would become:

def superDuperView(request, params,...): 
   # You could pass user your logic if you need.
   data = superDuberBusinessLogic(request.user, params,....)
   return HttpResponse('template.html', {data}) 

You could use your superDuberBusinessLogic in your management command.

Sign up to request clarification or add additional context in comments.

Comments

3

I'll fully admit to the hacky nature of this but if it works is it stupid?

from django.test import Client

user = User.objects.filter(is_superuser=True)[0]
assert user.is_authenticated()

c = Client()
c.force_login(user)

resp = c.get( reverse('frontend:csv-view', kwargs={'company':company.name}) )
print resp.content

Comments

0

If anyone is in the situation where they need a request object, a simple solution might be to use the curl command from a cron job

This is useful for eg. to build an absolute url in an email template

eg.

30 08 10 06 * curl http://localhost/your/view/param/etc/etc/

This bypasses the need for any management command codes.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.