Exemplo n.º 1
0
def get_oauth_url(request, scope, redirect_uri=None, extra_params=None):
    '''
    Returns the oauth url for the given request and scope
    Request maybe shouldnt be tied to this function, but for now it seems
    rather ocnvenient
    '''
    from django_facebook import settings as facebook_settings
    scope = parse_scope(scope)
    query_dict = QueryDict('', True)
    query_dict['scope'] = ','.join(scope)
    query_dict['client_id'] = facebook_settings.FACEBOOK_APP_ID
    redirect_uri = redirect_uri or request.build_absolute_uri()
    current_uri = redirect_uri

    # set attempt=1 to prevent endless redirect loops
    if 'attempt=1' not in redirect_uri:
        if '?' not in redirect_uri:
            redirect_uri += '?attempt=1'
        else:
            redirect_uri += '&attempt=1'

    query_dict['redirect_uri'] = redirect_uri
    oauth_url = 'https://www.facebook.com/dialog/oauth?'
    oauth_url += query_dict.urlencode()
    return oauth_url, current_uri, redirect_uri
Exemplo n.º 2
0
 def test_mutable_copy(self):
     """A copy of a QueryDict is mutable."""
     q = QueryDict().copy()
     with self.assertRaises(KeyError):
         q.__getitem__("foo")
     q['name'] = 'john'
     self.assertEqual(q['name'], 'john')
Exemplo n.º 3
0
 def test_https_login_url(self):
     login_url = 'https:///login/'
     login_required_url = self.get_login_required_url(login_url)
     querystring = QueryDict('', mutable=True)
     querystring['next'] = 'http://testserver/login_required/'
     self.assertEqual(login_required_url,
                      '%s?%s' % (login_url, querystring.urlencode('/')))
 def buildRequestUrl(self):
     qd = QueryDict("", mutable=True)
     for key in Quattro.QUERY_STRING_KEYS:
         value = getattr(self, key, None)
         if value:
             qd[key] = value
     return Quattro.QUATTRO_URL + "?" + qd.urlencode()
Exemplo n.º 5
0
 def test_login_url_with_querystring(self):
     login_url = '/login/?pretty=1'
     login_required_url = self.get_login_required_url(login_url)
     querystring = QueryDict('pretty=1', mutable=True)
     querystring['next'] = '/login_required/'
     self.assertEqual(login_required_url, 'http://testserver/login/?%s' %
                      querystring.urlencode('/'))
Exemplo n.º 6
0
def get_oauth_url(request, scope, redirect_uri=None):
    '''
    Returns the oauth url for the given request and scope
    Request maybe shouldnt be tied to this function, but for now it seems 
    rather ocnvenient
    '''
    from django_facebook import settings as facebook_settings
    scope = parse_scope(scope)
    query_dict = QueryDict('', True)
    query_dict['scope'] = ','.join(scope)
    query_dict['client_id'] = facebook_settings.FACEBOOK_APP_ID
    redirect_uri = redirect_uri or request.build_absolute_uri()

    #set attempt=1 to prevent endless redirect loops
    if 'attempt=1' not in redirect_uri:
        if '?' not in redirect_uri:
            redirect_uri += '?attempt=1'
        else:
            redirect_uri += '&attempt=1'
        
    if ('//localhost' in redirect_uri or '//127.0.0.1' in redirect_uri) and settings.DEBUG:
        raise ValueError, 'Facebook checks the domain name of your apps. Therefor you cannot run on localhost. Instead you should use something like local.fashiolista.com. Replace Fashiolista with your own domain name.'
    query_dict['redirect_uri'] = redirect_uri
    url = 'https://www.facebook.com/dialog/oauth?'
    url += query_dict.urlencode()
    return url, redirect_uri
Exemplo n.º 7
0
    def get_form_kwargs(self):
        
        kwargs = super(UpdateFormEntryView, self).get_form_kwargs()

        #ADD REFERNCE TO FORM OBJECT AND FIELD DATA
        kwargs['form_schema'] = self.object
        kwargs['request'] = self.request
        kwargs['instance'] = self.form_entry_object
        

        if self.request.method in ('POST', 'PUT'):
            
            kwargs.update({
                'data': self.request.POST,
                'files': self.request.FILES,
            })
            
        else:
            
            data = {'form_schema':self.object.pk}
            fields = self.form_entry_object.get_entries()
            for field in fields:
                key = self.form_class.form_field_prefix+field.form_field.slug
                data[key] = field.decompressed_value

            qdict = QueryDict('', mutable=True)
            qdict.update(data)
            kwargs['data'] = qdict

        

        return kwargs
Exemplo n.º 8
0
def get_job_detail_breadbox(request, job_id):
    job = get_job(request, job_id)
    if not job:
        return {}

    site_config = get_site_config(request)

    breadbox = helpers.job_breadcrumbs(job, site_config.browse_company_show)

    query_string = get_query_string(request)
    if query_string:
        # Append the query_path to all of the exising urls
        for field in breadbox:
            path = breadbox[field].get('path', '/jobs/')
            path_and_query_string = "%s?%s" % (path, query_string)
            new_url = (path_and_query_string if query_string
                       else breadbox[field]['path'])
            breadbox[field]['path'] = new_url

        # Create a new path for title and moc query string values
        # from the job information.
        fields = ['title', 'city']
        path = ''
        for field in fields:
            slab = getattr(job, '%s_slab' % field)
            path = "%s%s/" % (path, slab.split("::")[0])
        for field in ['q', 'moc']:
            if request.GET.get(field, None):
                breadbox[field] = {}
                qs = QueryDict(query_string).copy()
                del qs[field]
                breadbox[field]['path'] = "/%s?%s" % (path, qs.urlencode())
                breadbox[field]['display'] = request.GET.get(field)

    return breadbox
Exemplo n.º 9
0
    def get(self, request):
        data = self.get_data(request)
        code = self.get_data(request, "code")
        error = self.get_data(request, "error")
        client = self.get_data(request, "client")

        redirect_uri = data.get('redirect_uri', None) or client.redirect_uri

        parsed = urlparse.urlparse(redirect_uri)

        query = QueryDict('', mutable=True)

        if 'state' in data:
            query['state'] = data['state']

        if error is not None:
            query.update(error)
        elif code is None:
            query['error'] = 'access_denied'
        else:
            query['code'] = code

        parsed = parsed[:4] + (query.urlencode(), '')

        redirect_uri = urlparse.ParseResult(*parsed).geturl()

        self.clear_data(request)

        return HttpResponseRedirect(redirect_uri)
Exemplo n.º 10
0
    def test_single_key_value(self):
        """Test QueryDict with one key/value pair"""

        q = QueryDict('foo=bar')
        self.assertEqual(q['foo'], 'bar')
        self.assertRaises(KeyError, q.__getitem__, 'bar')
        self.assertRaises(AttributeError, q.__setitem__, 'something', 'bar')

        self.assertEqual(q.get('foo', 'default'), 'bar')
        self.assertEqual(q.get('bar', 'default'), 'default')
        self.assertEqual(q.getlist('foo'), ['bar'])
        self.assertEqual(q.getlist('bar'), [])

        self.assertRaises(AttributeError, q.setlist, 'foo', ['bar'])
        self.assertRaises(AttributeError, q.appendlist, 'foo', ['bar'])

        self.assertTrue(q.has_key('foo'))
        self.assertTrue('foo' in q)
        self.assertFalse(q.has_key('bar'))
        self.assertFalse('bar' in q)

        self.assertEqual(q.items(), [(u'foo', u'bar')])
        self.assertEqual(q.lists(), [(u'foo', [u'bar'])])
        self.assertEqual(q.keys(), ['foo'])
        self.assertEqual(q.values(), ['bar'])
        self.assertEqual(len(q), 1)

        self.assertRaises(AttributeError, q.update, {'foo': 'bar'})
        self.assertRaises(AttributeError, q.pop, 'foo')
        self.assertRaises(AttributeError, q.popitem)
        self.assertRaises(AttributeError, q.clear)
        self.assertRaises(AttributeError, q.setdefault, 'foo', 'bar')

        self.assertEqual(q.urlencode(), 'foo=bar')
