Ejemplo n.º 1
0
    def dispatch(self, request, *args, **kwargs):
        assert self.forward_group is not None, \
            'ForwardMixin subclasses need to set a forward_group.'

        if self.should_forward(request, *args, **kwargs):
            redirect_response = self.get_redirect_response(
                request, *args, **kwargs)

            if request.method == 'POST' and request.POST:
                redirect_response = self.create_forward(
                    request=request, response=redirect_response)

            return redirect_response

        forward_id = request.COOKIES.get('forward')
        if forward_id is not None:
            try:
                forward = Forward.objects.get(id=forward_id)
                forward_data = QueryDict('', mutable=True)
                forward_data.update(json.loads(forward.json))
                request.forward_data = forward_data
                Forward.objects.filter(
                    Q(created_at__gt=timezone.now() + timedelta(days=1))
                    | Q(pk=forward.pk)).delete()
            except Forward.DoesNotExist:
                pass

        return super().dispatch(request, *args, **kwargs)
Ejemplo n.º 2
0
    def get_feedback_filter_params(self):
        # We need to be careful here because some of the filter_form params
        # are for FRs not the nested Feedback. If we include those and then
        # we edit the FR in a way where it no longer matches the params we'll
        # get a 404 as we'll exclude ourself. Given that we only want to pass
        # along params that are for Feedback.
        params_to_exclude = (
            "search",
            "state",
            "theme",
            "priority",
            "effort",
            "shipped_start_date",
            "shipped_end_date",
            "shipped_date_range",
        )
        filter_dict = self.get_filter_form().data
        qd = QueryDict(mutable=True)
        qd.update(filter_dict)
        for param_name in params_to_exclude:
            if param_name in qd:
                qd.pop(param_name)

        # HACK: there is surely a better way but the form returns empty values
        # here as None but when we urlencode that we get 'None'. DateField
        # doesn't like 'None' b/c it's not a valid date. So... here we just
        # turn None into '' which the form is happy with.
        if qd.get("feedback_date_range", None) is None:
            qd["feedback_date_range"] = ""
        if qd.get("feedback_start_date", None) is None:
            qd["feedback_start_date"] = ""
        if qd.get("feedback_end_date", None) is None:
            qd["feedback_end_date"] = ""

        return qd
Ejemplo n.º 3
0
    def create(self, request):
        if request.method == 'POST':
            data = dict(request.data)
            #print(request.data)
            if len(data['calorie'][0]) == 0 or float(
                    data['calorie'][0]) == float(0):
                flag, val = nutritionnix_calorie_api(data['food_name'][0])
                if flag:
                    data['calorie'][0] = val
                else:
                    return Response(status=status.HTTP_400_BAD_REQUEST)

            query_dict = QueryDict('', mutable=True)
            query_dict.update(MultiValueDict(data))
            serializer = MealSerializer(data=query_dict)
            if serializer.is_valid():
                try:
                    user = UserProfile.objects.get(pk=self.request.user.id)
                    user.curr_calorie += float(data['calorie'][0])
                    if user.curr_calorie < user.max_calorie:
                        user.is_limit = False
                    else:
                        user.is_limit = True
                    user.save()
                except:
                    return Response(status=status.HTTP_404_NOT_FOUND)
                serializer.save(user_profile=self.request.user)
                return Response(serializer.data,
                                status=status.HTTP_201_CREATED)
            return Response(serializer.errors,
                            status=status.HTTP_400_BAD_REQUEST)
Ejemplo n.º 4
0
    def urlencode(self):
        """Return a URL encoded GET string"""

        def convert_date(date):
            """Get date into correct format"""
            if date is None:
                return ""
            else:
                return date.strftime("%m/%d/%Y")

        params = QueryDict("", mutable=True)
        min_pages = self.min_pages if self.min_pages is not None else ""
        min_date = convert_date(self.min_date)
        max_date = convert_date(self.max_date)
        params.update(
            {
                "q": self.query,
                "status": self.status,
                "has_embargo": self.embargo,
                "has_crowdfund": self.exclude_crowdfund,
                "minimum_pages": min_pages,
                "date_range_0": min_date,
                "date_range_1": max_date,
                "search_title": self.title,
            }
        )
        params.setlist("user", self.users.values_list("pk", flat=True))
        params.setlist("agency", self.agencies.values_list("pk", flat=True))
        params.setlist("projects", self.projects.values_list("pk", flat=True))
        params.setlist("tags", self.tags.values_list("pk", flat=True))
        params.setlist(
            "jurisdiction", [str(j) for j in self.searchjurisdiction_set.all()]
        )
        return params.urlencode()
 def get_form_kwargs(self):
     kwargs = super(RegistrationView, self).get_form_kwargs()
     self.ax = self.request.session['ax']
     if not self.ax:
         self.ax = RegistrationView.get_ax(self.request.POST)
     if self.ax:
         ax_data = {
                 'first_name' : self.ax['firstname'].split(maxsplit=1)[0] if 'firstname' in self.ax.keys() else None,
                 'last_name' : self.ax['lastname'] if 'lastname' in self.ax.keys() else None,
                 'gender' : self.ax['gender'] if 'gender' in self.ax.keys() else None,
                 'street' : self.ax['address'] if 'address' in self.ax.keys() else None,
                 'town' : self.ax['city'] if 'city' in self.ax.keys() else None,
                 'zip' : self.ax['postal_code'] if 'postal_code' in self.ax.keys() else None,
                 'birthday_day' : self.ax['birth_day'] if 'birth_day' in self.ax.keys() else None,
                 'birthday_month' : self.ax['birth_month'] if 'birth_month' in self.ax.keys() else None,
                 'birthday_year' : self.ax['birth_year'] if 'birth_year' in self.ax.keys() else None
         }
         data = QueryDict('', mutable=True)
         data.update(ax_data)
         if 'data' in kwargs.keys():
             data.update(kwargs['data'])
         kwargs['data'] = data
         kwargs.update({'eid' : True})
         self.eid = True
     else:
         kwargs.update({'eid' : False})
     self.request.session['ax'] = self.ax
     return kwargs
