def get_draft_url(url):
"""
Return the given URL with a draft mode HMAC in its querystring.
"""
if verify_draft_url(url):
# Nothing to do. Already a valid draft URL.
return url
# Parse querystring and add draft mode HMAC.
url = urlparse.urlparse(url)
salt = get_random_string(5)
# QueryDict requires a bytestring as its first argument
query = QueryDict(force_bytes(url.query), mutable=True)
query['edit'] = '%s:%s' % (salt, get_draft_hmac(salt, url.path))
# Reconstruct URL.
parts = list(url)
parts[4] = query.urlencode(safe=':')
return urlparse.urlunparse(parts)
python类QueryDict()的实例源码
def redirect_to_login(next, login_url=None,
redirect_field_name=REDIRECT_FIELD_NAME):
"""
Redirects the user to the login page, passing the given 'next' page
"""
resolved_url = resolve_url(login_url or settings.LOGIN_URL)
login_url_parts = list(urlparse(resolved_url))
if redirect_field_name:
querystring = QueryDict(login_url_parts[4], mutable=True)
querystring[redirect_field_name] = next
login_url_parts[4] = querystring.urlencode(safe='/')
return HttpResponseRedirect(urlunparse(login_url_parts))
# 4 views for password reset:
# - password_reset sends the mail
# - password_reset_done shows a success message for the above
# - password_reset_confirm checks the link the user clicked and
# prompts for a new password
# - password_reset_complete shows a success message for the above
def redirect_to_login(next, login_url=None,
redirect_field_name=REDIRECT_FIELD_NAME):
"""
Redirects the user to the login page, passing the given 'next' page
"""
resolved_url = resolve_url(login_url or settings.LOGIN_URL)
login_url_parts = list(urlparse(resolved_url))
if redirect_field_name:
querystring = QueryDict(login_url_parts[4], mutable=True)
querystring[redirect_field_name] = next
login_url_parts[4] = querystring.urlencode(safe='/')
return HttpResponseRedirect(urlunparse(login_url_parts))
# 4 views for password reset:
# - password_reset sends the mail
# - password_reset_done shows a success message for the above
# - password_reset_confirm checks the link the user clicked and
# prompts for a new password
# - password_reset_complete shows a success message for the above
def test_missing_credentials(self):
"""
Test for missing credentials.
"""
#self.skipTest("Temporarily skipped")
# Get user's credentials.
username, password, email = self._prompt(need_email=True)
# Setup request
request = self.factory.get('django-pam:login')
request.user = AnonymousUser()
kwargs = {}
data = kwargs.setdefault('data', QueryDict(mutable=True))
data.appendlist('username', username)
data.appendlist('password', '')
data.appendlist('email', email)
form = AuthenticationForm(**kwargs)
msg = "kwargs: {}, errors: {}".format(kwargs, form.errors.as_data())
self.assertFalse(form.is_valid(), msg)
# Check that we have a password and __all__ error messages.
self.assertTrue('password' in form.errors.as_data(), msg)
self.assertTrue('__all__' in form.errors.as_data(), msg)
def redirect_to_login(next, login_url=None,
redirect_field_name=REDIRECT_FIELD_NAME):
"""
Redirects the user to the login page, passing the given 'next' page
"""
resolved_url = resolve_url(login_url or settings.LOGIN_URL)
login_url_parts = list(urlparse(resolved_url))
if redirect_field_name:
querystring = QueryDict(login_url_parts[4], mutable=True)
querystring[redirect_field_name] = next
login_url_parts[4] = querystring.urlencode(safe='/')
return HttpResponseRedirect(urlunparse(login_url_parts))
# 4 views for password reset:
# - password_reset sends the mail
# - password_reset_done shows a success message for the above
# - password_reset_confirm checks the link the user clicked and
# prompts for a new password
# - password_reset_complete shows a success message for the above
def redirect_to_login(next, login_url=None,
redirect_field_name=REDIRECT_FIELD_NAME):
"""
Redirects the user to the login page, passing the given 'next' page
"""
resolved_url = resolve_url(login_url or settings.LOGIN_URL)
login_url_parts = list(urlparse(resolved_url))
if redirect_field_name:
querystring = QueryDict(login_url_parts[4], mutable=True)
querystring[redirect_field_name] = next
login_url_parts[4] = querystring.urlencode(safe='/')
return HttpResponseRedirect(urlunparse(login_url_parts))
# 4 views for password reset:
# - password_reset sends the mail
# - password_reset_done shows a success message for the above
# - password_reset_confirm checks the link the user clicked and
# prompts for a new password
# - password_reset_complete shows a success message for the above
def _run_import_view(self, postfile):
with factory.load_test_file(postfile) as poststring:
POST = QueryDict(poststring.read())
# mocking redis and celery task, to only test the view itself
with patch('main.views.redis.ScratchStorage') as MockStorage:
with patch('main.views.import_table_task.delay') as mock_task:
storage = MockStorage.return_value
storage.save.return_value = 'randomkey'
result = MagicMock()
result.id = '00000000-0000-0000-0000-000000000001'
mock_task.return_value = result
# fake the request
response = self.client.post(self._import_url(), data=POST)
# assert calls to redis and celery
storage.save.assert_called()
mock_task.assert_called_with(self.target_study.pk, self.user.pk, 'randomkey')
self.assertEqual(self._assay_count(), 0) # view does not change assays
return response
def create_time_select_form(self, payload, **kwargs):
""" Constructs a form to select the timepoint of data to export to SBML and the output
filename. Depends on measurement forms already existing.
:param payload: the QueryDict from POST attribute of a request
:param kwargs: any additional kwargs to pass to ALL forms; see Django Forms
documentation.
:return: a SbmlExportSelectionForm """
# error if no range or if max < min
if self._min is None or self._max is None or self._max < self._min:
return None
points = self._points
t_range = Range(min=self._min, max=self._max)
if points is not None:
points = sorted(points)
time_form = SbmlExportSelectionForm(
t_range=t_range, points=points, line=self._selection.lines[0], data=payload, **kwargs
)
time_form.sbml_warnings.extend(self._export_errors)
return time_form
def update_bound_data_with_defaults(self):
""" Forces data bound to the form to update to default values. """
super(SbmlExportOdForm, self).update_bound_data_with_defaults()
if self.is_bound:
# create mutable copy of QueryDict
replace_data = QueryDict(mutable=True)
replace_data.update(self.data)
# set initial gcdw_conversion values
cfield = self.fields['gcdw_conversion']
if cfield.initial:
name = self.add_prefix('gcdw_conversion')
for i, part in enumerate(cfield.widget.decompress(cfield.initial)):
replace_data['%s_%s' % (name, i)] = part
# set initial gcdw_default value
dfield = self.fields['gcdw_default']
replace_data[self.add_prefix('gcdw_default')] = '%s' % dfield.initial
self.data = replace_data
def clean(self):
data = super(WorklistDefaultsForm, self).clean()
# this is SUPER GROSS, but apparently the only way to change the form output from here is
# to muck with the source data, by poking the undocumented _mutable property of QueryDict
self.data._mutable = True
# if no incoming data for field, fall back to default (initial) instead of empty string
for name, field in self._created_fields.items():
key = self.add_prefix(name)
value = field.widget.value_from_datadict(self.data, self.files, key)
if not value:
value = field.initial
self.data[key] = data[key] = value
self._lookup[name].default_value = value
# flip back _mutable property
self.data._mutable = False
return data
def _init_options(self):
# sometimes self.data is a plain dict instead of a QueryDict
data = QueryDict(mutable=True)
data.update(self.data)
# update available choices based on instances in self._selection
if self._selection and hasattr(self._selection, 'lines'):
columns = self._selection.line_columns
self.fields['line_meta'].choices = map(table.ColumnChoice.get_field_choice, columns)
self.fields['line_meta'].coerce = table.ColumnChoice.coerce(columns)
# set all _meta options if no list of options was passed in
for meta in ['study_meta', 'line_meta', 'protocol_meta', 'assay_meta', 'measure_meta']:
if self.initial.get(meta, None) == '__all__':
self.initial.update({
meta: [choice[0] for choice in self.fields[meta].choices],
})
# update incoming data with default initial if not already set
if meta not in data and 'layout' not in data:
data.setlist(meta, self.initial.get(meta, []))
self.data = data
def redirect_to_login(next, login_url=None,
redirect_field_name=REDIRECT_FIELD_NAME):
"""
Redirects the user to the login page, passing the given 'next' page
"""
resolved_url = resolve_url(login_url or settings.LOGIN_URL)
login_url_parts = list(urlparse(resolved_url))
if redirect_field_name:
querystring = QueryDict(login_url_parts[4], mutable=True)
querystring[redirect_field_name] = next
login_url_parts[4] = querystring.urlencode(safe='/')
return HttpResponseRedirect(urlunparse(login_url_parts))
# 4 views for password reset:
# - password_reset sends the mail
# - password_reset_done shows a success message for the above
# - password_reset_confirm checks the link the user clicked and
# prompts for a new password
# - password_reset_complete shows a success message for the above
def redirect_to_login(next, login_url=None,
redirect_field_name=REDIRECT_FIELD_NAME):
"""
Redirects the user to the login page, passing the given 'next' page
"""
resolved_url = resolve_url(login_url or settings.LOGIN_URL)
login_url_parts = list(urlparse(resolved_url))
if redirect_field_name:
querystring = QueryDict(login_url_parts[4], mutable=True)
querystring[redirect_field_name] = next
login_url_parts[4] = querystring.urlencode(safe='/')
return HttpResponseRedirect(urlunparse(login_url_parts))
# 4 views for password reset:
# - password_reset sends the mail
# - password_reset_done shows a success message for the above
# - password_reset_confirm checks the link the user clicked and
# prompts for a new password
# - password_reset_complete shows a success message for the above
def assertURLEqual(self, url, expected, parse_qs=False):
"""
Given two URLs, make sure all their components (the ones given by
urlparse) are equal, only comparing components that are present in both
URLs.
If `parse_qs` is True, then the querystrings are parsed with QueryDict.
This is useful if you don't want the order of parameters to matter.
Otherwise, the query strings are compared as-is.
"""
fields = ParseResult._fields
for attr, x, y in zip(fields, urlparse(url), urlparse(expected)):
if parse_qs and attr == 'query':
x, y = QueryDict(x), QueryDict(y)
if x and y and x != y:
self.fail("%r != %r (%s doesn't match)" % (url, expected, attr))
def get_context_from_bindings(code, recipient, bindings):
"""Finalizes the bindings and create a Context for templating
"""
if code not in settings.EMAIL_TEMPLATES:
raise ImproperlyConfigured("Mail '%s' cannot be found")
url = settings.EMAIL_TEMPLATES[code]
res = dict(bindings)
res['EMAIL'] = recipient
qs = QueryDict(mutable=True)
qs.update(res)
# We first initialize the LINK_BROWSER variable as "#" (same page)
qs['LINK_BROWSER'] = "#"
# we generate the final browser link and add it to result dictionary
res['LINK_BROWSER'] = f"{url}?{qs.urlencode()}"
return res
def login(request):
if request.method == 'GET':
return render(request, 'core/login.html', {'alert': request.session.get('alert', False)})
elif request.method == 'POST':
data = QueryDict(request.body)
mysnu_username = data['username']
mysnu_password = data['password']
result = dict()
try:
result = crawlCourse(mysnu_username, mysnu_password)
except Exception:
request.session['alert'] = True
return redirect('login')
request.session['result'] = result
request.session.set_expiry(3600)
return redirect('courses')
def redirect_to_login(next, login_url=None,
redirect_field_name=REDIRECT_FIELD_NAME):
"""
Redirects the user to the login page, passing the given 'next' page
"""
resolved_url = resolve_url(login_url or settings.LOGIN_URL)
login_url_parts = list(urlparse(resolved_url))
if redirect_field_name:
querystring = QueryDict(login_url_parts[4], mutable=True)
querystring[redirect_field_name] = next
login_url_parts[4] = querystring.urlencode(safe='/')
return HttpResponseRedirect(urlunparse(login_url_parts))
# 4 views for password reset:
# - password_reset sends the mail
# - password_reset_done shows a success message for the above
# - password_reset_confirm checks the link the user clicked and
# prompts for a new password
# - password_reset_complete shows a success message for the above
def redirect_to_login(next, login_url=None,
redirect_field_name=REDIRECT_FIELD_NAME):
"""
Redirects the user to the login page, passing the given 'next' page
"""
resolved_url = resolve_url(login_url or settings.LOGIN_URL)
login_url_parts = list(urlparse(resolved_url))
if redirect_field_name:
querystring = QueryDict(login_url_parts[4], mutable=True)
querystring[redirect_field_name] = next
login_url_parts[4] = querystring.urlencode(safe='/')
return HttpResponseRedirect(urlunparse(login_url_parts))
# 4 views for password reset:
# - password_reset sends the mail
# - password_reset_done shows a success message for the above
# - password_reset_confirm checks the link the user clicked and
# prompts for a new password
# - password_reset_complete shows a success message for the above
def handle_redirect_to_login(request, **kwargs):
login_url = kwargs.get("login_url")
redirect_field_name = kwargs.get("redirect_field_name")
next_url = kwargs.get("next_url")
if login_url is None:
login_url = settings.ACCOUNT_LOGIN_URL
if next_url is None:
next_url = request.get_full_path()
try:
login_url = urlresolvers.reverse(login_url)
except urlresolvers.NoReverseMatch:
if callable(login_url):
raise
if "/" not in login_url and "." not in login_url:
raise
url_bits = list(urlparse(login_url))
if redirect_field_name:
querystring = QueryDict(url_bits[4], mutable=True)
querystring[redirect_field_name] = next_url
url_bits[4] = querystring.urlencode(safe="/")
return HttpResponseRedirect(urlunparse(url_bits))