Exemplo n.º 11
0
def next_redirect(request, default='/', additional_params=None,
                  next_key='next', redirect_url=None, canvas=False):
    from django_facebook import settings as facebook_settings
    if facebook_settings.FACEBOOK_DEBUG_REDIRECTS:
        return HttpResponse(
            '<html><head></head><body><div>Debugging</div></body></html>')
    from django.http import HttpResponseRedirect
    if not isinstance(next_key, (list, tuple)):
        next_key = [next_key]

    # get the redirect url
    if not redirect_url:
        for key in next_key:
            redirect_url = request.REQUEST.get(key)
            if redirect_url:
                break
        if not redirect_url:
            redirect_url = default

    if additional_params:
        query_params = QueryDict('', True)
        query_params.update(additional_params)
        seperator = '&' if '?' in redirect_url else '?'
        redirect_url += seperator + query_params.urlencode()

    if canvas:
        return CanvasRedirect(redirect_url)
    
    return HttpResponseRedirect(redirect_url)
Exemplo n.º 12
0
 def test_add(self):
     """
     Test adding a plugin to a *PAGE*.
     """
     page, placeholder, superuser, staff = self.get_data()
     get_data = {
         'plugin_type': "TextPlugin",
         'plugin_language': settings.LANGUAGES[0][0],
         'placeholder_id': page.placeholders.get(slot="body").pk,
     }
     post_data = {}
     self.assertEqual(CMSPlugin.objects.count(), 0)
     # log the user out and post the plugin data to the cms add-plugin URL.
     self.client.logout()
     add_url = URL_CMS_PLUGIN_ADD + '?' + urlencode(get_data)
     response = self.client.post(add_url, post_data)
     # since the user is not logged in, they should be prompted to log in.
     self.assertEqual(response.status_code, 302)
     querystring = QueryDict('', mutable=True)
     querystring['next'] = add_url
     expected_url = '/{lang}/admin/login/?{next}'.format(
         lang=settings.LANGUAGES[0][0],
         next=querystring.urlencode(safe='/')
     )
     self.assertRedirects(response, expected_url)
     self.assertEqual(CMSPlugin.objects.count(), 0)
     # now log a staff user without permissions in and do the same as above.
     self.client.login(username=getattr(staff, get_user_model().USERNAME_FIELD),
                       password=getattr(staff, get_user_model().USERNAME_FIELD))
     response = self.client.post(add_url, post_data)
     # the user is logged in and the security check fails, so it should 403.
     self.assertEqual(response.status_code, 403)
     self.assertEqual(CMSPlugin.objects.count(), 0)
Exemplo n.º 13
0
    def _wrapped_view(request, gid, *args, **kwargs):
        if not canEdit(request, gid):
            url = reverse("maps:auth", kwargs={"gid":gid})
            fwd = QueryDict('p=%s' % request.get_full_path())
            return HttpResponseRedirect("%s?%s" % (url, fwd.urlencode()))

        return view(request, gid, *args, **kwargs)
Exemplo n.º 14
0
def sso_logout(request):
    qs = QueryDict(None, mutable=True)
    qs['callback_url'] = request.build_absolute_uri(settings.SSO_LOGOUT_CALLBACK_PATH)

    logout_url = '{0}?{1}'.format(sso_hostname('/logout'), qs.urlencode(safe='/'))

    return HttpResponseRedirect(logout_url)
Exemplo n.º 15
0
def _get_nodes(request, graph_id, query={}):
	"""

	Query Parameters
	----------
	graph_id : string
		Unique ID of the graph.
	limit : integer
		Number of entities to return. Default value is 20.
	offset : integer
		Offset the list of returned entities by this number. Default value is 0.
	names : list of strings
		Search for groups with given names. In order to search for groups with given name as a substring, wrap the name with percentage symbol. For example, %xyz% will search for all groups with xyz in their name.
	labels : list of strings
		Search for groups with given labels. In order to search for groups with given label as a substring, wrap the label with percentage symbol. For example, %xyz% will search for all groups with xyz in their label.
	order : string
		Defines the column sort order, can only be 'asc' or 'desc'.
	sort : string
		Defines which column will be sorted.


	Parameters
	----------
	request : object
		HTTP GET Request.

	Returns
	-------
	total : integer
		Number of nodes matching the request.
	nodes : List of nodes.
		List of Node Objects with given limit and offset.

	Raises
	------

	Notes
	------

	"""

	authorization.validate(request, permission='GRAPH_READ', graph_id=graph_id)

	querydict = QueryDict('', mutable=True)
	querydict.update(query)
	query = querydict

	total, nodes_list = graphs.search_nodes(request,
	                                        graph_id=graph_id,
	                                        names=query.getlist('names[]', None),
	                                        labels=query.getlist('labels[]', None),
	                                        limit=query.get('limit', 20),
	                                        offset=query.get('offset', 0),
	                                        order=query.get('order', 'desc'),
	                                        sort=query.get('sort', 'name'))

	return {
		'total': total,
		'nodes': [utils.serializer(node) for node in nodes_list]
	}
Exemplo n.º 16
0
    def render_change_form(self, request, context, add=False, change=False,
                           form_url='', obj=None):
        lang_code = self._language(request)
        lang = get_language_name(lang_code)
        available_languages = self.get_available_languages(obj)

        context.update({
            'title': '%s (%s)' % (context['title'], lang),
            'current_is_translated': lang_code in available_languages,
            'allow_deletion': len(available_languages) > 1,
            'language_tabs': self.get_language_tabs(request, available_languages),
            'base_template': self.get_change_form_base_template(),
        })

        # Ensure form action url carries over tab language
        qs_language = request.GET.get('language')
        if qs_language:
            form_url = urlparse(form_url or request.get_full_path())
            query = QueryDict(form_url.query, mutable=True)
            if 'language' not in query:
                query['language'] = qs_language
            form_url = form_url._replace(query=query.urlencode()).geturl()

        return super(TranslatableAdmin, self).render_change_form(request,
                                                                  context,
                                                                  add, change,
                                                                  form_url, obj)
def form_validate(formclass, data, instance=None, commit=True):
    '''
    Uses a form to validate data passed in as a dictionary. See
    http://docs.djangoproject.com/en/dev/ref/forms/validation/

    Arguments:
    
        formclass
            The class of the form to use

        data
            A dictionary of data

        instance
            An existing instance to use to validate
    '''

    qd = QueryDict({}).copy()
    qd.update(data)

    form = formclass(qd, instance=instance)

    if not form.is_valid():
        raise exceptions.APIBadRequest(simplejson.dumps(form.errors))

    return form.save(commit=commit)
Exemplo n.º 18
0
 def test_edit(self):
     """
     Test editing a *PAGE* plugin
     """
     page, placeholder, superuser, staff = self.get_data()
     # create the plugin using a superuser
     plugin = add_plugin(placeholder, 'TextPlugin', 'en', body='body')
     plugin_data = {
         'plugin_id': plugin.pk,
         'body': 'newbody',
     }
     self.assertEqual(plugin.body, 'body') # check the body is as expected.
     # log the user out, try to edit the plugin
     self.client.logout()
     endpoint = self.get_change_plugin_uri(plugin)
     response = self.client.post(endpoint, plugin_data)
     # since the user is not logged in, they should be prompted to log in.
     self.assertEqual(response.status_code, 302)
     querystring = QueryDict('', mutable=True)
     querystring['next'] = endpoint
     expected_url = '/{lang}/admin/login/?{next}'.format(
         lang=settings.LANGUAGES[0][0],
         next=querystring.urlencode(safe='/')
     )
     self.assertRedirects(response, expected_url)
     plugin = self.reload(plugin)
     self.assertEqual(plugin.body, 'body')
     # now log a staff user without permissions in and do the same as above.
     self.client.login(username=getattr(staff, get_user_model().USERNAME_FIELD),
                       password=getattr(staff, get_user_model().USERNAME_FIELD))
     response = self.client.post(endpoint, plugin_data)
     # the user is logged in and the security check fails, so it should 403.
     self.assertEqual(response.status_code, 403)
     plugin = self.reload(plugin)
     self.assertEqual(plugin.body, 'body')