Ejemplo n.º 6
0
def index(request):
    if request.method == 'POST':
        vars = {k: request.POST[k].strip().lower() for k in ['material', 'item', 'transport', 'origin', 'destination']}
        post = QueryDict('', mutable=True)
        post.update(vars)
        return redirect('/qr?' + post.urlencode())
    return render(request, 'index.html', {'form': QRCodeRequestForm()})
Ejemplo n.º 7
0
def fill_form(get_new_package_name, get_new_tag_name, get_new_name):
    package_name = next(get_new_package_name)
    tag_name = next(get_new_tag_name)
    user1_name = next(get_new_name)
    user1 = User.objects.create_user(username=user1_name,
                                     password=G.default_password)
    user1.save()
    user2_name = next(get_new_name)
    user2 = User.objects.create_user(username=user2_name,
                                     password=G.default_password)
    user2.save()
    tag = Tag.objects.create(name=tag_name, owner_id=user2.id, owner=user2)
    tag.save()

    data = {
        'owner': [user1.id],
        'name': [package_name],
        'proficiency_value': ['1'],
        'proficiency_target': ['100'],
        'public': ['on'],
        'ref_url': ['https://www.djangoproject.com/'],
        'summary': ['<p>asdasd</p>'],
        'usage_notes': ['<p>To start server call: manage.py runserver</p>'],
        'tags': [tag.id],
        'resources': [],
        'codes': []
    }
    form_data = QueryDict('', mutable=True)
    form_data.update(MultiValueDict(data))
    return PackageForm(data=form_data, current_user=user1), tag.id, user1
Ejemplo n.º 8
0
    def urlencode(self):
        """Return a URL encoded GET string"""

        def convert_date(date):
            """Get date into correct format"""
            if date is None:
                return ''
            else:
                return date.strftime('%m/%d/%Y')

        params = QueryDict('', mutable=True)
        min_pages = self.min_pages if self.min_pages is not None else ''
        min_date = convert_date(self.min_date)
        max_date = convert_date(self.max_date)
        params.update({
            'q': self.query,
            'status': self.status,
            'has_embargo': self.embargo,
            'has_crowdfund': self.exclude_crowdfund,
            'minimum_pages': min_pages,
            'date_range_0': min_date,
            'date_range_1': max_date,
            'search_title': self.title,
        })
        params.setlist('user', self.users.values_list('pk', flat=True))
        params.setlist('agency', self.agencies.values_list('pk', flat=True))
        params.setlist('projects', self.projects.values_list('pk', flat=True))
        params.setlist('tags', self.tags.values_list('pk', flat=True))
        params.setlist(
            'jurisdiction',
            [unicode(j) for j in self.searchjurisdiction_set.all()],
        )
        return params.urlencode()
