Dark Launch

This is a Dark Launch

Django call class based view in script

Call a Django view with query parameters using querydict in a python script.

A simple view we want to call from a script:

Python
from django.http import HttpResponse
from django.utils import timezone
from django.views import View
 
 
class MyView(View):
    def get(self, request):
        now = timezone.now()
        html = "<html><body>It is now %s.</body></html>" % now
        return HttpResponse(html)

The script where we call the class-based view:

Python
from django.contrib.auth.models import User
from django.http import HttpRequest
from django.http.request import QueryDict
 
from myapp.views import MyView
 
 
user = User.objects.get(username='admin')
 
get = QueryDict('defer=0&id=1234&force')
 
request = HttpRequest()
request.method = 'GET'
request.user = user
request.GET = get
 
result = MyView.as_view()(request)
print('result:')
print(result)

The output when the script is run:

Code
result:
Content-Type: text/html; charset=utf-8
 
<html><body>It is now 2018-05-15 00:00:00.000000+00:00.</body></html>