Exemplo n.º 19
0
    def process_request(self, request):
        if 'application/json' in request.META.get('CONTENT_TYPE', ''):
            # load the json data
            data = json.loads(request.body)
            # for consistency sake, we want to return
            # a Django QueryDict and not a plain Dict.
            # The primary difference is that the QueryDict stores
            # every value in a list and is, by default, immutable.
            # The primary issue is making sure that list values are
            # properly inserted into the QueryDict.  If we simply
            # do a q_data.update(data), any list values will be wrapped
            # in another list. By iterating through the list and updating
            # for each value, we get the expected result of a single list.
            q_data = QueryDict('', mutable=True)
            for key, value in data.iteritems():
                print value
                if isinstance(value, list):
                    # need to iterate through the list and update
                    # so that the list does not get wrapped in an
                    # additional list.
                    for x in value:
                        q_data.update({key: x})
                else:
                    q_data.update({key: value})

            if request.method == 'GET':
                request.GET = q_data

            if request.method == 'POST':
                request.POST = q_data

        return None
Exemplo n.º 20
0
 def test_mutable_copy(self):
     """A copy of a QueryDict is mutable."""
     q = QueryDict().copy()
     with self.assertRaises(KeyError):
         q.__getitem__("foo")
     q["name"] = "john"
     self.assertEqual(q["name"], "john")
Exemplo n.º 21
0
 def test_delete_ph(self):
     page, placeholder, superuser, staff = self.get_data()
     plugin = add_plugin(placeholder, 'TextPlugin', 'en', body='body')
     plugin_data = {
         'plugin_id': plugin.pk,
     }
     plugin = self.reload(plugin)
     self.assertEqual(plugin.body, 'body')
     endpoint = self.get_delete_plugin_uri(plugin, container=Example1)
     # log the user out and try to remove a plugin using PlaceholderAdmin
     self.client.logout()
     response = self.client.post(endpoint, plugin_data)
     # since the user is not logged in, they should be prompted to log in.
     self.assertEqual(response.status_code, 302)
     querystring = QueryDict('', mutable=True)
     querystring['next'] = endpoint
     expected_url = '/{lang}/admin/login/?{next}'.format(
         lang=settings.LANGUAGES[0][0],
         next=querystring.urlencode(safe='/')
     )
     self.assertRedirects(response, expected_url)
     self.assertEqual(CMSPlugin.objects.count(), 1)
     # now log a staff user without permissions in and do the same as above.
     self.client.login(username=getattr(staff, get_user_model().USERNAME_FIELD),
                       password=getattr(staff, get_user_model().USERNAME_FIELD))
     response = self.client.post(endpoint, plugin_data)
     # the user is logged in and the security check fails, so it should 403.
     self.assertEqual(response.status_code, 403)
     self.assertEqual(CMSPlugin.objects.count(), 1)
Exemplo n.º 22
0
def test_remove_qs_to_several():
    orig = QueryDict(mutable=True)
    orig.update({'foo': 'val1'})
    orig.update({'foo': 'val2'})
    assert dict(orig) == {'foo': ['val1', 'val2']}
    params = _remove_qs(orig, foo='val2')
    assert dict(params) == {'foo': ['val1']}
Exemplo n.º 23
0
    def _verify_postback(self):
        # ### Now we don't really care what result was, just whether a flag was set or not.
        from paypal.standard.pdt.forms import PayPalPDTForm

        response_list = self.response.split('\n')
        response_dict = {}
        for i, line in enumerate(response_list):
            unquoted_line = unquote_plus(line).strip()
            if i == 0:
                self.st = unquoted_line
            else:
                if self.st != "SUCCESS":
                    self.set_flag(line)
                    break
                try:
                    if not unquoted_line.startswith(' -'):
                        k, v = unquoted_line.split('=')
                        response_dict[k.strip()] = v.strip()
                except ValueError:
                    pass

        qd = QueryDict('', mutable=True)
        qd.update(response_dict)
        qd.update(dict(ipaddress=self.ipaddress, st=self.st, flag_info=self.flag_info, flag=self.flag,
                       flag_code=self.flag_code))
        pdt_form = PayPalPDTForm(qd, instance=self)
        pdt_form.save(commit=False)
Exemplo n.º 24
0
def orders(request):
    """
    This is basically like orders/index, but limited to the user
    First, filter by the provided search criteria,
    then check if we have a saved search filter
    then default to user id
    Always update saved search filter
    """
    args = request.GET.copy()
    default = {"state": Order.STATE_OPEN}

    if len(args) < 2:
        f = request.session.get("account_search_filter", default)
        args = QueryDict("", mutable=True)
        args.update(f)

    # On the profile page, filter by the user, no matter what
    args.update({"followed_by": request.user.pk})
    request.session["account_search_filter"] = args

    data = prepare_list_view(request, args)
    data["title"] = _("My Orders")

    del (data["form"].fields["assigned_to"])

    return render(request, "accounts/orders.html", data)
Exemplo n.º 25
0
    def _parse_response(self, response):
        """Turn the PayPal response into a dict"""
        q = QueryDict(response, encoding='UTF-8').dict()
        tmp = {}
        for k,v in q.items():
            tmp.update({k.lower(): v})
	return tmp
 def _get_initial_query_dict(self, qdict):
     if not qdict:
         qdict = QueryDict(None, mutable=True)
     elif isinstance(qdict, QueryDict):
         qdict = qdict.copy()
     elif isinstance(qdict, basestring):
         if qdict.startswith('?'):
             qdict = qdict[1:]
         qdict = QueryDict(qdict, mutable=True)
     else:
         # Accept any old dict or list of pairs.
         try:
             pairs = qdict.items()
         except:
             pairs = qdict
         qdict = QueryDict(None, mutable=True)
         # Enter each pair into QueryDict object:
         try:
             for k, v in pairs:
                 # Convert values to unicode so that detecting
                 # membership works for numbers.
                 if isinstance(v, (list, tuple)):
                     for e in v:
                         qdict.appendlist(k,unicode(e))
                 else:
                     qdict.appendlist(k, unicode(v))
         except:
             # Wrong data structure, qdict remains empty.
             pass
     return qdict
Exemplo n.º 27
0
def format_preserving_redirect(request, target, get_dict=None):
  """
  If request represents an ajax or embeddable "format", tries
  to preserve that for redirects.

  Any GET params may be passed through the QueryDict get_dict,
  which should be mutable.
  """
  my_get_dict = QueryDict('', mutable=True)
  if get_dict:
    my_get_dict.update(get_dict)

  if is_jframe_request(request):
    logging.info("JFrame redirection" +  target)
    my_get_dict['format'] = 'embed'
  elif request.ajax:
    my_get_dict['format'] = 'json'

  param = my_get_dict.urlencode()
  if param:
    if '?' not in target:
      param = '?' + param
    else:
      param = '&' + param

  return HttpResponseRedirect(target + param)
Exemplo n.º 28
0
    def test_expired_course(self):
        """
        Ensure that a user accessing an expired course sees a redirect to
        the student dashboard, not a 404.
        """
        CourseDurationLimitConfig.objects.create(enabled=True, enabled_as_of=datetime(2010, 1, 1))
        course = CourseFactory.create(start=THREE_YEARS_AGO)
        url = course_home_url(course)

        for mode in [CourseMode.AUDIT, CourseMode.VERIFIED]:
            CourseModeFactory.create(course_id=course.id, mode_slug=mode)

        # assert that an if an expired audit user tries to access the course they are redirected to the dashboard
        audit_user = UserFactory(password=self.TEST_PASSWORD)
        self.client.login(username=audit_user.username, password=self.TEST_PASSWORD)
        audit_enrollment = CourseEnrollment.enroll(audit_user, course.id, mode=CourseMode.AUDIT)
        ScheduleFactory(start=THREE_YEARS_AGO, enrollment=audit_enrollment)

        response = self.client.get(url)

        expiration_date = strftime_localized(course.start + timedelta(weeks=4), 'SHORT_DATE')
        expected_params = QueryDict(mutable=True)
        course_name = CourseOverview.get_from_id(course.id).display_name_with_default
        expected_params['access_response_error'] = 'Access to {run} expired on {expiration_date}'.format(
            run=course_name,
            expiration_date=expiration_date
        )
        expected_url = '{url}?{params}'.format(
            url=reverse('dashboard'),
            params=expected_params.urlencode()
        )
        self.assertRedirects(response, expected_url)