Ejemplo n.º 9
0
    def process_request(self, request):
        if 'application/json' in request.META['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():
                if isinstance(value, list):
                    # need to iterate through the list and upate
                    # 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
Ejemplo n.º 10
0
def get_task(request):
    msg, username = '', ''
    QueryDict_ask = QueryDict('', mutable=True)
    if request.method == 'POST':
        if 'username' in request.session:
            username = str(request.session['username'])
            request.POST._mutable = True  # need change to mutable
            QueryDict_ask = request.POST
            QueryDict_ask.update({'username': username})
            form = QuestionPostForm(QueryDict_ask, request.FILES)
        else:
            msg = '請先登入 login first please'
            print('login first')
            return render(request, 'forum/get_task.html', {'msg': msg})

        if form.is_valid():
            form = form.save()
            request_id = form.id
            form.save()
            # ch state from null to open, wait set default value
            query = QuestionPost.objects.filter(id=request_id)
            query.update(state='open')
            url = reverse('forum:detail_task',
                          kwargs={'question_url_id': request_id})
            return HttpResponseRedirect(url)
        else:
            print('is_valid() failed')
    else:
        print('provide form')
        form = QuestionPostForm()
    return render(request, 'forum/get_task.html', {'form': form})
Ejemplo n.º 11
0
def host_add(request):
    if not request.user.has_perm('cmdb.add_host'):
        raise PermissionDenied

    t = request.GET.get('t', '2')  # 资产类型ID
    active = 'cmdb_host_1_active' if t == '1' else 'cmdb_host_2_active'

    context = {active: 'active'}
    if request.method == 'POST':
        # import ipdb;ipdb.set_trace()
        newhost = QueryDict(mutable=True)
        newhost.update(request.POST)
        newhost.update({'asset_type': t})
        form = HostForm(newhost)
        if form.is_valid():
            form.save()
            ref_url = request.POST.get('ref_url', '/')
            return redirect(ref_url)
    else:
        form = HostForm()
        ref_url = request.META.get('HTTP_REFERER', '/')  # 来源URL,供POST成功后返回
        context.update({'ref_url': ref_url})

    context.update({'form': form})
    html = 'host_2.html'

    return render(request, html, context)
Ejemplo n.º 12
0
def auto_publish(request, category_id=3):
    with open("/home/david/htdocs/feedback_django/example/spirit/topic/json/O.json","r",encoding='UTF-8') as file:
        jsonContent = json.load(file)
        # print(jsonContent['course'][0])
        
        # <QueryDict: {'comment': ['f**k'], 'category': ['5'], 'csrfmiddlewaretoken': ['TrhHjnBCe5pAHjeSKGN4n3kbY3m7SvXh'], 'title': ['auto']}>
        jsondict = {'category': ['3'], 'comment': ['this is test'],
            'csrfmiddlewaretoken': ['TrhHjnBCe5pAHjeSKGN4n3kbY3m7SvXh'], 'title':  ['json works']}
        qdict = QueryDict('',mutable=True)
        qdict.update(jsondict)

    if category_id:
        get_object_or_404(Category.objects.visible(),
                          pk=category_id)

    form = TopicForm(user=request.user, data=qdict)
    cform = CommentForm(user=request.user, data=qdict)
    print(form)
    print(form.is_valid())
    print(cform.is_valid())
    if all([form.is_valid(), cform.is_valid()]):  # TODO: test!
        # wrap in transaction.atomic?
        topic = form.save()
        cform.topic = topic
        comment = cform.save()
        comment_posted(comment=comment, mentions=cform.mentions)
        return redirect(topic.get_absolute_url())

    context = {
        'form': form,
        'cform': cform
    }
    return render(request, 'spirit/topic/publish.html', context)
Ejemplo n.º 13
0
    def post(self, request, *args, **kwargs):
        try:
            images = request.FILES
            query_images = QueryDict("", mutable=True)
            query_images.update(images)
            images_list = query_images.getlist("photo")

            for photo in images_list:
                imgstr = base64.b64encode(photo.file.read())

                album = ImageAlbum.objects.get(id=request.data["album_id"])
                image = upload_image(imgstr, str(photo))
                imageCDN_obj = ImageCDN.objects.create(
                    album=album,
                    file_id=image["fileId"],
                    name=image["name"],
                    url=image["url"],
                    thumbnail=image["thumbnailUrl"],
                    file_type=image["fileType"])

            images_CDN = ImageCDN.objects.all().order_by(
                "id").reverse()[:len(images_list)]
            return Response(ImageCDNSerializer(reversed(images_CDN),
                                               many=True).data,
                            status=status.HTTP_201_CREATED)
        except:
            return Response(
                ImageCDNSerializer(status=status.HTTP_400_BAD_REQUEST))
Ejemplo n.º 14
0
 def test_ds_response_3(self):
     """
     Testing that it works with get data from an advanced search
     """
     get_dic = {
         'search_name': 'wha%',
         'search_pi': 'jame%',
         'from_date_year': '2015',
         'from_date_month': '11',
         'from_date_day': '19',
         'to_date_year': '2015',
         'to_date_month': '11',
         'to_date_day': '22',
     }
     response = self.client.get('/experimentsearch/data_source/What is up/',
                                get_dic)
     from_get = QueryDict(mutable=True)
     from_get.update(get_dic)
     self.assertEqual(QueryDict(query_string=response.context['from_dic']),
                      from_get)
     self.assertTemplateUsed(response, 'experimentsearch/datasource.html')
     expected_table = DataSourceTable(ds_table_set)
     actual_table = response.context['table']
     self.check_tables_equal(actual_table, expected_table,
                             DataSourceForTable)
Ejemplo n.º 15
0
def save_quick_search(request):
    search_name = request.POST.get('search_name', '')
    user_search = {}
    search_filters = {
        'name', 'product_business', 'business_area', 'analytic_focus',
        'provider_focus', 'utilization_category'
    }
    filter_empty = True
    for item in search_filters:
        user_search[item] = list(request.POST.get(item, '').split(','))
        if request.POST.get(item, ''):
            filter_empty = False
    asset_list = AssetCatalog.objects.all()
    total_assets = asset_list.count()
    query_dict = QueryDict('', mutable=True)
    query_dict.update(MultiValueDict(user_search))
    asset_filter = AssetFilter(query_dict, queryset=asset_list)

    if not search_name:
        messages.warning(
            request,
            'Saving QUICK SEARCH: Please, provide a name for this quick search!'
        )

    elif filter_empty:
        messages.warning(
            request,
            'Saving QUICK SEARCH: Please, add some filter to this quick search!'
        )

    else:

        previous_search = AssetUserSearch.objects.filter(
            name=search_name, user=request.user.profile)
        if previous_search.exists():
            messages.warning(
                request,
                'Saving QUICK SEARCH: You already have a saved search using this name.'
            )
        else:
            search_text = json.dumps(user_search)
            new_search = AssetUserSearch.objects.create(
                name=search_name,
                user=request.user.profile,
                search_criteria=search_text)
            if new_search:
                print('Done')
                messages.success(
                    request,
                    'Saving QUICK SEARCH: Your search was saved successfully!')

    return render(
        request, 'asset_mgmt/asset.html', {
            'filter': asset_filter,
            'product_name': request.POST.get('tag_search', ''),
            'type_asset': '',
            'total': total_assets,
            'messages': 'OK'
        })
Ejemplo n.º 16
0
 def get_url(self, viewname, arguments=None, query_args=None):
     arguments = arguments or {}
     query_args = query_args or {}
     query_dict = QueryDict(mutable=True)
     query_dict.update(**query_args)
     return '{url}?{query}'.format(url=reverse(viewname=viewname,
                                               kwargs=arguments),
                                   query=query_dict.urlencode())
Ejemplo n.º 17
0
 def get_contributions_url(self, obj):
     if not obj.contributions:
         # don't add anything when it's not set.
         return obj.contributions
     parts = urlsplit(obj.contributions)
     query = QueryDict(parts.query, mutable=True)
     query.update(amo.CONTRIBUTE_UTM_PARAMS)
     return urlunsplit((parts.scheme, parts.netloc, parts.path,
                        query.urlencode(), parts.fragment))
Ejemplo n.º 18
0
 def test_filter_query_string(self):
     """
     Test the filter query string definition.
     """
     test_dict = {'test': '1'}
     query_dict = QueryDict('', mutable=True)
     query_dict.update(test_dict)
     new_query_string = filter_query_string(query_dict)
     self.assertEqual(new_query_string, '&test=1')
Ejemplo n.º 19
0
 def test_filter_query_string(self):
     """
     Test the filter query string definition.
     """
     test_dict = {'test': '1'}
     query_dict = QueryDict('', mutable=True)
     query_dict.update(test_dict)
     new_query_string = filter_query_string(query_dict)
     self.assertEqual(new_query_string, '&test=1')
Ejemplo n.º 20
0
 def format_filter(self, obj):
     qd = QueryDict(mutable=True)
     filter_fields = self.filter.keys()
     for field_name in filter_fields:
         qd.update({
             '[{}]'.format(field_name):
             self.lookup_attribute(obj, self.filter[field_name])
         })
     return qd.urlencode(safe=['[', ']'])
Ejemplo n.º 21
0
def encode_query(querydict):
    """
    Encode a querydict as form params, using '+'' for ' '.
    """
    if not isinstance(querydict, QueryDict):
        temp = querydict
        querydict = QueryDict('', mutable=True)
        querydict.update(temp)
    return querydict.urlencode(': ').replace(' ', '+')
Ejemplo n.º 22
0
def query_string_from_dict(qs_dict):
    qs_prepared_dict = OrderedDict()
    for key, val in qs_dict.items():
        if isinstance(val, list):
            val = '[%s]' % ','.join([force_text(v) for v in val])
        qs_prepared_dict[key] = val

    qdict = QueryDict('').copy()
    qdict.update(qs_prepared_dict)
    return qdict.urlencode()
Ejemplo n.º 23
0
 def render_text(self):
     soup = BeautifulSoup(self.text, 'html.parser')
     for a in soup.find_all('a'):
         if 'href' in a.attrs:
             querydict = QueryDict(mutable=True)
             querydict.update(notification=self.id, url=a['href'])
             wrapped_url = '%s?%s' % (reverse('notification_link_click'),
                                      querydict.urlencode())
             a['href'] = wrapped_url
     return unicode(soup)
Ejemplo n.º 24
0
def query_string_from_dict(qs_dict):
    qs_prepared_dict = OrderedDict()
    for key, val in qs_dict.items():
        if isinstance(val, list):
            val = '[%s]' % ','.join([force_text(v) for v in val])
        qs_prepared_dict[key] = val

    qdict = QueryDict('').copy()
    qdict.update(qs_prepared_dict)
    return qdict.urlencode()
Ejemplo n.º 25
0
    def dispatch(self, request, *args, **kwargs):

        list_filter = None
        list_slug = kwargs.get('listslug', None)
        if list_slug:
            list_filter = {
                'slug': list_slug,
                'group__slug': kwargs.get('group'),
                'group__portal': CosinnusPortal.get_current()
            }
        elif request.method == 'GET':
            # if we navigate to the index, redirect to the default todolist instead, if it exists
            default_todolist_slug = settings.COSINNUS_TODO_DEFAULT_TODOLIST_SLUG
            default_list_filter = {
                'slug': default_todolist_slug,
                'group__slug': kwargs.get('group'),
                'group__portal': CosinnusPortal.get_current()
            }
            default_todolist = get_object_or_None(TodoList,
                                                  **default_list_filter)
            if default_todolist:
                return redirect(
                    group_aware_reverse('cosinnus:todo:list-list',
                                        kwargs={
                                            'group': kwargs.get('group'),
                                            'listslug': default_todolist.slug
                                        }))

        if list_filter:
            self.todolist = get_object_or_404(TodoList, **list_filter)
        else:
            self.todolist = None

        todo_slug = kwargs.get('todoslug', None)
        if todo_slug:
            self.todo = get_object_or_404(
                TodoEntry,
                slug=todo_slug,
                group__slug=kwargs.get('group'),
                group__portal=CosinnusPortal.get_current())
        else:
            self.todo = None

        # default filter for todos is completed=False
        if not 'is_completed' in request.GET:
            qdict = QueryDict('', mutable=True)
            qdict.update(request.GET)
            qdict.update(
                {'is_completed': 0}
            )  # set this to '0' instead of 0 to show the "active filter" bubble
            request.GET = qdict

        ret = super(TodoListCreateView, self).dispatch(request, *args,
                                                       **kwargs)
        return ret
Ejemplo n.º 26
0
def generate_link(search_param_parser, offset_prediction):
    """
    Generate next/previous URL links

    Args:
        search_param_parser(SearchParamParser): Parsed Request Search Object
        offset_prediction: offset prediction number

    Returns:
        URL for next/previous links (string)
    """
    query_temp = QueryDict(mutable=True)
    query_temp.update({'search': search_param_parser.search_string})
    query_temp.update({'offset': offset_prediction})
    query_temp.update({'limit':
                       search_param_parser.limit})  # Limit stays the same

    [
        query_temp.update({'category': current_category})
        for current_category in search_param_parser.categories
    ]
    [
        query_temp.update({'agency': current_category})
        for current_category in search_param_parser.agencies
    ]
    [
        query_temp.update({'type': current_category})
        for current_category in search_param_parser.listing_types
    ]

    return '{!s}/api/listings/essearch/?{!s}'.format(
        search_param_parser.base_url, query_temp.urlencode())
Ejemplo n.º 27
0
def create_campaigns_through_csv(csvfile):
    message = ''
    columns = 3
    Campaigns_list = []
    errors = []
    for index, line in enumerate(csv.reader(csvfile)):
        if len(line) != columns:
            return 'Incorrect columns structure. It must contains 3 columns and be in profile_id , notes, name format.'
        customer, notes, name = line
        campaign = {}
        campaign['name'] = name
        campaign['notes'] = notes
        campaign['customer'] = customer

        if campaign['customer']:
            if not Profile.objects.filter(id=campaign['customer']).exists():
                return 'Profile for Id: {} - wasn\'t found.\n' \
                    .format(
                    campaign['customer'])
            else:
                campaign['customer'] = Profile.objects.get(
                    id=campaign['customer'])
        else:
            return 'Please provide profile id.'

        data = QueryDict('', mutable=True)
        data.update(campaign)
        form = CampaignsAddForm(data)

        if not form.is_valid():
            errors.append(
                'Row: {} Followed errors has been found in file: {}\n'.format(
                    index + 1,
                    ', '.join('{}: {}'.format(field, ', '.join(error))
                              for field, error in form.errors.iteritems())))
        else:
            campaign['name'] = form.cleaned_data['name']
            campaign['notes'] = form.cleaned_data['notes']

            Campaigns_list.append(campaign)

    if errors:
        return '\n'.join(errors)

    for camp in Campaigns_list:
        message += 'Creating Campaign for {}... \n'.format(camp['name'])

        Campaigns.objects.create(customer=camp['customer'],
                                 name=camp['name'],
                                 notes=camp['notes'])
        message += 'Created Campaign: {} successfully\n'.format(camp['name'])
        message += '==================================================\n'

    return message
Ejemplo n.º 28
0
 def filter_queryset(self, queryset):
     """Given a queryset, filter it, returning a new queryset."""
     keys = self.request.DESCRIPTOR.fields_by_name.keys()
     request = HttpRequest()
     query_params = QueryDict('', mutable=True)
     query_params.update(
         MessageToDict(self.request, preserving_proto_field_name=True))
     request.query_params = query_params
     for backend in list(self.filter_backends):
         queryset = backend().filter_queryset(request, queryset, self)
     return queryset
Ejemplo n.º 29
0
def on_user_logged_out(sender, request, user, **kwargs):
    if not settings.AUTH_OPENID:
        return
    if not settings.AUTH_OPENID_SHARE_SESSION:
        return
    query = QueryDict('', mutable=True)
    query.update({'redirect_uri': settings.BASE_SITE_URL})
    client = new_client()
    openid_logout_url = "%s?%s" % (client.get_url_end_session_endpoint(),
                                   query.urlencode())
    request.COOKIES['next'] = openid_logout_url
Ejemplo n.º 30
0
def _setupRequestData(value_dict):
    if len(value_dict) == 0:
        return QueryDict()
    qd = QueryDict(mutable=True)
    for key in value_dict.keys():
        val = value_dict[key]
        if type(val) == list:
            for item in val:
                qd.update({key: item})
        else:
            qd.update({key: val})
    return qd
Ejemplo n.º 31
0
    def post(self, req, *args, **kwargs):
        print("test_ini")

        # get requested data
        new_data = req.data.dict()

        # requested file object
        file_name = req.data['file_name']
        date = req.data['date']

        # create full path for saving file
        new_file_full_name = file_upload_path(file_name.name)

        # new file path
        file_path = '/'.join(new_file_full_name.split('/')[0:-1])

        # file extension
        file_ext = os.path.splitext(file_name.name)[1]

        # add new data to QueryDict(for mapping with DB)
        new_data['file_ext'] = file_ext
        new_data['is_img'] = is_image(file_ext)
        new_data['file_path'] = file_path
        new_data['file_origin_name'] = req.data['file_name'].name
        new_data['file_save_name'] = req.data['file_name']

        new_query_dict = QueryDict('', mutable=True)
        new_query_dict.update(new_data)

        celery_scan = CeleryScan(json_results='', is_complete=False)
        celery_scan.save()
        id_no = celery_scan.id_key

        file_serializer = FileSerializer(data=new_query_dict)
        print("test1")
        if file_serializer.is_valid():
            print("test2")
            file_serializer.save()
            print("save complete")
            print(file_serializer.data)

            # create the object so scan can be applied
            result = scan_code_async.delay(
                file_serializer.data['file_save_name'], date, id_no)

            # return the response as HttpResponse
            url = 'loaclhost:8000/taejo_api_result/' + str(id_no)
            return Response({"url": url}, status=status.HTTP_200_OK)
        else:

            log_util.error(__name__, file_serializer.errors)
            return Response(file_serializer.errors,
                            status=status.HTTP_400_BAD_REQUEST)
Ejemplo n.º 32
0
    def send(self, url, message_data, **kwargs):
        qs = QueryDict(mutable=True)
        qs.update(message_data)

        r = urllib.request.urlopen(urllib.request.Request(
            url,
            qs.urlencode().encode('utf-8'),
        ))

        result = r.read().decode('utf-8')

        return self.validate(r.headers['content-type'], result, message_data)
Ejemplo n.º 33
0
 def setUp(self):
     ProgrammeType.objects.create(display_name="Design",
                                  description="Some description text",
                                  id=1)
     query = QueryDict(mutable=True)
     query.update({
         "CompanyID": "ROYALC9RCH",
         "courseIDs": 1,
         "venueIDs": "",
         "categoryIDs": "",
     })
     self.query = query.urlencode()
Ejemplo n.º 34
0
    def __init__(self, *args, **kwargs):
        super(AutoManagementFormMixin, self).__init__(*args, **kwargs)

        if self.is_bound:
            if isinstance(self.data, MergeDict):
                data = QueryDict(None, mutable=True)
                for d in self.data.dicts:
                    data._encoding = d._encoding
                    data.update(d)
                self.data = data  # Make data mutable
            elif not getattr(self.data, '_mutable', True):
                self.data = self.data.copy()  # Make data mutable
Ejemplo n.º 35
0
    def send(self, url, message_data, **kwargs):
        qs = QueryDict(mutable=True)
        qs.update(message_data)

        r = urllib.request.urlopen(urllib.request.Request(
            url,
            qs.urlencode().encode('utf-8'),
        ))

        result = r.read().decode('utf-8')

        return self.validate(r.headers['content-type'], result, message_data)
Ejemplo n.º 36
0
 def query_params(self):
     orignal_params = super(BlendedRequest, self).query_params
     if self._params_prefix:
         params = QueryDict(mutable=True)
         params.update({k[len(self._params_prefix):]: v for k, v in orignal_params.items() if k.startswith(self._params_prefix)})
     else:
         params = super(BlendedRequest, self).query_params
     for m_k, m_v in  self._mapped_params.items():
         for o_k, o_v in orignal_params.items():
             matches = re.match(m_v, o_k)
             if matches:
                 params[''.join([m_k, (matches.group(1) if matches.lastindex >= 1 else '')])] = o_v
     return params
Ejemplo n.º 37
0
    def post(self, request):
        data = {**request.data}
        data.update({'user': [request.user.id]})

        query_dict = QueryDict('', mutable=True)
        query_dict.update(MultiValueDict(data))

        serializer = serializers.PlantSerializer(data=query_dict)

        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data, status=status.HTTP_201_CREATED)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
