def build_dummy_request(newsitem):
"""
Construct a HttpRequest object that is, as far as possible,
representative of ones that would receive this page as a response. Used
for previewing / moderation and any other place where we want to
display a view of this page in the admin interface without going
through the regular page routing logic.
"""
url = newsitem.full_url
if url:
url_info = urlparse(url)
hostname = url_info.hostname
path = url_info.path
port = url_info.port or 80
else:
# Cannot determine a URL to this page - cobble one together based on
# whatever we find in ALLOWED_HOSTS
try:
hostname = settings.ALLOWED_HOSTS[0]
except IndexError:
hostname = 'localhost'
path = '/'
port = 80
request = WSGIRequest({
'REQUEST_METHOD': 'GET',
'PATH_INFO': path,
'SERVER_NAME': hostname,
'SERVER_PORT': port,
'HTTP_HOST': hostname,
'wsgi.input': StringIO(),
})
# Apply middleware to the request - see http://www.mellowmorning.com/2011/04/18/mock-django-request-for-testing/
handler = BaseHandler()
handler.load_middleware()
# call each middleware in turn and throw away any responses that they might return
for middleware_method in handler._request_middleware:
middleware_method(request)
return request
评论列表
文章目录