Exemplo n.º 29
0
    def test_single_key_value(self):
        """Test QueryDict with one key/value pair"""

        q = QueryDict("foo=bar")
        self.assertEqual(q["foo"], "bar")
        self.assertRaises(KeyError, q.__getitem__, "bar")
        self.assertRaises(AttributeError, q.__setitem__, "something", "bar")

        self.assertEqual(q.get("foo", "default"), "bar")
        self.assertEqual(q.get("bar", "default"), "default")
        self.assertEqual(q.getlist("foo"), ["bar"])
        self.assertEqual(q.getlist("bar"), [])

        self.assertRaises(AttributeError, q.setlist, "foo", ["bar"])
        self.assertRaises(AttributeError, q.appendlist, "foo", ["bar"])

        self.assertTrue(q.has_key("foo"))
        self.assertTrue("foo" in q)
        self.assertFalse(q.has_key("bar"))
        self.assertFalse("bar" in q)

        self.assertEqual(q.items(), [(u"foo", u"bar")])
        self.assertEqual(q.lists(), [(u"foo", [u"bar"])])
        self.assertEqual(q.keys(), ["foo"])
        self.assertEqual(q.values(), ["bar"])
        self.assertEqual(len(q), 1)

        self.assertRaises(AttributeError, q.update, {"foo": "bar"})
        self.assertRaises(AttributeError, q.pop, "foo")
        self.assertRaises(AttributeError, q.popitem)
        self.assertRaises(AttributeError, q.clear)
        self.assertRaises(AttributeError, q.setdefault, "foo", "bar")

        self.assertEqual(q.urlencode(), "foo=bar")
Exemplo n.º 30
0
Arquivo: rpc.py Projeto: intaxi/adrest
    def rpc_call(self, request, method=None, **payload):
        """ Call REST API with RPC force.
        """
        assert method and self.separator in method, \
            "Wrong method name: {0}".format(method)

        resource_name, method = method.split(self.separator, 1)
        assert resource_name in self.api.resources, "Unknown method"

        data = QueryDict('', mutable=True)
        data.update(payload.get('data', dict()))
        data['callback'] = payload.get('callback') or request.GET.get(
            'callback') or request.GET.get('jsonp') or 'callback'
        for h, v in payload.get('headers', dict()).iteritems():
            request.META["HTTP_%s" % h.upper().replace('-', '_')] = v

        request.POST = request.PUT = request.GET = data
        delattr(request, '_request')
        request.method = method.upper()
        request.META['CONTENT_TYPE'] = 'application/x-www-form-urlencoded'
        params = payload.pop('params', dict())
        response = self.api.call(resource_name, request, **params)
        response.finaly = True
        assert response.status_code == 200, response.content
        return response
Exemplo n.º 31
0
 def get_url_found_user(user, page):
     get = QueryDict('', mutable=True)
     get['page'] = page
     return url + '?' + get.urlencode() + '#' + str(user.id)
Exemplo n.º 32
0
    def setUp(self):
        super(ClipboardPluginTest, self).setUp()
        UserModel = get_user_model()
        self.admin_user = UserModel.objects.get(username='******')

        # add a Bootstrap Container Plugin
        container_model = add_plugin(self.placeholder, BootstrapContainerPlugin, 'en',
                                     glossary={'breakpoints': BS3_BREAKPOINT_KEYS})
        self.assertIsInstance(container_model, CascadeElement)
        container_plugin = container_model.get_plugin_class_instance(self.admin_site)
        self.assertIsInstance(container_plugin, BootstrapContainerPlugin)
        ModelForm = container_plugin.get_form(self.request, container_model)
        post_data = QueryDict('', mutable=True)
        post_data.setlist('breakpoints', ['sm', 'md'])
        form = ModelForm(post_data, None, instance=container_model)
        html = form.as_p()
        self.assertInHTML(
            '<input id="id_glossary_breakpoints_0" name="breakpoints" type="checkbox" value="xs" />',
            html)
        self.assertInHTML(
            '<input checked="checked" id="id_glossary_breakpoints_2" name="breakpoints" type="checkbox" value="md" />',
            html)
        self.assertInHTML('<input id="id_glossary_fluid" name="fluid" type="checkbox" />', html)
        container_plugin.save_model(self.request, container_model, form, False)
        self.assertListEqual(container_model.glossary['breakpoints'], ['sm', 'md'])
        self.assertTrue('fluid' in container_model.glossary)
        self.assertEqual(str(container_model), 'for tablets, laptops')

        # add a RowPlugin with 3 Columns
        row_model = add_plugin(self.placeholder, BootstrapRowPlugin, 'en', target=container_model)
        row_plugin = row_model.get_plugin_class_instance()
        row_change_form = BootstrapRowForm({'num_children': 3})
        row_change_form.full_clean()
        row_plugin.save_model(self.request, row_model, row_change_form, False)
        self.assertDictEqual(row_model.glossary, {})
        self.assertIsInstance(row_model, CascadeElement)
        self.assertEqual(str(row_model), 'with 3 columns')
        plugin_list = [container_model, row_model]
        columns_qs = CascadeElement.objects.filter(parent_id=row_model.id)
        self.assertEqual(columns_qs.count(), 3)
        row_data = []
        for column_model in columns_qs:
            self.assertIsInstance(column_model, CascadeElement)
            column_plugin = column_model.get_plugin_class_instance()
            self.assertIsInstance(column_plugin, BootstrapColumnPlugin)
            self.assertEqual(column_model.parent.id, row_model.id)
            self.assertEqual(str(column_model), 'default width: 4 units')
            plugin_list.append(column_model)
            row_data.append(['BootstrapColumnPlugin', {'glossary': column_model.glossary}, []])
        # container_data = ['BootstrapRowPlugin', {'glossary': row_model.glossary}, row_data]

        # Render the Container Plugin with all of its children
        build_plugin_tree(plugin_list)
        html = self.get_html(container_model, self.get_request_context())
        self.assertHTMLEqual(html, '<div class="container"><div class="row">' +
                             '<div class="col-sm-4"></div><div class="col-sm-4"></div>' +
                             '<div class="col-sm-4"></div>' +
                             '</div></div>')

        # change data inside the first column
        column_model = columns_qs[0]
        delattr(column_model, '_inst')
        column_plugin = column_model.get_plugin_class_instance(self.admin_site)
        column_plugin.cms_plugin_instance = column_model
        post_data = QueryDict('', mutable=True)
        post_data.update({'sm-column-offset': 'col-sm-offset-1', 'sm-column-width': 'col-sm-3'})
        ModelForm = column_plugin.get_form(self.request, column_model)
        form = ModelForm(post_data, None, instance=column_model)
        self.assertTrue(form.is_valid())
        column_plugin.save_model(self.request, column_model, form, True)

        # change data inside the second column
        column_model = columns_qs[1]
        delattr(column_model, '_inst')
        column_plugin = column_model.get_plugin_class_instance(self.admin_site)
        column_plugin.cms_plugin_instance = column_model
        post_data = QueryDict('', mutable=True)
        post_data.update({'sm-responsive-utils': 'hidden-sm', 'sm-column-width': 'col-sm-4'})
        ModelForm = column_plugin.get_form(self.request, column_model)
        form = ModelForm(post_data, None, instance=column_model)
        self.assertTrue(form.is_valid())
        column_plugin.save_model(self.request, column_model, form, False)
        html = self.get_html(container_model, self.get_request_context())
        self.assertHTMLEqual(html, '<div class="container"><div class="row">' +
                             '<div class="col-sm-3 col-sm-offset-1"></div>' +
                             '<div class="col-sm-4 hidden-sm"></div><div class="col-sm-4"></div>' +
                             '</div></div>')