Ejemplo n.º 38
0
    def test_chain_setup_saves_chains_correctly(self):
        request = HttpRequest()
        request.method = 'POST'
        request.session = self.engine.SessionStore(None)
        request.session['pdb_id'] = '1SC1'
        request.session['all_chains'] = ['A', 'B']
        _dict = {'chains' : 'A'}
        _qdict = QueryDict('', mutable=True)
        _qdict.update(_dict)
        request.POST = _qdict

        response = chain_setup(request)
        self.assertEqual(request.session.get('included_chains'), ['A'])
        self.assertEqual(request.session.get('removed_chains'), ['B'])
Ejemplo n.º 39
0
    def render(self, context):
        request = context['request']

        # Make request.GET mutable.
        # request.GET = dict(request.GET)

        if self.var_name in request.GET:
            return ''
        else:
        	mydict = {self.var_name : 1}
        	qdict = QueryDict('')
        	qdict = request.GET.copy()
        	qdict.update(mydict)
        	request.GET = qdict
        	# request.GET[self.var_name] = 1
        	return self.nodelist.render(context)
Ejemplo n.º 40
0
def on_user_logged_out(sender, request, user, **kwargs):
    if not settings.AUTH_OPENID:
        return

    query = QueryDict('', mutable=True)
    query.update({
        'redirect_uri': settings.BASE_SITE_URL
    })

    openid_logout_url = "%s?%s" % (
        client.openid_connect_client.get_url(
            name='end_session_endpoint'),
        query.urlencode()
    )

    request.COOKIES['next'] = openid_logout_url
