def parse_request(request): if request.content_type.startswith('multipart/form-data'): if hasattr(request, '_body'): data = BytesIO(request._body) else: data = request try: return request.parse_file_upload(request.META, data) except MultiPartParserError: request._mark_post_parse_error() return elif request.content_type == 'application/x-www-form-urlencoded': return QueryDict(request.body, encoding=request._encoding, mutable=True), MultiValueDict() else: return QueryDict(encoding=request._encoding, mutable=True), MultiValueDict()
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
def _internal_service_call(self, share_data) : try: # internal : IMAGE print("■■■■■■■■■■ 이미지 분석 결과 분석 시작 ■■■■■■■■■■ ") temp = {} request_type = share_data.get_request_type() decode_text = base64.decodebytes(str.encode(share_data.get_request_data())) temp['test'] = [InMemoryUploadedFile(io.BytesIO(decode_text), None, 'test.jpg', 'image/jpeg', len(decode_text), None)] ml = MultiValueDict(temp) # fp = open("/hoya_src_root/nn00004/1/test1.jpg", 'wb') # fp.write(decode_text) # fp.close() # CNN Prediction if(request_type == "image"): return_val = PredictNetCnn().run('nn00004', None, ml ) name_tag = {"KYJ" : "김영재", "KSW" : "김승우", "LTY" : "이태영", "LSH" : "이상현", "PJH" : "백지현", "KSS" : "김수상", "PSC" : "박성찬"} print("■■■■■■■■■■ 이미지 분석 결과 분석 결과 : " + return_val['test.jpg']['key'][0]) share_data.set_output_data(name_tag[return_val['test.jpg']['key'][0]] + "인거 같은데 맞나요?") else : share_data.set_output_data("이미지 분석 결과가 없습니다") return share_data except Exception as e: raise Exception(e)
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)
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' })
def _load_post_and_files(request): """ Заполняет `request._post` и `request._files`. Работает с методами 'PUT', 'PATCH' и 'DELETE' и только если тип контента является данными формы. """ if request.method not in ('PUT', 'PATCH', 'DELETE'): return if request._read_started and not hasattr(request, '_body'): request._mark_post_parse_error() return update = bool(request.method != 'DELETE') if update and request.META.get('CONTENT_TYPE', '').startswith('multipart/form-data'): if hasattr(request, '_body'): # Use already read data data = BytesIO(request._body) else: data = request try: request._post, request._files = request.parse_file_upload( request.META, data) except MultiPartParserError: # An error occurred while parsing POST data. Since when # formatting the error the request handler might access # request.POST, set request._post and request._file to prevent # attempts to parse POST data again. # Mark that an error occurred. This allows request.__repr__ to # be explicit about it instead of simply representing an # empty POST request._mark_post_parse_error() raise elif request.META.get('CONTENT_TYPE', '').startswith('application/x-www-form-urlencoded'): request._post, request._files = QueryDict( request.body, encoding=request._encoding), MultiValueDict() else: request._post, request._files = QueryDict( '', encoding=request._encoding), MultiValueDict()
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)
def test_get_list_of_filters(self): """Test data from filter fields to convert to the list of integers""" data_from_filter = { "genres": list(map(str, self.faker.pylist(value_types=int))) } filter_query_dict = QueryDict("", mutable=True) filter_query_dict.update(MultiValueDict(data_from_filter)) genre_ids = views.get_list_of_filters("genres", filter_query_dict) for genre_id in genre_ids: self.assertIsInstance(genre_id, int) self.assertCountEqual(list(map(int, data_from_filter["genres"])), genre_ids)
def update(self, request, pk=None): try: snippet = Meal.objects.get(pk=pk) except Meal.DoesNotExist: return Response(status=status.HTTP_404_NOT_FOUND) if request.method == 'PUT': calorie = 0 if snippet.food_name == request.data['food_name'] and float( request.data['calorie']) != float(0): calorie = request.data['calorie'] serializer = MealSerializer(snippet, data=request.data) else: data = dict(request.data) # \ or float(snippet.calorie) == float(data['calorie'][0]) if not data['calorie'] 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) calorie = data['calorie'][0] query_dict = QueryDict('', mutable=True) query_dict.update(MultiValueDict(data)) serializer = MealSerializer(snippet, data=query_dict) if serializer.is_valid(): try: if request.user.is_superuser: user = UserProfile.objects.get( pk=snippet.user_profile.id) else: user = UserProfile.objects.get(pk=self.request.user.id) user.curr_calorie -= float(snippet.calorie) user.curr_calorie += float(calorie) 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() return Response(serializer.data) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
def test_view_helpers(self): dictionary = {'max': ['3'], 'type': ['download'], 'jurisdiction_name': ['alabama']} query_params = QueryDict('', mutable=True) query_params.update(MultiValueDict(dictionary)) formatted_params = view_helpers.format_query(query_params, dict()) """ assert type is removed """ assert 'type' not in formatted_params assert 'max' not in formatted_params queries = list(map(view_helpers.make_query, list(formatted_params.items()))) assert len(queries) == 1 first_q = queries[0] assert first_q.children[0][0] == 'jurisdiction__name__icontains'
def elements_list(request, filter_url=None): """ Try to make semantic url for filter. TODO make it DRY """ filter_data = {} if filter_url: for part in filter_url.split(';'): params = part.split('-is-') try: items = params[1].split('-or-') except: raise Http404("Url does not exist.") filter_data[params[0]] = items qdict = QueryDict('', mutable=True) qdict.update(MultiValueDict(filter_data)) element_qs = Elements.objects.all().order_by('-created', 'total') f = ElementsFilter(data=qdict or request.GET, queryset=element_qs) paginator = Paginator(f.qs, 17) page = request.GET.get('page') try: page = paginator.page(page) except PageNotAnInteger: page = paginator.page(1) except EmptyPage: page = paginator.page(paginator.num_pages) context = { 'filter': f, 'meta': Meta(**{'title': 'Records'}), 'paginator': paginator, 'page_obj': page, 'is_paginated': page.has_other_pages(), 'cache_key': f.qs._cache_key(), 'summary': get_summary_by_category(f.qs) } return render(request, 'main/elements_list_filter.html', context)
def get_set_post_request(post, edit=False): created, ids, key_errors = create_valid_keys(post.getlist('keys')) is_valid, added_keys = valid_roast(post.getlist('body')[0], ids) if is_valid or len(added_keys) == 0: roast_exists = 'f' if not is_valid and not edit: roast_exists = 't' new_post = { 'keys': ids, 'body': post.getlist('body'), 'csrfmiddlewaretoken': post.getlist('csrfmiddlewaretoken'), 'key_errors': key_errors, 'roast_exists': [roast_exists] } post_request = QueryDict('', mutable=True) post_request.update(MultiValueDict(new_post)) return post_request
def get_mvdict(data): return MultiValueDict(data)
def search(request, search_id=0): if not request.user.is_authenticated: return redirect(LOGIN_URL) query_dict = QueryDict('', mutable=True) if search_id and request.GET == query_dict: print(request.GET) search_text = AssetUserSearch.objects.get(pk=search_id).search_criteria search_user = json.loads(search_text) for key in list(search_user): if search_user[key] == [""]: del search_user[key] if 'name' in search_user: search_user['name'] = search_user['name'][0] asset_list = AssetCatalog.objects.all() tag_search = search_user.get('name', '') if tag_search: asset_list = asset_list.filter( Q(name__icontains=tag_search) | Q(description__icontains=tag_search) | Q(business_area__name__icontains=tag_search) | Q(product_business__name__icontains=tag_search) | Q(capability_business__name__icontains=tag_search)).distinct( ) type_asset = '' total_assets = asset_list.count() query_dict.update(MultiValueDict(search_user)) asset_filter = AssetFilter(query_dict, queryset=asset_list) else: asset_list = AssetCatalog.objects.all() tag_search = request.GET.get('tag_search', '') type_asset = request.GET.get('asset_type', '') if tag_search: asset_list = asset_list.filter( Q(name__icontains=tag_search) | Q(description__icontains=tag_search) | Q(business_area__name__icontains=tag_search) | Q(product_business__name__icontains=tag_search) | Q(capability_business__name__icontains=tag_search)).distinct( ) total_assets = asset_list.count() asset_filter = AssetFilter(request.GET, queryset=asset_list) page = request.GET.get('page', 1) paginator = Paginator(asset_filter.qs, 30) try: products = paginator.page(page) except PageNotAnInteger: products = paginator.page(1) except EmptyPage: products = paginator.page(paginator.num_pages) return render( request, 'asset_mgmt/asset.html', { 'filter': asset_filter, 'product_name': tag_search, 'type_asset': type_asset, 'total': total_assets, 'products': products })