Exemplo n.º 33
0
def do_oauth(accounts, apps, variant, settings, otp):
    from accounts.models import Account
    from idapi.models import IDApplication
    from django.core.urlresolvers import reverse
    from django.http import QueryDict
    import json

    def check_redirect(response, redirect_uri):
        assert response.status_code == 302
        assert response.url.index(redirect_uri) == 0
        from six.moves.urllib import parse
        params = QueryDict(parse.urlparse(response.url).query)
        assert params['state'] == 'mystate'
        return params

    noop = DummyContext()
    client = Client(secure=True)
    settings.TWO_FACTOR_AUTH = False
    member1 = accounts['member1']
    if variant == 'inactive':
        member1.is_active = False
        member1.save(update_fields=['is_active'])

    url = reverse('authorize')
    app = apps['portal']
    qd = QueryDict('', mutable=True)
    redirect_uri = app.redirect_uris
    data = dict(
        redirect_uri=redirect_uri,
        client_id=app.client_id,
        scope="unique member profile",
        state="mystate",
        response_type="code",
    )
    if variant in ('redirect_uri1', 'scope1', 'client_id1'):
        data[variant[:-1]] = 'bad'
        normal = False
    else:
        normal = True
    qd.update(data)
    url += '?' + qd.urlencode()
    response = client.get(url)
    assert SESSION_KEY not in client.session
    if not normal:
        if variant == 'scope1':
            params = check_redirect(response, redirect_uri)
            assert params['error'] == 'invalid_scope'
        else:
            assert response.status_code == 400
        return
    else:
        assert response.status_code == 200
    data = response.context['form'].initial
    data.update(dict(username='******', password='******',
                     allow='Authorize'))  #,allow='Authorize'
    expect = raises(AssertionError)
    if variant in ('username', 'password'): data[variant] = 'bad'
    elif variant in ('redirect_uri2', 'scope2', 'client_id2'):
        data[variant[:-1]] = 'bad'
        if variant != 'redirect_uri2': expect = noop
    elif variant == 'inactive': pass
    else: expect = noop
    response = client.post(url, data, follow=False)
    with expect:
        params = check_redirect(response, redirect_uri)
        assert SESSION_KEY not in client.session
        if variant == 'scope2':
            assert params['error']=='invalid_scope' and \
                params['error_description'] == 'scope bad is not permitted for this client'
            return
        elif variant == 'client_id2':
            assert params['error'] == 'invalid_client_id'
            return
        code = params['code']
    if not expect is noop: return
    data = dict(
        code=code,
        client_id=app.client_id,
        client_secret=app.client_secret,
        grant_type='authorization_code',
        redirect_uri=redirect_uri,
    )
    expect = raises(AssertionError)
    if variant[:-1] in ('redirect_uri', 'client_id') and variant[-1] == '3':
        data[variant[:-1]] = 'bad'
    elif variant in ('client_secret', 'code'):
        data['client_secret'] = 'bad'
    else:
        expect = noop
    headers = {
        'Content-Type': 'application/x-www-form-urlencoded',
        'Accept': 'application/json'
    }
    response = client.post(reverse('oauth2_provider:token'), data, **headers)
    with expect:
        assert response.status_code == 200
        resp = json.loads(response.content.decode('utf-8'))
        assert resp['scope'] == qd['scope'] and resp['token_type'] == 'Bearer'
Exemplo n.º 34
0
def do_login(accounts, variant, settings, otp):
    from accounts.models import Account
    from django.core import mail
    from django.core.urlresolvers import reverse
    from django.http import QueryDict
    from django_otp.plugins.otp_email.models import EmailDevice
    import re
    member1 = accounts['member1']
    noop = DummyContext()
    client = Client(secure=True)
    device = 'django_otp.plugins.otp_email.models.EmailDevice/\d+'
    if variant == 'inactive':
        member1.is_active = False
        member1.save(update_fields=['is_active'])
    elif variant in ['opton', 'optoff']:
        settings.TWO_FACTOR_AUTH = 'optional'
        member1.two_factor_auth = variant == 'opton'
        member1.save(update_fields=['two_factor_auth'])
    elif otp:
        settings.TWO_FACTOR_AUTH = 'mandatory'
    else:
        settings.TWO_FACTOR_AUTH = False
    if otp:
        EmailDevice.objects.create(user=member1, name='email', confirmed=True)
    url = reverse('accounts:index')
    if variant == 'next':
        nexturl = reverse('accounts:profile')
        qd = QueryDict('', mutable=True)
        qd['next'] = nexturl
        url += '?' + qd.urlencode()
    else:
        nexturl = url
    if variant == 'partial':
        assert client.login(username='******', password='******')
    response = client.get(url, follow=True)
    check_response(response)
    assert 'form' in response.context

    if variant != 'partial':
        assert SESSION_KEY not in client.session
        data = dict(username='******', password='******')
        if variant in ('username', 'password'): data[variant] = 'bad'
        response = client.post(url, data, follow=True)
        if variant == 'optoff':
            check_response(response, url)
            assert SESSION_KEY in client.session
            return
        if variant in ['', 'next', 'token', 'opton']: expect = noop
        else: expect = raises(AssertionError)
        with expect:
            if otp:
                assert SESSION_KEY not in client.session
                check_response(response)
                assert 'form' in response.context
                device = re.search(device, response.content.decode("utf8"))
                assert device
            else:
                check_response(response, nexturl)
                assert SESSION_KEY in client.session
                assert 'form' not in response.context
        if not otp or not expect is noop: return
    else:
        assert SESSION_KEY in client.session
        device = re.search(device, response.content.decode("utf8"))
        assert device
        data = {}

    data['otp_device'] = device.group()
    data['otp_challenge'] = "Get challenge"
    response = client.post(url, data, follow=True)
    check_response(response)
    assert variant == 'partial' or SESSION_KEY not in client.session
    del data['otp_challenge']
    assert len(mail.outbox) == 1
    reply = mail.outbox[0]
    assert reply.to == [receiver]
    if variant == 'token':
        expect = raises(AssertionError)
        data['otp_token'] = 'bad'
    else:
        expect = noop
        data['otp_token'] = reply.body
    with expect:
        response = client.post(url, data, follow=True)
        check_response(response, nexturl)
        assert SESSION_KEY in client.session
        assert 'form' not in response.context
Exemplo n.º 35
0
    def _get_and_send_report(self, language, emails):
        from corehq.apps.reports.views import get_scheduled_report_response, render_full_report_notification

        with localize(language):
            title = (
                _(DEFAULT_REPORT_NOTIF_SUBJECT)
                if self.email_subject == DEFAULT_REPORT_NOTIF_SUBJECT
                else self.email_subject
            )

            attach_excel = getattr(self, 'attach_excel', False)
            try:
                content, excel_files = get_scheduled_report_response(
                    self.owner, self.domain, self._id, attach_excel=attach_excel,
                    send_only_active=True
                )

                # Will be False if ALL the ReportConfigs in the ReportNotification
                # have a start_date in the future.
                if content is False:
                    return

                for email in emails:
                    body = render_full_report_notification(None, content, email, self).content
                    send_html_email_async.delay(
                        title, email, body,
                        email_from=settings.DEFAULT_FROM_EMAIL,
                        file_attachments=excel_files,
                        smtp_exception_skip_list=LARGE_FILE_SIZE_ERROR_CODES)
            except Exception as er:
                notify_exception(
                    None,
                    message="Encountered error while generating report or sending email",
                    details={
                        'subject': title,
                        'recipients': str(emails),
                        'error': er,
                    }
                )
                if getattr(er, 'smtp_code', None) in LARGE_FILE_SIZE_ERROR_CODES or type(er) == ESError:
                    # If the email doesn't work because it is too large to fit in the HTML body,
                    # send it as an excel attachment, by creating a mock request with the right data.

                    for report_config in self.configs:
                        mock_request = HttpRequest()
                        mock_request.couch_user = self.owner
                        mock_request.user = self.owner.get_django_user()
                        mock_request.domain = self.domain
                        mock_request.couch_user.current_domain = self.domain
                        mock_request.couch_user.language = self.language
                        mock_request.method = 'GET'
                        mock_request.bypass_two_factor = True

                        mock_query_string_parts = [report_config.query_string, 'filterSet=true']
                        if report_config.is_configurable_report:
                            mock_query_string_parts.append(urlencode(report_config.filters, True))
                            mock_query_string_parts.append(urlencode(report_config.get_date_range(), True))
                        mock_request.GET = QueryDict('&'.join(mock_query_string_parts))
                        date_range = report_config.get_date_range()
                        start_date = datetime.strptime(date_range['startdate'], '%Y-%m-%d')
                        end_date = datetime.strptime(date_range['enddate'], '%Y-%m-%d')

                        datespan = DateSpan(start_date, end_date)
                        request_data = vars(mock_request)
                        request_data['couch_user'] = mock_request.couch_user.userID
                        request_data['datespan'] = datespan

                        full_request = {'request': request_data,
                                        'domain': request_data['domain'],
                                        'context': {},
                                        'request_params': json_request(request_data['GET'])}

                        export_all_rows_task(report_config.report, full_request, emails)