Ejemplo n.º 41
0
    def test_source_setup_stores_source_residues_to_session_variable(self):
        request = HttpRequest()
        request.method = 'POST'
        request.session = self.engine.SessionStore(None)
        request.session['pdb_id'] = '1SC1'
        request.session['chains'] = ['A', 'B']
        request.session['hetatms'] = [('PHQ', 'C', '1'), ('CF0', 'C', '5')]
        request.session['residue_list'] = [('125', 'A'), ('126', 'A')]
        
        _dict = {'residues' : '0'}
        _qdict = QueryDict('', mutable=True)
        _qdict.update(_dict)
        request.POST = _qdict

        response = source_setup(request)

        self.assertEqual(request.session.get('source_residues')[0], ('125', 'A'))
Ejemplo n.º 42
0
 def format_filter(self, obj):
     qd = QueryDict(mutable=True)
     filter_fields = self.filter.keys()
     for field_name in filter_fields:
         try:
             # check if serializer method passed in
             serializer_method = getattr(self.parent, self.filter[field_name])
         except AttributeError:
             value = self.lookup_attribute(obj, self.filter[field_name])
         else:
             value = serializer_method(obj)
         if not value:
             continue
         qd.update({'[{}]'.format(field_name): value})
     if not qd.keys():
         return None
     return qd.urlencode(safe=['[', ']'])
