本文整理汇总了Python中django.http.HttpRequest.GET方法的典型用法代码示例。如果您正苦于以下问题:Python HttpRequest.GET方法的具体用法?Python HttpRequest.GET怎么用?Python HttpRequest.GET使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类django.http.HttpRequest
的用法示例。
在下文中一共展示了HttpRequest.GET方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: execute_subscription
# 需要导入模块: from django.http import HttpRequest [as 别名]
# 或者: from django.http.HttpRequest import GET [as 别名]
def execute_subscription(sched_id, force_run=False, today=None):
"""Handles creating the report PDF and sending the email.
(A future optimzation could re-use the PDF if multiple Subscriptions of
the same report are running at the same time.)
'today' defaults to current day, but you can set different dates for testing.
This accepts the ID instead of the object itself in order to handle concurrancy issues.
(It would seem to make sense to put this method with the Subscription model, however it leads to
some circular imports so it was cleaner to break it out into a utility function)."""
#Locks record until this function completes
sched_obj = Subscription.objects.select_for_update().get(pk=sched_id)
#check whether we should send
if not force_run:
if not sched_obj.should_send(today=today):
return False
sched_obj.last_scheduled_run = timezone.localtime(timezone.now())
if not getattr(settings, 'MR_REPORTS_WKHTMLTOPDF_PATH','') and getattr(settings, 'BASE_PATH',''):
sched_obj.last_run_succeeded = False
sched_obj.save()
raise ValueError("PDF generation not available. Please add and set 'MR_REPORTS_WKHTMLTOPDF_PATH', and 'BASE_PATH' in your settings.py file.")
#Generate PDF
mock_request = HttpRequest()
mock_request.method = 'GET'
if sched_obj.report_parameters:
mock_request.GET = QueryDict(sched_obj.report_parameters.lstrip('?'))
else:
#If the report has parameters and none are provided, provide dummy GET data
if Parameter.objects.filter(dataset__report=sched_obj.report):
mock_request.GET = QueryDict('use_defaults')
response = render_report(mock_request, report_id=sched_obj.report.pk, format='pdf')
#Send email
full_url = settings.BASE_PATH.rstrip('/') + sched_obj.report.get_absolute_url()
message = """\
Greetings,<br><br>
This is a snapshot of the report '%s'.<br><br>
Go here to view the realtime version of the report and/or change your subscription: <br>
<a href="%s">%s</a>
<br><br>
""" % (sched_obj.report.title, full_url, full_url)
message += sched_obj.email_body_extra
subject = 'Scheduled Report - ' + sched_obj.email_subject
text_content = re.sub(r'<[^>]+>','',message)
html_content = message
msg = EmailMultiAlternatives(subject, text_content, sched_obj.send_to.email, [sched_obj.send_to.email])
msg.attach_alternative(html_content, "text/html")
msg.attach(sched_obj.report.filename()+'.pdf', response.content, response['Content-Type'])
msg.send()
sched_obj.last_run_succeeded = True
sched_obj.save()
return True
示例2: test_top_level_jsonp
# 需要导入模块: from django.http import HttpRequest [as 别名]
# 或者: from django.http.HttpRequest import GET [as 别名]
def test_top_level_jsonp(self):
api = Api()
api.register(NoteResource())
api.register(UserResource())
request = HttpRequest()
request.META = {"HTTP_ACCEPT": "text/javascript"}
request.GET = {"callback": "foo"}
resp = api.top_level(request)
self.assertEqual(resp.status_code, 200)
self.assertEqual(resp["content-type"].split(";")[0], "text/javascript")
self.assertEqual(
resp.content.decode("utf-8"),
'foo({"notes": {"list_endpoint": "/api/v1/notes/", "schema": "/api/v1/notes/schema/"}, "users": {"list_endpoint": "/api/v1/users/", "schema": "/api/v1/users/schema/"}})',
)
request = HttpRequest()
request.META = {"HTTP_ACCEPT": "text/javascript"}
request.GET = {"callback": ""}
try:
resp = api.top_level(request)
self.fail("Broken callback didn't fail!")
except BadRequest:
# Regression: We expect this, which is fine, but this used to
# be an import error.
pass
示例3: test_auth_required_error
# 需要导入模块: from django.http import HttpRequest [as 别名]
# 或者: from django.http.HttpRequest import GET [as 别名]
def test_auth_required_error(self):
user = User(first_name='vivek', last_name='chand',
username='[email protected]')
user.save()
request = HttpRequest()
request.META = {
'SERVER_NAME': 'testserver',
'SERVER_PORT': 80,
'REMOTE_ADDR': '6457.255.345.123',
}
request.GET = {
'state': xsrfutil.generate_token(settings.SECRET_KEY, user),
}
request.GET = {
'error': 'access_denied',
}
request.user = user
response = auth_required(request)
self.assertEqual(
response.content, 'Access Denied:No code was supplied in the query parameters.')
self.assertEqual(response.status_code, 400)
user.delete()
示例4: test_workflow_04
# 需要导入模块: from django.http import HttpRequest [as 别名]
# 或者: from django.http.HttpRequest import GET [as 别名]
def test_workflow_04(self):
msgt('(4) Try with HttpRequest - GET')
msg('(a) Try form with HttpRequest object')
h = HttpRequest()
h.GET = self.expected_params
f1 = CheckForExistingLayerForm(h.GET)
self.assertEqual(f1.is_valid(), True)
msg('(b) Try signature validity check - break assertion by sending dict, not HttpRequest')
self.assertRaises(AssertionError, f1.is_signature_valid_check_get, h.GET)
msg('(c) Try signature check with invalid data--no signature key')
h_bad_data = HttpRequest()
h_bad_data.GET = self.test_data
self.assertEqual(f1.is_signature_valid_check_get(h_bad_data), False)
msg('(d) Try signature check with invalid data--bad signature key')
h_bad_data2 = HttpRequest()
h_bad_data2.GET = self.expected_params_bad_signature
self.assertEqual(f1.is_signature_valid_check_get(h_bad_data2), False)
msg('(e) Try signature check with valid data')
self.assertEqual(f1.is_signature_valid_check_get(h), True)
msg('(f) cleaned data.')
self.assertEqual(f1.cleaned_data, self.expected_clean_data)
示例5: test_general
# 需要导入模块: from django.http import HttpRequest [as 别名]
# 或者: from django.http.HttpRequest import GET [as 别名]
def test_general(self):
"""
Tests the basics: missing referrer, query string etc.
"""
handler = SearchTermHandler(search_terms='alice')
handler.prepare()
req = HttpRequest()
self.assertFalse(handler.check(req))
for ref, result in [
('http://www.google.co.uk/search?not_the_right_param=alice', False),
('gibberish', False),
('', False),
('http://www.example.com/no_query_string/', False),
]:
req.GET = {'r': urllib.quote_plus(ref)}
self.assertTrue(result == handler.check(req), msg='%s should have tested %s' % (ref, result))
#check wildcards aren't possible
handler = SearchTermHandler(search_terms='b*ob frank')
handler.prepare()
for t, result in [ ('baaaaob', False),
('bbbbbbob', False),
]:
req.GET = {'r': urllib.quote_plus('http://www.google.co.uk/search?q=' + t)}
self.assertTrue(result == handler.check(req), msg='%s should have tested %s' % (t, result))
示例6: setUp
# 需要导入模块: from django.http import HttpRequest [as 别名]
# 或者: from django.http.HttpRequest import GET [as 别名]
def setUp(self):
request1 = HttpRequest()
request1.GET = QueryDict('')
self.context1 = RequestContext(request1)
request2 = HttpRequest()
request2.GET = QueryDict('foo=bar')
self.context2 = RequestContext(request2)
示例7: test_thread_safety
# 需要导入模块: from django.http import HttpRequest [as 别名]
# 或者: from django.http.HttpRequest import GET [as 别名]
def test_thread_safety(self):
exceptions = []
def threaded_view(resp_queue, view, request):
import time; time.sleep(2)
try:
inst = view(request)
resp_queue.put(request.GET['name'])
except Exception as e:
exceptions.append(e)
raise
class ThreadedSearchView(SearchView):
def __call__(self, request):
print("Name: %s" % request.GET['name'])
return super(ThreadedSearchView, self).__call__(request)
view = search_view_factory(view_class=ThreadedSearchView)
resp_queue = queue.Queue()
request_1 = HttpRequest()
request_1.GET = {'name': 'foo'}
request_2 = HttpRequest()
request_2.GET = {'name': 'bar'}
th1 = Thread(target=threaded_view, args=(resp_queue, view, request_1))
th2 = Thread(target=threaded_view, args=(resp_queue, view, request_2))
th1.start()
th2.start()
th1.join()
th2.join()
foo = resp_queue.get()
bar = resp_queue.get()
self.assertNotEqual(foo, bar)
示例8: test_items_per_page_tag
# 需要导入模块: from django.http import HttpRequest [as 别名]
# 或者: from django.http.HttpRequest import GET [as 别名]
def test_items_per_page_tag(self):
with self.settings(PAGINATOR_LIMITS=[10, 25, 50]):
request = HttpRequest()
default_limit = settings.PAGINATOR_LIMITS[0]
default_limit_link = ('<a href="?limit={limit}&offset=0"><span class="hidden">'
'view </span>{limit}'.format(limit=default_limit))
request.GET = QueryDict('', mutable=False)
template = Template(
"{% load pagination_tags %}{% items_per_page request %}")
result = template.render(RequestContext(request, {}))
self.assertIn('<a href="?limit=50&offset=0"><span class="hidden">view </span>50', result)
self.assertNotIn(default_limit_link, result)
request.GET = QueryDict('limit=50', mutable=False)
result = template.render(RequestContext(request, {}))
self.assertNotIn(
'<a href="?limit=50" title="View 50 items per page">50</a>',
result)
self.assertIn(default_limit_link, result)
# test offset
# offset=10, limit=10 -> offset=0, limit=25
# offset=20, limit=10 -> offset=0, limit=25
# offset=30, limit=10 -> offset=25, limit=25
template = Template(
"{% load pagination_tags %}{% items_per_page request %}")
request.GET = QueryDict('limit=10&offset=10', mutable=False)
result = template.render(RequestContext(request, {}))
self.assertNotIn('offset=10', result)
self.assertIn('offset=0', result)
request.GET = QueryDict('limit=10&offset=30', mutable=False)
result = template.render(RequestContext(request, {}))
self.assertNotIn('offset=10', result)
self.assertIn('offset=25', result)
示例9: test_determine_format
# 需要导入模块: from django.http import HttpRequest [as 别名]
# 或者: from django.http.HttpRequest import GET [as 别名]
def test_determine_format(self):
serializer = Serializer()
request = HttpRequest()
# Default.
self.assertEqual(determine_format(request, serializer), 'application/json')
# Test forcing the ``format`` parameter.
request.GET = {'format': 'json'}
self.assertEqual(determine_format(request, serializer), 'application/json')
request.GET = {'format': 'jsonp'}
self.assertEqual(determine_format(request, serializer), 'text/javascript')
request.GET = {'format': 'xml'}
self.assertEqual(determine_format(request, serializer), 'application/xml')
request.GET = {'format': 'yaml'}
self.assertEqual(determine_format(request, serializer), 'text/yaml')
request.GET = {'format': 'foo'}
self.assertEqual(determine_format(request, serializer), 'application/json')
# Test the ``Accept`` header.
request.META = {'HTTP_ACCEPT': 'application/json'}
self.assertEqual(determine_format(request, serializer), 'application/json')
request.META = {'HTTP_ACCEPT': 'text/javascript'}
self.assertEqual(determine_format(request, serializer), 'text/javascript')
request.META = {'HTTP_ACCEPT': 'application/xml'}
self.assertEqual(determine_format(request, serializer), 'application/xml')
request.META = {'HTTP_ACCEPT': 'text/yaml'}
self.assertEqual(determine_format(request, serializer), 'text/yaml')
request.META = {'HTTP_ACCEPT': 'text/html'}
self.assertEqual(determine_format(request, serializer), 'text/html')
request.META = {'HTTP_ACCEPT': '*/*'}
self.assertEqual(determine_format(request, serializer), 'application/json')
request.META = {'HTTP_ACCEPT': 'application/json,application/xml;q=0.9,*/*;q=0.8'}
self.assertEqual(determine_format(request, serializer), 'application/json')
request.META = {'HTTP_ACCEPT': 'text/plain,application/xml,application/json;q=0.9,*/*;q=0.8'}
self.assertEqual(determine_format(request, serializer), 'application/xml')
request.META = {'HTTP_ACCEPT': 'application/json; charset=UTF-8'}
self.assertEqual(determine_format(request, serializer), 'application/json')
request.META = {'HTTP_ACCEPT': 'text/javascript,application/json'}
self.assertEqual(determine_format(request, serializer), 'application/json')
示例10: test_determine_format
# 需要导入模块: from django.http import HttpRequest [as 别名]
# 或者: from django.http.HttpRequest import GET [as 别名]
def test_determine_format(self):
request = HttpRequest()
resource = UnimplementedDetailResource()
# Default.
self.assertEqual(
resource.determine_format(request), 'application/json')
# Test forcing the ``format`` parameter.
request.GET = {'format': 'json'}
self.assertEqual(
resource.determine_format(request), 'application/json')
request.GET = {'format': 'jsonp'}
self.assertEqual(resource.determine_format(request), 'text/javascript')
request.GET = {'format': 'xml'}
self.assertEqual(resource.determine_format(request), 'application/xml')
request.GET = {'format': 'yaml'}
self.assertEqual(resource.determine_format(request), 'text/yaml')
request.GET = {'format': 'foo'}
self.assertEqual(
resource.determine_format(request), 'application/json')
# Test the ``Accept`` header.
request.META = {'HTTP_ACCEPT': 'application/json'}
self.assertEqual(
resource.determine_format(request), 'application/json')
request.META = {'HTTP_ACCEPT': 'text/javascript'}
self.assertEqual(resource.determine_format(request), 'text/javascript')
request.META = {'HTTP_ACCEPT': 'application/xml'}
self.assertEqual(resource.determine_format(request), 'application/xml')
request.META = {'HTTP_ACCEPT': 'text/yaml'}
self.assertEqual(resource.determine_format(request), 'text/yaml')
request.META = {'HTTP_ACCEPT': 'text/html'}
self.assertEqual(resource.determine_format(request), 'text/html')
request.META = {
'HTTP_ACCEPT': 'application/json,application/xml;q=0.9,*/*;q=0.8'}
self.assertEqual(
resource.determine_format(request), 'application/json')
request.META = {
'HTTP_ACCEPT': \
'text/plain,application/xml,application/json;q=0.9,*/*;q=0.8'}
self.assertEqual(resource.determine_format(request), 'application/xml')
示例11: test_top_level_include_schema_content
# 需要导入模块: from django.http import HttpRequest [as 别名]
# 或者: from django.http.HttpRequest import GET [as 别名]
def test_top_level_include_schema_content(self):
api = Api()
note_resource = NoteResource()
user_resource = UserResource()
api.register(note_resource)
api.register(user_resource)
request = HttpRequest()
request.GET = {'fullschema': 'true'}
resp = api.top_level(request)
self.assertEqual(resp.status_code, 200)
content = json.loads(resp.content.decode('utf-8'))
content['notes']['schema'] = adjust_schema(content['notes']['schema'])
content['users']['schema'] = adjust_schema(content['users']['schema'])
dummy_request = HttpRequest()
dummy_request.method = 'GET'
notes_schema = adjust_schema(json.loads(note_resource.get_schema(dummy_request).content.decode('utf-8')))
user_schema = adjust_schema(json.loads(user_resource.get_schema(dummy_request).content.decode('utf-8')))
self.assertEqual(content['notes']['list_endpoint'], '/api/v1/notes/')
self.assertEqual(content['notes']['schema'], notes_schema)
self.assertEqual(content['users']['list_endpoint'], '/api/v1/users/')
self.assertEqual(content['users']['schema'], user_schema)
示例12: send_bookkeeper_email
# 需要导入模块: from django.http import HttpRequest [as 别名]
# 或者: from django.http.HttpRequest import GET [as 别名]
def send_bookkeeper_email(month=None, year=None, emails=None):
today = datetime.date.today()
# now, make sure that we send out LAST month's invoices if we did
# not specify a month or year.
today = utils.get_previous_month_date_range(today)[0]
month = month or today.month
year = year or today.year
from corehq.apps.accounting.interface import InvoiceInterface
request = HttpRequest()
params = urlencode((
('report_filter_statement_period_use_filter', 'on'),
('report_filter_statement_period_month', month),
('report_filter_statement_period_year', year),
))
request.GET = QueryDict(params)
request.couch_user = FakeUser(
domain="hqadmin",
username="[email protected]",
)
invoice = InvoiceInterface(request)
invoice.is_rendered_as_email = True
first_of_month = datetime.date(year, month, 1)
email_context = {
'month': first_of_month.strftime("%B"),
}
email_content = render_to_string(
'accounting/bookkeeper_email.html', email_context)
email_content_plaintext = render_to_string(
'accounting/bookkeeper_email_plaintext.html', email_context)
format_dict = Format.FORMAT_DICT[Format.CSV]
excel_attachment = {
'title': 'Invoices_%(period)s.%(extension)s' % {
'period': first_of_month.strftime('%B_%Y'),
'extension': format_dict['extension'],
},
'mimetype': format_dict['mimetype'],
'file_obj': invoice.excel_response,
}
emails = emails or settings.BOOKKEEPER_CONTACT_EMAILS
for email in emails:
send_HTML_email(
"Invoices for %s" % datetime.date(year, month, 1).strftime("%B %Y"),
email,
email_content,
email_from=settings.DEFAULT_FROM_EMAIL,
text_content=email_content_plaintext,
file_attachments=[excel_attachment],
)
logger.info(
"[BILLING] Sent Bookkeeper Invoice Summary for %(month)s "
"to %(emails)s." % {
'month': first_of_month.strftime("%B %Y"),
'emails': ", ".join(emails)
})
示例13: direct_get_response
# 需要导入模块: from django.http import HttpRequest [as 别名]
# 或者: from django.http.HttpRequest import GET [as 别名]
def direct_get_response (url, request=None):
"""
Hack to load a view contents without going through the (local) server, work
around for local (testing) server blockage when called form another request
request is optional, but NB the default one is really minimal and may be
missing many things a view may require (like a REQUEST object)... so better
to pass a real request object
Returns response object (resp.content is content in bytes)
"""
if request == None:
request = HttpRequest()
request.user = django.contrib.auth.models.AnonymousUser()
request.REQUEST = {}
request.POST = {}
request.GET = {}
# de-absolutize the URL
rurl = urlparse.urlparse(url).path
(func, args, kwargs) = resolve(rurl)
try:
return func(request, *args, **kwargs)
except Exception, e:
print("aacore.utils.direct_get_response: Exception:", e)
示例14: test_httprequest_repr
# 需要导入模块: from django.http import HttpRequest [as 别名]
# 或者: from django.http.HttpRequest import GET [as 别名]
def test_httprequest_repr(self):
request = HttpRequest()
request.path = "/somepath/"
request.GET = {"get-key": "get-value"}
request.POST = {"post-key": "post-value"}
request.COOKIES = {"post-key": "post-value"}
request.META = {"post-key": "post-value"}
self.assertEqual(
repr(request),
str_prefix(
"<HttpRequest\npath:/somepath/,\nGET:{%(_)s'get-key': %(_)s'get-value'},\nPOST:{%(_)s'post-key': %(_)s'post-value'},\nCOOKIES:{%(_)s'post-key': %(_)s'post-value'},\nMETA:{%(_)s'post-key': %(_)s'post-value'}>"
),
)
self.assertEqual(build_request_repr(request), repr(request))
self.assertEqual(
build_request_repr(
request,
path_override="/otherpath/",
GET_override={"a": "b"},
POST_override={"c": "d"},
COOKIES_override={"e": "f"},
META_override={"g": "h"},
),
str_prefix(
"<HttpRequest\npath:/otherpath/,\nGET:{%(_)s'a': %(_)s'b'},\nPOST:{%(_)s'c': %(_)s'd'},\nCOOKIES:{%(_)s'e': %(_)s'f'},\nMETA:{%(_)s'g': %(_)s'h'}>"
),
)
示例15: decode_request
# 需要导入模块: from django.http import HttpRequest [as 别名]
# 或者: from django.http.HttpRequest import GET [as 别名]
def decode_request(value):
"""
Decodes a request JSONish value to a HttpRequest object.
"""
request = HttpRequest()
request.GET = CustomQueryDict(value['get'])
request.POST = CustomQueryDict(value['post'])
request.COOKIES = value['cookies']
request.path = value['path']
request.method = value['method']
request.reply_channel = value['reply_channel']
# Channels requests are more high-level than the dumping ground that is
# META; re-combine back into it
request.META = {
"REQUEST_METHOD": value["method"],
"SERVER_NAME": value["server"][0],
"SERVER_PORT": value["server"][1],
"REMOTE_ADDR": value["client"][0],
"REMOTE_HOST": value["client"][0], # Not the DNS name, hopefully fine.
}
for header, header_value in value.get("headers", {}).items():
request.META["HTTP_%s" % header.upper()] = header_value
# We don't support non-/ script roots
request.path_info = value['path']
return request