Exemplo n.º 36
0
    def get_report_content(self, lang, attach_excel=False):
        """
        Get the report's HTML content as rendered by the static view format.

        """
        from corehq.apps.locations.middleware import LocationAccessMiddleware

        try:
            if self.report is None:
                return ReportContent(
                    _("The report used to create this scheduled report is no"
                      " longer available on CommCare HQ.  Please delete this"
                      " scheduled report and create a new one using an available"
                      " report."),
                    None,
                )
        except Exception:
            pass

        if getattr(self.report, 'is_deprecated', False):
            return ReportContent(
                self.report.deprecation_email_message or
                _("[DEPRECATED] %s report has been deprecated and will stop working soon. "
                  "Please update your saved reports email settings if needed." % self.report.name
                  ),
                None,
            )

        mock_request = HttpRequest()
        mock_request.couch_user = self.owner
        mock_request.user = self.owner.get_django_user()
        mock_request.domain = self.domain
        mock_request.couch_user.current_domain = self.domain
        mock_request.couch_user.language = lang
        mock_request.method = 'GET'
        mock_request.bypass_two_factor = True

        mock_query_string_parts = [self.query_string, 'filterSet=true']
        if self.is_configurable_report:
            mock_query_string_parts.append(urlencode(self.filters, True))
            mock_query_string_parts.append(urlencode(self.get_date_range(), True))
        mock_request.GET = QueryDict('&'.join(mock_query_string_parts))

        # Make sure the request gets processed by PRBAC Middleware
        CCHQPRBACMiddleware.apply_prbac(mock_request)
        LocationAccessMiddleware.apply_location_access(mock_request)

        try:
            dispatch_func = functools.partial(self._dispatcher.__class__.as_view(),
                                              mock_request, **self.view_kwargs)
            email_response = dispatch_func(render_as='email')
            if email_response.status_code == 302:
                return ReportContent(
                    _(
                        "We are sorry, but your saved report '%(config_name)s' "
                        "is no longer accessible because the owner %(username)s "
                        "is no longer active."
                    ) % {
                        'config_name': self.name,
                        'username': self.owner.username
                    },
                    None,
                )
            try:
                content_json = json.loads(email_response.content)
            except ValueError:
                email_text = email_response.content
            else:
                email_text = content_json['report']
            excel_attachment = dispatch_func(render_as='excel') if attach_excel else None
            return ReportContent(email_text, excel_attachment)
        except PermissionDenied:
            return ReportContent(
                _(
                    "We are sorry, but your saved report '%(config_name)s' "
                    "is no longer accessible because your subscription does "
                    "not allow Custom Reporting. Please talk to your Project "
                    "Administrator about enabling Custom Reports. If you "
                    "want CommCare HQ to stop sending this message, please "
                    "visit %(saved_reports_url)s to remove this "
                    "Emailed Report."
                ) % {
                    'config_name': self.name,
                    'saved_reports_url': absolute_reverse(
                        'saved_reports', args=[mock_request.domain]
                    ),
                },
                None,
            )
        except Http404:
            return ReportContent(
                _(
                    "We are sorry, but your saved report '%(config_name)s' "
                    "can not be generated since you do not have the correct permissions. "
                    "Please talk to your Project Administrator about getting permissions for this"
                    "report."
                ) % {
                    'config_name': self.name,
                },
                None,
            )
        except UnsupportedSavedReportError:
            return ReportContent(
                _(
                    "We are sorry, but your saved report '%(config_name)s' "
                    "is no longer available. If you think this is a mistake, please report an issue."
                ) % {
                    'config_name': self.name,
                },
                None,
            )
Exemplo n.º 37
0
def cats(request):
    try:
        if request.method == "POST" and request.FILES['catimage']:
            document = request.FILES['catimage']
            cat_name = request.POST['cat_name_placeholder']
            fs = FileSystemStorage()
            imagename = fs.save(document.name, document)

            imageurl = fs.url(imagename)

            previous_image = Cat.objects.filter(owner=request.user,
                                                cat_name=cat_name)[0].imagename

            file_remove = settings.MEDIA_ROOT + "/" + previous_image
            try:
                os.remove(file_remove)
            except:
                pass
            Cat.objects.filter(owner=request.user,
                               cat_name=cat_name).update(imagename=imagename,
                                                         imageurl=imageurl)
    except:
        pass

    try:
        if request.method == "POST" and request.FILES['recordimage']:
            document = request.FILES['recordimage']

            record_id = request.POST['record_id_up']
            fs = FileSystemStorage()
            imagename = fs.save(document.name, document)
            imageurl = fs.url(imagename)

            previous_image = MedicalRecord.objects.filter(
                pk=int(record_id))[0].imagename

            file_remove = settings.MEDIA_ROOT + "/" + previous_image
            try:
                os.remove(file_remove)
            except:
                pass
            MedicalRecord.objects.filter(pk=int(record_id)).update(
                imagename=imagename, imageurl=imageurl)

    except:
        pass

    try:
        if request.method == 'POST' and request.POST[
                'objective'] == "CREATE_CAT":
            cat_name = request.POST['cat_name']
            gender = request.POST['gender']
            birthday = request.POST['birthday']
            cat_weight = request.POST['cat_weight']
            cat_weight_unit = request.POST['cat_weight_unit']
            cat_breed = request.POST['cat_breed']
            Spayed_Neutered = request.POST['Spayed_Neutered']
            microchip_number = request.POST['microchip_number']
            insurance_provider = request.POST['insurance_provider']
            insurance_policy_number = request.POST['insurance_policy_number']
            clinic_name = request.POST['clinic_name']

            if Spayed_Neutered == 'Yes':
                spayed = True
            elif Spayed_Neutered == 'No':
                spayed = False

            Cat.objects.create(owner=request.user,
                               cat_name=cat_name,
                               gender=gender,
                               birthday=birthday,
                               cat_weight=cat_weight,
                               cat_weight_unit=cat_weight_unit,
                               cat_breed=cat_breed,
                               Spayed_Neutered=spayed,
                               microchip_number=microchip_number,
                               insurance_provider=insurance_provider,
                               insurance_policy_number=insurance_policy_number,
                               clinic_name=clinic_name,
                               imagename="",
                               imageurl="")
    except:
        pass

    try:

        if request.method == "PUT" and QueryDict(
                request.body).get('objective') == "EDIT_CAT":
            PUT = QueryDict(request.body)
            cat_name = PUT.get('cat_name')
            gender = PUT.get('gender')
            birthday = PUT.get('birthday')
            cat_photo = PUT.get('cat_photo')
            cat_weight = PUT.get('cat_weight')
            cat_weight_unit = PUT.get('cat_weight_unit')
            cat_breed = PUT.get('cat_breed')
            Spayed_Neutered = PUT.get('Spayed_Neutered')
            microchip_number = PUT.get('microchip_number')
            insurance_provider = PUT.get('insurance_provider')
            insurance_policy_number = PUT.get('insurance_policy_number')
            clinic_name = PUT.get('clinic_name')

            if Spayed_Neutered == 'Yes':
                spayed = True
            elif Spayed_Neutered == 'No':
                spayed = False

            if cat_weight is '':
                cat_weight = None

            if birthday == '':
                Cat.objects.filter(
                    owner=request.user, cat_name=cat_name).update(
                        gender=gender,
                        cat_weight=cat_weight,
                        cat_weight_unit=cat_weight_unit,
                        cat_breed=cat_breed,
                        Spayed_Neutered=spayed,
                        microchip_number=microchip_number,
                        insurance_provider=insurance_provider,
                        insurance_policy_number=insurance_policy_number,
                        clinic_name=clinic_name)
            else:
                Cat.objects.filter(
                    owner=request.user, cat_name=cat_name).update(
                        gender=gender,
                        birthday=birthday,
                        cat_weight=cat_weight,
                        cat_weight_unit=cat_weight_unit,
                        cat_breed=cat_breed,
                        Spayed_Neutered=spayed,
                        microchip_number=microchip_number,
                        insurance_provider=insurance_provider,
                        insurance_policy_number=insurance_policy_number,
                        clinic_name=clinic_name)
    except:
        pass

    try:
        if request.method == "PUT" and QueryDict(
                request.body).get('objective') == "DELETE_CAT":
            cat_name = QueryDict(request.body).get('cat_name')
            Cat.objects.get(owner=request.user, cat_name=cat_name).delete()
    except:
        pass

    try:
        if request.method == 'POST' and request.POST[
                'objective'] == "CREATE_MEDICAL_RECORD":
            cat_model = request.POST['cat_model']
            title = request.POST['title']
            description = request.POST['description']
            the_cat = Cat.objects.get(owner=request.user, cat_name=cat_model)
            MedicalRecord.objects.create(cat=the_cat,
                                         title=title,
                                         description=description,
                                         imagename="",
                                         imageurl="")
    except:
        pass

    try:
        if request.method == "PUT" and QueryDict(
                request.body).get('objective') == "DELETE_MEDICAL_RECORD":
            record_id = QueryDict(request.body).get('record_id')
            MedicalRecord.objects.get(pk=record_id).delete()
    except:
        pass

    try:
        if request.method == "PUT" and QueryDict(
                request.body).get('objective') == "CHANGE_MEDICAL_RECORD":
            PUT = QueryDict(request.body)
            record_id = PUT.get('record_id_change')
            new_title = PUT.get('title_change')
            new_description = PUT.get('description_change')
            MedicalRecord.objects.filter(pk=int(record_id)).update(
                title=new_title, description=new_description)
    except:
        pass

    user_cats = Cat.objects.filter(owner=request.user)
    cat_medical_records = MedicalRecord.objects.filter(cat__owner=request.user)
    context = {
        "owner_cats": user_cats,
        "cat_medical_records": cat_medical_records
    }
    return render(request, 'core/cats.html', context)