Ejemplo n.º 43
0
    def test_hetatm_setup_saves_included_ligands_correctly(self):
        request = HttpRequest()
        request.method = 'POST'
        request.session = self.engine.SessionStore(None)
        request.session['pdb_id'] = '2HBQ'
        request.session['included_chains'] = ['A', 'B', 'C']
        request.session['removed_chains'] = []
        request.session['hetatms'] = [('PHQ', 'C', '1'), ('CF0', 'C', '5')]

        _dict = {'hetatms' : '0'}
        _qdict = QueryDict('', mutable=True)
        _qdict.update(_dict)
        request.POST = _qdict

        response = hetatm_setup(request)

        self.assertIn(['1', 'C'], request.session.get('included_hetatms'))
Ejemplo n.º 44
0
 def merge_defaults(self):
     if self.use_defaults:
         data = QueryDict('', mutable=True)
         if self.data:
             data.update(self.data)
         initial = self.initial_data
         for key in initial:
             if key in data:
                 continue
             value = initial[key]
             name = self.add_prefix(key)
             if value is not None:
                 if isinstance(value, (list, tuple)):
                     data.setlistdefault(name, value)
                 else:
                     data.setdefault(name, value)
         self.data = data
Ejemplo n.º 45
0
    def __init__(self, *args, **kwargs):
        newPosts = QueryDict("", True)
        if len(args) > 0:
            posts = dict(args[0].items())

            if posts["dlDate"] and posts["dlHour"] and posts["dlMin"]:
                posts["deadline"] = self.getDeadline(posts["dlDate"], posts["dlHour"], posts["dlMin"])

            if posts["terms"]:
                posts["term"] = posts["terms"]

            posts["identifier"] = self.randStr(20)

            newPosts.update(posts)
            super(EventForm, self).__init__((newPosts))
        else:
            super(EventForm, self).__init__(*args, **kwargs)
Ejemplo n.º 46
0
 def read_raw_data(self, request):
     # convert the data into the correct format and add
     # it as POST variables.
     from django.http.request import QueryDict, MultiValueDict
     if not request.method in ['POST', 'PUT']:
         request._post, request._files = QueryDict('', encoding=request._encoding), MultiValueDict()
     else:
         # TODO multipart (files) not supported.
         q = QueryDict('', encoding=request._encoding).copy()
         d = self._raw_data_to_dict(request)
         for key in d.keys():
             if isinstance(d[key], list):
                 q.setlist(key, d.pop(key))
         q.update(d)
         request.method = 'POST'
         request._post = q
         request._files = MultiValueDict()
Ejemplo n.º 47
0
    def test_hetatm_setup_POST_redirects_to_source_setup(self):
        request = HttpRequest()
        request.method = 'POST'
        request.session = self.engine.SessionStore(None)
        request.session['pdb_id'] = '2HBQ'
        request.session['included_chains'] = ['A', 'B', 'C']
        request.session['hetatms'] = [('PHQ', 'C', '1'), ('CF0', 'C', '5')]
        request.session['removed_chains'] = []
        
        _dict = {'hetatms' : '0'}
        _qdict = QueryDict('', mutable=True)
        _qdict.update(_dict)
        request.POST = _qdict

        response = hetatm_setup(request)

        self.assertEqual(response.status_code, 302)
        self.assertEqual(response['location'], '/source')
Ejemplo n.º 48
0
 def test_value_from_datadict(self):
     formset = formset_factory(ContactsForm)
     widget = widgets.ContactsWidget(attrs={'formset': formset})
     data = {
         'contacts-TOTAL_FORMS': '2',
         'contacts-INITIAL_FORMS': '1',
         'contacts-MAX_NUM_FORMS': '0',
         'contacts-MAX_NUM_FORMS': '1000',
         'contacts-0-name': 'Ringo',
         'contacts-0-email': '*****@*****.**',
         'contacts-0-tel': '555-555',
         'contacts-1-name': '',
         'contacts-1-email': '',
         'contacts-1-tel': ''
     }
     q_dict = QueryDict('', mutable=True)
     q_dict.update(data)
     value = widget.value_from_datadict(q_dict, {}, 'contacts')
     assert isinstance(value, formset)
