Reputation: 497
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?
Upvotes: 4
Views: 2516
Reputation: 2428
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.
Upvotes: 0
Reputation: 2405
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
Upvotes: 3
Reputation: 2771
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.
Upvotes: 5