Exemplo n.º 38
0
 def test_immutable_get_with_default(self):
     q = QueryDict(str(''))
     self.assertEqual(q.get('foo', 'default'), 'default')
Exemplo n.º 39
0
 def test_update_from_querydict(self):
     """Regression test for #8278: QueryDict.update(QueryDict)"""
     x = QueryDict(str("a=1&a=2"), mutable=True)
     y = QueryDict(str("a=3&a=4"))
     x.update(y)
     self.assertEqual(x.getlist('a'), ['1', '2', '3', '4'])
Exemplo n.º 40
0
 def get_url_for_user(username):
     get = QueryDict('', mutable=True)
     get['user'] = username
     get['page'] = 1
     return url + '?' + get.urlencode()
Exemplo n.º 41
0
 def test_mutable_delete(self):
     q = QueryDict(str('')).copy()
     q['name'] = 'john'
     del q['name']
     self.assertFalse('name' in q)
Exemplo n.º 42
0
 def test_missing_key(self):
     q = QueryDict(str(''))
     self.assertRaises(KeyError, q.__getitem__, 'foo')
Exemplo n.º 43
0
    def test_single_key_value(self):
        """Test QueryDict with one key/value pair"""

        q = QueryDict(str('foo=bar'))
        self.assertEqual(q['foo'], 'bar')
        with self.assertRaises(KeyError):
            q.__getitem__('bar')
        with self.assertRaises(AttributeError):
            q.__setitem__('something', 'bar')

        self.assertEqual(q.get('foo', 'default'), 'bar')
        self.assertEqual(q.get('bar', 'default'), 'default')
        self.assertEqual(q.getlist('foo'), ['bar'])
        self.assertEqual(q.getlist('bar'), [])

        with self.assertRaises(AttributeError):
            q.setlist('foo', ['bar'])
        with self.assertRaises(AttributeError):
            q.appendlist('foo', ['bar'])

        if six.PY2:
            self.assertTrue(q.has_key('foo'))
        self.assertIn('foo', q)
        if six.PY2:
            self.assertFalse(q.has_key('bar'))
        self.assertNotIn('bar', q)

        self.assertEqual(list(six.iteritems(q)), [('foo', 'bar')])
        self.assertEqual(list(six.iterlists(q)), [('foo', ['bar'])])
        self.assertEqual(list(six.iterkeys(q)), ['foo'])
        self.assertEqual(list(six.itervalues(q)), ['bar'])
        self.assertEqual(len(q), 1)

        with self.assertRaises(AttributeError):
            q.update({'foo': 'bar'})
        with self.assertRaises(AttributeError):
            q.pop('foo')
        with self.assertRaises(AttributeError):
            q.popitem()
        with self.assertRaises(AttributeError):
            q.clear()
        with self.assertRaises(AttributeError):
            q.setdefault('foo', 'bar')

        self.assertEqual(q.urlencode(), 'foo=bar')
Exemplo n.º 44
0
    def test_basic_mutable_operations(self):
        q = QueryDict(str('')).copy()
        q['name'] = 'john'
        self.assertEqual(q.get('foo', 'default'), 'default')
        self.assertEqual(q.get('name', 'default'), 'john')
        self.assertEqual(q.getlist('name'), ['john'])
        self.assertEqual(q.getlist('foo'), [])

        q.setlist('foo', ['bar', 'baz'])
        self.assertEqual(q.get('foo', 'default'), 'baz')
        self.assertEqual(q.getlist('foo'), ['bar', 'baz'])

        q.appendlist('foo', 'another')
        self.assertEqual(q.getlist('foo'), ['bar', 'baz', 'another'])
        self.assertEqual(q['foo'], 'another')
        if six.PY2:
            self.assertTrue(q.has_key('foo'))
        self.assertTrue('foo' in q)

        self.assertListEqual(sorted(list(six.iteritems(q))),
                             [('foo', 'another'), ('name', 'john')])
        self.assertListEqual(sorted(list(six.iterlists(q))),
                             [('foo', ['bar', 'baz', 'another']),
                              ('name', ['john'])])
        self.assertListEqual(sorted(list(six.iterkeys(q))), ['foo', 'name'])
        self.assertListEqual(sorted(list(six.itervalues(q))),
                             ['another', 'john'])

        q.update({'foo': 'hello'})
        self.assertEqual(q['foo'], 'hello')
        self.assertEqual(q.get('foo', 'not available'), 'hello')
        self.assertEqual(q.getlist('foo'), ['bar', 'baz', 'another', 'hello'])
        self.assertEqual(q.pop('foo'), ['bar', 'baz', 'another', 'hello'])
        self.assertEqual(q.pop('foo', 'not there'), 'not there')
        self.assertEqual(q.get('foo', 'not there'), 'not there')
        self.assertEqual(q.setdefault('foo', 'bar'), 'bar')
        self.assertEqual(q['foo'], 'bar')
        self.assertEqual(q.getlist('foo'), ['bar'])
        self.assertIn(q.urlencode(),
                      ['foo=bar&name=john', 'name=john&foo=bar'])

        q.clear()
        self.assertEqual(len(q), 0)