Ejemplo n.º 49
0
 def test_ds_response_3(self):
     """
     Testing that it works with get data from an advanced search
     """
     get_dic = {
         'search_name': 'wha%', 'search_pi': 'jame%', 'from_date_year': '2015',
         'from_date_month': '11', 'from_date_day': '19',
         'to_date_year': '2015', 'to_date_month': '11', 'to_date_day': '22',
     }
     response = self.client.get(
         '/experimentsearch/data_source/What is up/', get_dic
     )
     from_get = QueryDict(mutable=True)
     from_get.update(get_dic)
     self.assertEqual(QueryDict(query_string=response.context['from_dic']), from_get)
     self.assertTemplateUsed(response, 'experimentsearch/datasource.html')
     expected_table = DataSourceTable(ds_table_set)
     actual_table = response.context['table']
     self.check_tables_equal(actual_table, expected_table, DataSourceForTable)
Ejemplo n.º 50
0
    def test_source_redirects_to_results(self):
        request = HttpRequest()
        request.method = 'POST'
        request.session = self.engine.SessionStore(None)
        request.session['pdb_id'] = '1SC1'
        request.session['included_chains'] = ['A', 'B']
        request.session['removed_chains'] = ['A']
        request.session['hetatms'] = [('PHQ', 'C', '1'), ('CF0', 'C', '5')]
        request.session['residue_list'] = [('125', 'A'), ('126', 'A')]
        
        _dict = {'residues' : '0'}
        _qdict = QueryDict('', mutable=True)
        _qdict.update(_dict)
        request.POST = _qdict

        response = source_setup(request)

        self.assertEqual(response.status_code, 302)
        self.assertEqual(response['location'], '/results')
Ejemplo n.º 51
0
    def post(self, request, *args, **kwargs):
        from django.http.request import QueryDict

        form_class = self.get_form_class()

        # Recibe la peticion enviada por POST
        # y actualiza agregando los campos por defecto basados en la vista

        data = QueryDict.dict(request.POST)
        data.update(**self.get_default_fields())

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

        form = form_class(qdict)

        if form.is_valid():
            return self.form_valid(form)
        else:
            return self.form_invalid(form)
Ejemplo n.º 52
0
def plugin_caller(specs, query):
    p = compile("(^.+?)_.*$") # Add '?' to prevent greedy matching
    unique_plugins = set(str(p.match(s).groups(0)[0]) for s in query.keys() if p.match(s))
    
    plugin_funcs = JSCommand.get_functions()
    for p in unique_plugins:
        # print("plugin: ", p,plugins.base.plugin_funcs.keys())
        if plugin_funcs.has_key(p):
            start=len(p+"_")
            params = {k[start:]:v for (k,v) in query.items() if k.startswith(p+"_") and len(k) > start}
            query_params = QueryDict('', mutable=True)
            query_params.update({k:v for (k,v) in query.items() if k.startswith(p+"_")})
            params['query_params'] = query_params.urlencode()
            specs = plugin_funcs[p](specs, params)
            #print(plugin_funcs[p].__name__)
            #import pdb; pdb.set_trace()
        
        else:
            raise exceptions.PluginNotFoundError('Can\'t find plugin %s' %p)
    return specs
Ejemplo n.º 53
0
 def get_data(self):
     if '@disable_auto_data' in self._data:
         return self._data
     if not hasattr(self, '_data_'):
         self._data_ = self._data
         if isinstance(self._data, MergeDict):
             data = QueryDict(None, mutable=True)
             for d in self._data.dicts:
                 data._encoding = d._encoding
                 data.update(d)
             self._data = data  # Make data mutable
         elif not getattr(self._data, '_mutable', True):
             self._data_ = self._data.copy()  # Make data mutable
         for name, field in self.fields.items():
             initial_value = None
             prefixed_name = self.add_prefix(name)
             data_value = field.widget.value_from_datadict(self._data_, self.files, prefixed_name)
             if data_value is None:
                 if not field.show_hidden_initial:
                     initial_value = self.initial.get(name, field.initial)
                     if callable(initial_value):
                         initial_value = initial_value()
                 else:
                     initial_prefixed_name = self.add_initial_prefix(name)
                     hidden_widget = field.hidden_widget()
                     try:
                         initial_value = field.to_python(hidden_widget.value_from_datadict(
                             self.data, self.files, initial_prefixed_name))
                     except ValidationError:
                         # Always assume data has changed if validation fails.
                         self._changed_data.append(name)
                         continue
                 if callable(initial_value):
                     initial_value = initial_value()
                 if initial_value is not None:
                     self._data_[prefixed_name] = initial_value
     return self._data_
Ejemplo n.º 54
0
def generate_link(search_param_parser, offset_prediction):
    """
    Generate next/previous URL links

    Args:
        search_param_parser(SearchParamParser): Parsed Request Search Object
        offset_prediction: offset prediction number

    Returns:
        URL for next/previous links (string)
    """
    query_temp = QueryDict(mutable=True)
    query_temp.update({'search': search_param_parser.search_string})
    query_temp.update({'offset': offset_prediction})
    query_temp.update({'limit': search_param_parser.limit})  # Limit stays the same

    [query_temp.update({'category': current_category}) for current_category in search_param_parser.categories]
    [query_temp.update({'agency': current_category}) for current_category in search_param_parser.agencies]
    [query_temp.update({'type': current_category}) for current_category in search_param_parser.listing_types]

    return '{!s}/api/listings/essearch/?{!s}'.format(search_param_parser.base_url, query_temp.urlencode())
Ejemplo n.º 55
0
def query_string_from_dict(qs_dict):
    qdict = QueryDict('').copy()
    qdict.update(qs_dict)
    return qdict.urlencode()