Exemplo n.º 45
0
 def test_missing_key(self):
     q = QueryDict()
     with self.assertRaises(KeyError):
         q.__getitem__('foo')
Exemplo n.º 46
0
 def test_mutable_copy(self):
     """A copy of a QueryDict is mutable."""
     q = QueryDict(str('')).copy()
     self.assertRaises(KeyError, q.__getitem__, "foo")
     q['name'] = 'john'
     self.assertEqual(q['name'], 'john')
Exemplo n.º 47
0
 def test_fromkeys_noniterable(self):
     with self.assertRaises(TypeError):
         QueryDict.fromkeys(0)
Exemplo n.º 48
0
 def test_immutability(self):
     q = QueryDict()
     with self.assertRaises(AttributeError):
         q.__setitem__('something', 'bar')
     with self.assertRaises(AttributeError):
         q.setlist('foo', ['bar'])
     with self.assertRaises(AttributeError):
         q.appendlist('foo', ['bar'])
     with self.assertRaises(AttributeError):
         q.update({'foo': 'bar'})
     with self.assertRaises(AttributeError):
         q.pop('foo')
     with self.assertRaises(AttributeError):
         q.popitem()
     with self.assertRaises(AttributeError):
         q.clear()
Exemplo n.º 49
0
 def test_duplicates_in_fromkeys_iterable(self):
     self.assertEqual(QueryDict.fromkeys('xyzzy'), QueryDict('x&y&z&z&y'))
Exemplo n.º 50
0
 def test_create_with_no_args(self):
     self.assertEqual(QueryDict(), QueryDict(str('')))
Exemplo n.º 51
0
 def test_fromkeys_is_immutable_by_default(self):
     # Match behavior of __init__() which is also immutable by default.
     q = QueryDict.fromkeys(['key1', 'key2', 'key3'])
     with self.assertRaisesMessage(AttributeError,
                                   'This QueryDict instance is immutable'):
         q['key4'] = 'nope'
Exemplo n.º 52
0
 def test_fromkeys_empty_iterable(self):
     self.assertEqual(QueryDict.fromkeys([]), QueryDict(''))
Exemplo n.º 53
0
 def test_querydict_fromkeys(self):
     self.assertEqual(QueryDict.fromkeys(['key1', 'key2', 'key3']),
                      QueryDict('key1&key2&key3'))
Exemplo n.º 54
0
 def test_fromkeys_mutable_override(self):
     q = QueryDict.fromkeys(['key1', 'key2', 'key3'], mutable=True)
     q['key4'] = 'yep'
     self.assertEqual(q, QueryDict('key1&key2&key3&key4=yep'))
Exemplo n.º 55
0
 def test_mutable_delete(self):
     q = QueryDict(mutable=True)
     q['name'] = 'john'
     del q['name']
     self.assertNotIn('name', q)
Exemplo n.º 56
0
 def test_fromkeys_with_nonempty_value(self):
     self.assertEqual(
         QueryDict.fromkeys(['key1', 'key2', 'key3'], value='val'),
         QueryDict('key1=val&key2=val&key3=val'))
Exemplo n.º 57
0
def handleCourseRequests(request):

    hash_id = request.user.hash_id

    if request.method == "GET":
        data = {}

        # Propogate memories to return to frontend
        for courseRequest in CourseRequest.objects.filter(hash_id = hash_id):
            data[courseRequest.id] = {"courses": courseRequest.courses, "topPriority": courseRequest.topPriority, "sport": courseRequest.sport, "musicLesson": courseRequest.musicLesson, "comments": courseRequest.comments}

        # Return data to frontend
        return JsonResponse(data, status=200)

    if request.method == "POST":
        # Decode request body content
        content = QueryDict(request.body.decode('utf-8')).dict()

        # Determine a string representation of the term
        date = datetime.date()
        if 3 <= date.month <= 9:
            term = "Fall '" + str(date.year%100)
        elif 10 <= date.month <= 12:
            term = "Winter '" + str((date.year + 1)%100)
        else:
            term = "Spring '" + str(date.year%100)


        try:
            coursesString = content["courses"] # should be an array of the courses' IDs
            courses = []
            num = ""
            count = 0
            # parse string array, will look like "[[-1, 2, 3], [4, 5, 6]]"
            tempCourses = []
            for char in coursesString:
                if char == '[':
                    count += 1
                if char == ']':
                    courses.append(tempCourses)
                    tempCourses = []
                    count -= 1
                elif char.isdigit() or char == "-":
                    num += char
                elif char == ',' and count > 1:
                    tempCourses.append(int(num))
                    num = ""

            sixthCourse = int(content["sixthCourse"])
            topPriority = int(content["topPriority"])

            sport = content["sport"] # should be the sport's ID
            mL = content["musicLesson"] # should be a dict in the proper musiclesson format
            comments = content["comments"]
        except:
            return JsonResponse({'status':'false', 'message':"Unable to parse dictionary of params"}, status=401)

        try:
            musicLesson = MusicLession(instrument=mL["instrument"], teacher=mL["teacher"],length=mL["length"])
            musicLesson.save()
        except:
            musicLesson = -1
            return JsonResponse({'status':'false', 'message':"Unable to process music lesson"}, status=401)

        # Create a CourseRequest object and save its reference to access id
        try:
            courseRequest = CourseRequest(hash_id = hash_id, term = term, courses = courses, topPriority = topPriority, sport = sport, musicLesson = musicLesson.id, comments = comments)
            courseRequest.save()
        except:
            return JsonResponse({'status':'false', 'message':"Unable to save course request"}, status=401)

        returning = JsonResponse({'status':'true', 'message':"Your course request has been POSTed"}, status=200)
Exemplo n.º 58
0
    def test_multiple_keys(self):
        """Test QueryDict with two key/value pairs with same keys."""

        q = QueryDict(str('vote=yes&vote=no'))

        self.assertEqual(q['vote'], 'no')
        with self.assertRaises(AttributeError):
            q.__setitem__('something', 'bar')

        self.assertEqual(q.get('vote', 'default'), 'no')
        self.assertEqual(q.get('foo', 'default'), 'default')
        self.assertEqual(q.getlist('vote'), ['yes', 'no'])
        self.assertEqual(q.getlist('foo'), [])

        with self.assertRaises(AttributeError):
            q.setlist('foo', ['bar', 'baz'])
        with self.assertRaises(AttributeError):
            q.setlist('foo', ['bar', 'baz'])
        with self.assertRaises(AttributeError):
            q.appendlist('foo', ['bar'])

        if six.PY2:
            self.assertIs(q.has_key('vote'), True)
        self.assertIn('vote', q)
        if six.PY2:
            self.assertIs(q.has_key('foo'), False)
        self.assertNotIn('foo', q)
        self.assertEqual(list(six.iteritems(q)), [('vote', 'no')])
        self.assertEqual(list(six.iterlists(q)), [('vote', ['yes', 'no'])])
        self.assertEqual(list(six.iterkeys(q)), ['vote'])
        self.assertEqual(list(six.itervalues(q)), ['no'])
        self.assertEqual(len(q), 1)

        with self.assertRaises(AttributeError):
            q.update({'foo': 'bar'})
        with self.assertRaises(AttributeError):
            q.pop('foo')
        with self.assertRaises(AttributeError):
            q.popitem()
        with self.assertRaises(AttributeError):
            q.clear()
        with self.assertRaises(AttributeError):
            q.setdefault('foo', 'bar')
        with self.assertRaises(AttributeError):
            q.__delitem__('vote')
Exemplo n.º 59
0
 def response_dict(self):
     """
     Returns a (MultiValueDict) dictionary containing all the parameters returned in the PayPal response.
     """
     # Undo the urlencode done in init
     return QueryDict(self.response)
Exemplo n.º 60
0
def authenticate(request: WSGIRequest) -> HttpResponse:
    request.session["token"] = QueryDict(request.body).get("token")
    return HttpResponse(status=http.HTTPStatus.OK)