Ejemplo n.º 56
0
    def __init__(self, *args, **kwargs):
        user = kwargs.pop('user')
        super(CreateJobForm, self).__init__(*args, **kwargs)

        # Request details fieldset
        branchList = []
        for branch in user.branch.all():
            branchList.append((branch.name, branch.name))
        branchAmount = len(branchList)
        self.fields['branches'] = forms.ChoiceField(
            widget=forms.RadioSelect,
            choices=tuple(branchList),
        )
        if branchAmount == 1:
            data = QueryDict('', mutable=True)
            data.update(self.data)
            data['branches'] = branchList[0][0]
            self.data = data
            self.fields['branches'].widget.attrs = {'disabled' : 'true', 'checked' : 'true'}
        self.fields['title'].widget.attrs = {'autofocus':'true', 'id':'job_title', 'placeholder':_('Request title')}
        self.fields['date'].required = False
        self.fields['start_time'] = forms.TimeField(
            widget=forms.TimeInput(
                attrs={'placeholder' : 'Format: 00:00'},
            ),
            label=_('Start time'),
        )
        self.fields['duration'] = forms.TimeField(
            widget=forms.TimeInput(
                attrs={'placeholder' : 'Format: 00:00'},
            ),
            label=_('Duration'),
        )
        self.fields['km'] = forms.DecimalField(
            min_value=0,
            initial=0,
            label=_('Distance to be covered (approximation)'),
            max_digits=4,
        )

        # Job category fieldset
        self.fields['category'] = forms.ChoiceField(
            widget=forms.RadioSelect,
            choices=Job.CAT
        )
        # self.fields['other'] = forms.CharField(
        #     required=False,
        #     widget=TextInput(
        #         attrs={'placeholder':'Other'}    #TODO disabled
        #     )
        # )

        # Job timeline fieldset
        self.fields['frequency'] = forms.ChoiceField(
            widget=forms.RadioSelect,
            choices=Job.FREQ
        )
        self.fields['dayrange'] = forms.MultipleChoiceField(
            required=False,
            widget=forms.CheckboxSelectMultiple,
            choices=((x,x) for x in range(1,32))
        )

        # Job visibility fieldset
        self.fields['visibility'] = forms.MultipleChoiceField(
            widget=forms.CheckboxSelectMultiple,
            choices=Job.JOB_VISIBILITY_TUPLE
        )
Ejemplo n.º 57
0
 def format_filter(self, obj):
     qd = QueryDict(mutable=True)
     filter_fields = self.filter.keys()
     for field_name in filter_fields:
         qd.update({'[{}]'.format(field_name): self.lookup_attribute(obj, self.filter[field_name])})
     return qd.urlencode(safe=['[', ']'])
Ejemplo n.º 58
0
def YATSSearch(request):
    def ValuesQuerySetToDict(vqs):
        return [item for item in vqs]

    tic = get_ticket_model().objects.select_related('type', 'state', 'assigned', 'priority', 'customer').all()
    data = json.loads(request.body)

    if 'extra_filter' in data:
        extra_filter = data['extra_filter']
        del data['extra_filter']
    else:
        extra_filter = None
    if 'days' in data:
        days = data['days']
        del data['days']
    else:
        days = None
    if 'exclude_own' in data:
        exclude_own = data['exclude_own']
        del data['exclude_own']
    else:
        exclude_own = False

    POST = QueryDict(mutable=True)
    POST.update(data)
    form = SearchForm(POST, include_list=settings.TICKET_SEARCH_FIELDS, is_stuff=request.user.is_staff, user=request.user, customer=request.organisation.id)
    form.is_valid()
    for err in form._errors:
        field = form.fields[err]
        # b = type(field)
        if err in ['c_user', 'assigned']:
            try:
                form.cleaned_data[err] = field.choices.queryset.get(username=data[err]).pk
            except:
                form.cleaned_data[err] = -1

        else:
            try:
                form.cleaned_data[err] = field.choices.queryset.get(name=data[err]).pk
            except:
                form.cleaned_data[err] = -1

    search_params, base_query = build_ticket_search(request, tic, {}, clean_search_values(form.cleaned_data))
    if extra_filter:
        if extra_filter == '1':  # days since closed
            base_query = base_query.filter(close_date__gte=datetime.date.today() - datetime.timedelta(days=days)).exclude(close_date=None)
        if extra_filter == '2':  # days since created
            base_query = base_query.filter(c_date__gte=datetime.date.today() - datetime.timedelta(days=days))
        if extra_filter == '3':  # days since last changed
            base_query = base_query.filter(u_date__gte=datetime.date.today() - datetime.timedelta(days=days))
        if extra_filter == '4':  # days since last action
            base_query = base_query.filter(last_action_date__gte=datetime.date.today() - datetime.timedelta(days=days))
        if extra_filter == '5':  # days since falling due
            base_query = base_query.filter(deadline__lte=timezone.now() - datetime.timedelta(days=days)).filter(deadline__isnull=False)

    if exclude_own:
        base_query = base_query.exclude(assigned=request.user)

    seen = tickets_participants.objects.filter(user=request.user, ticket__in=base_query.values_list('id', flat=True)).values_list('ticket_id', 'seen')
    seen_elements = {}
    for see in seen:
        seen_elements[see[0]] = see[1]

    neededColumns = ['id', 'caption', 'c_date', 'type__name', 'state__name', 'assigned__username', 'deadline', 'closed', 'priority__color', 'customer__name', 'customer__hourly_rate', 'billing_estimated_time', 'close_date', 'last_action_date']
    """
    availableColumns = []
    tickets = get_ticket_model()
    t = tickets()
    for field in t._meta.fields:
        if field.name in neededColumns:
            availableColumns.append(field.name)
    """
    result = ValuesQuerySetToDict(base_query.values(*neededColumns))

    for ele in result:
        ele['seen'] = 0
        if ele['id'] in seen_elements:
            if seen_elements[ele['id']]:
                ele['seen'] = 2
            else:
                ele['seen'] = 1

    return result
Ejemplo n.º 59
0
def get_request_data(request):
    # simulate old request.REQUEST for backwards compatibility
    data = QueryDict(query_string=None, mutable=True)
    data.update(request.GET)
    data.update(request.POST)
    return data