def encode_data(data, content_type=None): # type: (Any, Optional[text_type]) -> Any # content_type of None means django's test client's default content type # if content_type is None, return data as it is if content_type is None: if data is None: return {} else: return data elif content_type.startswith('application/json'): if data is None: raise BadDataError("empty_json") try: return force_text(json.dumps(data, cls=DjangoJSONEncoder)) except ValueError: raise BadDataError("invalid_format") elif content_type.startswith(FORM_CONTENT_TYPE): if data is None or data == "": return "" elif isinstance(data, dict): form_data = QueryDict(mutable=True) for key, value in six.iteritems(data): if isinstance(value, Sequence) and not(isinstance(value, text_type)): form_data.setlist(str(key), value) else: form_data[key] = value return form_data.urlencode() else: raise BadDataError("invalid_format") else: raise ContentTypeError(content_type)
def get(self, request, *args, **kwargs): args_dict = request.GET.copy() args_dict.update({ "test_suite_pk": kwargs["pk"], "measure_name": kwargs["mname"] }) cmd = [ settings.PYTHON_EXE, os.path.join(settings.BASE_DIR, "bin", "plot_png.py"), args_dict.urlencode(safe='/%') ] print "Plot png: %s" % cmd[-1] result = subprocess.check_output(cmd, env=os.environ.copy()).strip() qdict = QueryDict(result) fname = qdict.get("fname") alarm = qdict.get("alarm") if fname and fname != "": f = open(fname, 'rb') response = HttpResponse(f.read(), 'image/png') f.close() m_path = reverse( 'appmonitor:measure', args=[kwargs["pk"], kwargs["mname"]] ) response.set_cookie("alarm_state", alarm, path=m_path) return response else: f = open('appmonitor/static/appmonitor/nodata.png', 'rb') response = HttpResponse(f.read(), 'image/png') f.close() return response
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)
def add_data(request): response = BaseResponse() try: response.error = [] post_dict = QueryDict(request.body, encoding='utf-8') idc_name = post_dict.get('idc_name') idc_floor = post_dict.get('idc_floor') idc_phone = post_dict.get('idc_phone') idc_address = post_dict.get('idc_address') add_to_db = CMDB_MODELS.IDC( name=idc_name, floor=idc_floor, phone=idc_phone, idc_address = idc_address, ) add_to_db.save() except Exception as e: print(Exception, e) response.status = False response.message = str(e) return response
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
def add_server_group(request): response = BaseResponse() try: response.error = {} print(request.body) post_dict = QueryDict(request.body, encoding='utf-8') add_group_app_id = post_dict.get('add_group_app_id') add_group_name = post_dict.get('add_group_name') add_group_yaml_path = post_dict.get('add_group_yaml_path') add_group_type = post_dict.get('add_group_type') add_to_db = repository_models.AppGroups( name=add_group_name, yaml_path=add_group_yaml_path, # app_id = repository_models.Applications.objects.get(id=add_group_app_id) group_type=add_group_type, ) add_to_db.save() add_to_db.app_id.add(repository_models.Applications.objects.get(id=add_group_app_id)) except Exception as e: print(Exception, e) response.status = False response.message = str(e) return response
def update_urlmaps_groups(request): response = BaseResponse() try: response.error = {} post_dict = QueryDict(request.body, encoding='utf-8') urlmaps_id = post_dict.get('urlmaps_id') instance_list = post_dict.getlist('instance_list') group_type = post_dict.get('group_type') urlmaps_obj = repository_models.UrlConfigHandler.objects.get(id=urlmaps_id) if group_type == 'cloud': urlmaps_obj.cloud.clear() for instance_id in instance_list: urlmaps_obj.cloud.add(CMDB_MODELS.Asset.objects.get(id=instance_id)) elif group_type == 'forward': urlmaps_obj.forward.clear() for instance_id in instance_list: urlmaps_obj.forward.add(CMDB_MODELS.Asset.objects.get(id=instance_id)) elif group_type == 'docker': urlmaps_obj.docker.clear() for instance_id in instance_list: urlmaps_obj.docker.add(CMDB_MODELS.DockerInstance.objects.get(id=instance_id)) except Exception as e: print(Exception, e) response.status = False response.message = str(e) return response
def data_create(request): response = BaseResponse() try: post_data = QueryDict(request.body, encoding='utf-8') role_name = post_data.get('role_name') role_memo = post_data.get('role_memo') permission_list = post_data.getlist('permission_list') # 创建role data_obj = USER_CENTER_MODELS.Roles( name=role_name, memo=role_memo, ) data_obj.save() # 关联permission for obj_id in permission_list: data_obj.permissions.add(obj_id) except Exception as e: print(Exception, e) response.status = False response.message = str(e) return response
def do(self, action_context, view, email, *args, **kwargs): # Reset token user = action_context.extra_context.get('user') if user: refresh_password_reset_token(user) url = reverse('auth:reset-password', kwargs={ 'user_id': user.id, 'uuid': str(user.password_reset_token)}) # Prepare the full url (get the domain from the asked # wiggum entrypoint) domain = action_context.request.META.get('HTTP_HOST') scheme = 'http' if settings.DEBUG else "https" # Get redirection uri params = QueryDict(mutable=True) redirect_uri = action_context.extra_context.get("redirect_uri") if redirect_uri: params[settings.REDIRECT_URL_VALID_PARAMS[0]] = redirect_uri url = urllib.parse.ParseResult(scheme=scheme, netloc=domain, path=url, params="", query=params.urlencode(), fragment="").geturl() action_context.extra_context['pass_reset_url'] = url logger.debug("Password recover url created: {0}".format(url)) return super().do(action_context, view, email, *args, **kwargs)
def dict_to_querydict(dict_data): qdict = QueryDict('', mutable=True) for key, value in dict_data.items(): if isinstance(value, list): qdict.setlist(key, value) else: qdict[key] = value return qdict
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(' ', '+')
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')
def update_params(param_str, **kwargs): query_dict = QueryDict(param_str, True) for key, val in kwargs.iteritems(): if val: query_dict[key] = val else: query_dict.pop(key) if query_dict.has_key(key) else None return UrlHelper.format_params(query_dict)
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()
def test_search_view_with_twitter(self): status_code_expected = 200 dictionary = {'search': 'guadalajara', 'service': 'twitter'} request = QueryDict('', mutable=True) request.GET = dictionary search_view = views.SearchView() response = search_view.get(request, format=None) self.assertEquals( response.status_code, status_code_expected )
def delete_data(request): response = BaseResponse() try: delete_dict = QueryDict(request.body, encoding='utf-8') obj_id = delete_dict.get('obj_id') models.BusinessUnit.objects.filter(id=obj_id).delete() response.message = '删除成功' except Exception as e: response.status = False response.message = str(e) return response
def delete_data(request): response = BaseResponse() try: recv_data = QueryDict(request.body, encoding='utf-8') project_id = recv_data.get("project_id") repository_models.ProjectInfo.objects.get(id=project_id).delete() response.message = '删除成功' except Exception as e: response.status = False response.message = str(e) return response
def delete_assets(request): response = BaseResponse() try: delete_dict = QueryDict(request.body, encoding='utf-8') id_list = delete_dict.getlist('id_list') models.Asset.objects.filter(id__in=id_list).delete() response.message = '删除成功' except Exception as e: response.status = False response.message = str(e) return response
def delete_data(request): response = BaseResponse() try: recv_data = QueryDict(request.body, encoding='utf-8') idc_id = recv_data.get("idc_id") CMDB_MODELS.IDC.objects.get(id=idc_id).delete() response.message = '删除成功' except Exception as e: response.status = False response.message = str(e) return response
def render(self, context): if not len(self.args) or "=" in self.args[0]: querydict = QueryDict("", mutable=True) else: first = self.args[0] self.args = self.args[1:] querydict = Variable(first).resolve(context).copy() for pair in self.args: k, v = [Variable(p).resolve(context) for p in pair.split("=")] querydict[k] = v return querydict.urlencode()
def test_county_select_persists_after_session_update(self): response = self.client.fill_form( reverse('intake-apply'), counties=['alameda', 'contracosta'], confirm_county_selection='yes') request = response.wsgi_request qdict = QueryDict('', mutable=True) qdict.setlist('hello', ['world']) utils.save_form_data_to_session( request, ApplicantFormViewBase.session_key, qdict) form_data = self.client.session.get(ApplicantFormViewBase.session_key) self.assertListEqual(['alameda', 'contracosta'], form_data['counties'])
def data_delete(request): response = BaseResponse() try: delete_data = QueryDict(request.body, encoding='utf-8') obj_id = delete_data.get('obj_id') USER_CENTER_MODELS.Roles.objects.get(id=obj_id).delete() response.message = '删除成功' except Exception as e: response.status = False response.message = str(e) return response
def url_param_replace(self, **kwargs): query = QueryDict(self.request.META['QUERY_STRING'], mutable=True) for key, value in kwargs.items(): if not key: query.pop(key, None) else: query[key] = value if query: return self.request.path_info + '?' + query.urlencode('{}') else: return self.request.path_info
def delete_data(request): response = BaseResponse() try: recv_data = QueryDict(request.body, encoding='utf-8') user_id = recv_data.get("user_id") user_models.UserProfile.objects.get(id=user_id).delete() response.message = '删除成功' except Exception as e: response.status = False response.message = str(e) return response
def parse(cls, request): from django.http.request import QueryDict tmp = QueryDict('', mutable=True) data = underscoreize(dict(request.GET)) for k, v in data.items(): if k in cls.parsing_values: if isinstance(v, str): v = camel_to_underscore(v) elif isinstance(v, list): v = [(camel_to_underscore(v_) if isinstance(v_, str) else v_) for v_ in v] tmp.setlistdefault(k, v) return tmp
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
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)
def get_app_by_project(request): response = BaseResponse() post_dict = QueryDict(request.body, encoding='utf-8') project_id = post_dict.get('project_id') try: data_list = repository_models.Applications.objects.filter(project_id__id=project_id).values() response.data = list(data_list) except Exception as e: response.status = False response.message = str(e) return response
def get_form_data_from_session(request, session_key): """Gets a dictionary from the session based on a key and converts each key, list pair into a mutable QueryDict so that it can be processed by a form as if it were post data """ raw_dict = request.session.get(session_key, {}) qdict = QueryDict('', mutable=True) for key, items in raw_dict.items(): if not isinstance(items, list): items = [items] qdict.setlist(key, items) return qdict
def asset_data_create(request): response = BaseResponse() try: asset_data = QueryDict(request.body, encoding='utf-8') new_asset_num = asset_num.asset_num_builder() asset_sn = asset_data.get('sn') try: Memory = int(asset_data.get('Memory')) except: Memory = None try: DeviceSize = int(asset_data.get('DeviceSize')) except: DeviceSize = None try: cpu_count = int(asset_data.get('cpu_count')) except: cpu_count = None if not asset_sn: asset_sn = new_asset_num # 创建asset obj asset_obj = models.Asset( device_type_id = asset_data.get('device_type_id'), asset_num = new_asset_num, sn = asset_sn, idc_id = asset_data.get('idc_id'), business_unit_id = asset_data.get('business_unit_id'), ) asset_obj.save() # 创建server obj server_obj = models.Server( asset_id = asset_obj.id, hostname = asset_data.get('hostname'), ipaddress = asset_data.get('ipaddress'), manage_ip = asset_data.get('manage_ip'), Memory = Memory, DeviceSize = DeviceSize, cpu_count = cpu_count, ) server_obj.save() response.message = '获取成功' except Exception as e: print(Exception, e) response.status = False response.message = str(e) return response
def deliveryorderconfirmation(request): context = {} do_id = request.POST['delivery_order_id'] po_id = request.POST['purchase_order_id'] user_id = request.user.id staff = Person.objects.get(user_id=user_id) vendor_id = request.POST['vendor_id'] shipping_inst = request.POST['shipping_inst'] description = request.POST['description'] try: vendor_info = Vendor.objects.get(vendor_id=vendor_id) responses = request.read() print(responses) q = QueryDict(responses) items_id = q.getlist('item_id') print(items_id) items_name = q.getlist('item_name') print(items_name) items_quantity = q.getlist('quantity') print(items_quantity) items_unit_price = q.getlist('unit_price') print(items_unit_price) items_total_price = q.getlist('total_price') print(items_total_price) items = list() i = 0 items_length = len(items_id) grand_total = Decimal(0) while i < items_length: total = Decimal(items_quantity[i]) * Decimal(items_unit_price[i]) item_table = { 'item_name': items_name[i], 'item_id': items_id[i], 'quantity': items_quantity[i], 'unit_price': items_unit_price[i], 'total_price': total } items.append(item_table) i = i + 1 grand_total = grand_total + total print(items) context = { 'title': 'Delivery Order Confirmation', 'purchase_order_id': po_id, 'delivery_order_id': do_id, 'staff_id': staff.person_id, 'vendor_id': vendor_id, 'shipping_inst': shipping_inst, 'grand_total': grand_total, 'rows': items, 'staff_info': staff, 'vendor_info': vendor_info, 'description': description } return render(request, 'DeliveryOrder/deliveryorderconfirmation.html', context) except Vendor.DoesNotExist: context = { 'error': 'Please fill in the Record Delivery Order form before submitting!', } return render(request, 'DeliveryOrder/deliveryorderform.html', context)
def purchaseorderconfirmation(request): context = {} po_id = request.POST['purchase_order_id'] quotation_id = request.POST['quotation_id'] staff_id = request.user.id staff = Person.objects.get(user_id=staff_id) vendor_id = request.POST['vendor_id'] shipping_inst = request.POST['shipping_inst'] description = request.POST['description'] vendor_info = Vendor.objects.get(vendor_id=vendor_id) #extract information from item table responses = request.read() print(responses) q = QueryDict(responses) items_id = q.getlist('item_id') print(items_id) items_name = q.getlist('item_name') print(items_name) items_quantity = q.getlist('quantity') print(items_quantity) items_unit_price = q.getlist('unit_price') print(items_unit_price) items_total_price = q.getlist('total_price') print(items_total_price) items = list() i = 0 items_length = len(items_id) grand_total = Decimal(0) while i < items_length: total = Decimal(items_quantity[i]) * Decimal(items_unit_price[i]) item_table = { 'item_name': items_name[i], 'item_id': items_id[i], 'quantity': items_quantity[i], 'unit_price': items_unit_price[i], 'total_price': total } items.append(item_table) i = i + 1 grand_total = grand_total + total print(items) context = { 'title': 'Purchase Order Confirmation', 'quotation_id': quotation_id, 'purchase_order_id': po_id, 'vendor_id': vendor_id, 'shipping_inst': shipping_inst, 'grand_total': grand_total, 'rows': items, 'staff': staff, 'vendor_info': vendor_info, 'description': description } return render(request, 'PurchaseOrder/purchaseorderconfirmation.html', context)
def back_url_param(self): query = QueryDict(mutable=True) if self.request.GET: query[self.change_filter_name] = self.request.GET.urlencode() return query.urlencode()
def requestforquotationdetails(request): context = {} rfq_id = request.POST['request_for_quotation_id'] purchase_requisition_id = request.POST['purchase_requisition_id'] staff_id = request.user.id vendor_id = request.POST['vendor_id'] description = request.POST['description'] purchase_requisition = PurchaseRequisition.objects.get( pr_id=purchase_requisition_id) staff_info = Person.objects.get(user_id=staff_id) vendor_info = Vendor.objects.get(vendor_id=vendor_id) responses = request.read() print(responses) q = QueryDict(responses) items_id = q.getlist('item_id') print(items_id) items_name = q.getlist('item_name') print(items_name) items_quantity = q.getlist('quantity') print(items_quantity) items_unit_price = q.getlist('unit_price') print(items_unit_price) items_total_price = q.getlist('total_price') print(items_total_price) items = list() i = 0 items_length = len(items_id) grand_total = Decimal(0) while i < items_length: total = Decimal(items_quantity[i]) * Decimal(items_unit_price[i]) item_table = { 'item_name': items_name[i], 'item_id': items_id[i], 'quantity': items_quantity[i], 'unit_price': items_unit_price[i], 'total_price': total } items.append(item_table) i = i + 1 grand_total = grand_total + total print(items) # push the data to the database current_time = datetime.datetime.now() print(current_time) rfq_info = RequestForQuotation( request_for_quotation_id=rfq_id, time_created=current_time, total_price=grand_total, person_id=staff_info, description=description, vendor_id=vendor_info, purchase_requisition_id=purchase_requisition) rfq_info.save() request_for_quotation = RequestForQuotation.objects.get( request_for_quotation_id=rfq_id) for item in items: item_info = Item.objects.get(item_id=item['item_id']) rfq_item_info = RequestForQuotationItem( request_for_quotation_id=request_for_quotation, item_id=item_info, quantity=item['quantity'], unit_price=item['unit_price'], total_price=item['total_price']) rfq_item_info.save() # update status purchase requisition pr = PurchaseRequisition.objects.get(pr_id=purchase_requisition_id) pr.status = 'APPROVED' pr.save() print(pr) try: #send email to vendor x = PrettyTable() x.field_names = [ "Item ID", "Item Name", "Quantity", "Unit Price", "Total Price" ] for item in items: x.add_row([ item['item_id'], item['item_name'], item['quantity'], item['unit_price'], item['total_price'] ]) subject = 'REQUEST FOR QUOTATION INFORMATION: ' + rfq_id message = 'This is the Request of Quotation Order Information: \n' + 'Person In Charge: ' + staff_info.person_name + '\n' + staff_info.person_address + '\n' + 'Request of Quotation Number: ' + rfq_id + '\n' + '\n' + 'Time Issued: ' + str( current_time ) + '\n' + 'Vendor ID: ' + vendor_id + '\n' + 'Description: ' + description + '\n' + str( x) + '\n' email_from = settings.EMAIL_HOST_USER recipient_list = [ vendor_info.vendor_email, ] send_mail(subject, message, email_from, recipient_list) # info pass to html context = { 'title': 'Request For Quotation Details', 'purchase_requisition_id': purchase_requisition_id, 'request_for_quotation_id': rfq_id, 'vendor_id': vendor_id, 'rows': items, 'staff_info': staff_info, 'vendor_info': vendor_info, 'grand_total': grand_total, 'time_created': current_time, 'description': description } return render(request, 'RequestForQuotation/requestforquotationdetails.html', context) except IntegrityError: return render(request, 'RequestForQuotation/requestforquotationdetails.html', context) except ConnectionRefusedError: context = { 'title': 'Request For Quotation Details', 'purchase_requisition_id': purchase_requisition_id, 'request_for_quotation_id': rfq_id, 'vendor_id': vendor_id, 'rows': items, 'staff_info': staff_info, 'vendor_info': vendor_info, 'grand_total': grand_total, 'time_created': current_time, 'description': description } return render(request, 'RequestForQuotation/requestforquotationdetails.html', context)
def changelist_view(self, request): """ 查看列表 :param requset: :return: """ #生成页面上的添加按钮 #namespace,app_label,model_name # print(request.GET.urlencode()) #urlencode获取url param_dict = QueryDict(mutable=True) #设置为可修改 if request.GET: param_dict['_changlistfilter'] = request.GET.urlencode() base_add_url = reverse("{2}:{0}_{1}_add".format( self.app_label, self.model_name, self.site.namespace)) add_url = "{0}?{1}".format(base_add_url, param_dict.urlencode()) self.request = request #分页开始 condition = {} from extraapp.utils.my_page import PageInfo all_count = self.model_class.objects.filter(**condition).count() base_page_url = self.changelist_param_url() page_param_dict = copy.deepcopy(request.GET) #全新的复制一份 page_param_dict._mutable = True page_param_dict["page"] = 1 page_obj = PageInfo(request.GET.get("page"), all_count, base_page_url, page_param_dict) result_list = self.model_class.objects.filter( **condition)[page_obj.start:page_obj.end] ################ Action操作 ################ #get请求,显示下拉框 action_list = [] for item in self.action_list: tpl = {'name': item.__name__, 'text': item.text} action_list.append(tpl) if request.method == "POST": """1、获取action""" func_name_str = request.POST.get('action') ret = getattr(self, func_name_str)(request) action_page_url = self.changelist_param_url() if ret: action_page_url = self.changelist_param_url(request.GET) return redirect(action_page_url) ######组合搜索操作####### from extraapp.utils.filter_code import FilterList filter_list = [] for option in self.filter_list: if option.is_func: data_list = option.field_or_func(self, option, request) else: #username ug m2m from django.db.models import ForeignKey, ManyToManyField field = self.model_class._meta.get_field(option.field_or_func) # print(request.GET) if isinstance(field, ForeignKey): # print(field.rel.model) #封装了外键表对象 data_list = FilterList(option, field.rel.model.objects.all(), request) elif isinstance(field, ManyToManyField): data_list = FilterList(option, field.rel.model.objects.all(), request) else: # self.model_class or field.model 都可以拿到userinfo data_list = FilterList(option, field.model.objects.all(), request) # yield data_list filter_list.append(data_list) context = { 'result_list': result_list, 'list_display': self.list_display, 'BaseExtraAdmin_obj': self, 'add_url': add_url, 'page_str': page_obj.pager(), 'action_list': action_list, 'filter_list': filter_list } return render( request, 'exapp/change_list.html', # {'result_list':result_list,'list_display':self.list_display} context #同上一样 )
def __init__(self, view): self.view = view self.cookie_data = QueryDict(view.cookie_data.get(self.slug)) or None
}), ), ( "https://sentry.io/organizations/org1/alerts/rules/details/12345/", (LinkType.INCIDENTS, { "incident_id": 12345, "org_slug": "org1" }), ), ( "https://sentry.io/organizations/org1/discover/results/?project=1&yAxis=count()", ( LinkType.DISCOVER, { "org_slug": "org1", "query": QueryDict("project=1&yAxis=count()") }, ), ), ], ) def test_match_link(url, expected): assert match_link(url) == expected class UnfurlTest(TestCase): def setUp(self): super().setUp() self.request = RequestFactory().get("slack/event") self.user = self.create_user(is_superuser=False) self.org = self.create_organization(owner=None)
def invoicedetails(request): context = {} inv_id = request.POST['invoice_id'] purchase_order_id = request.POST['purchase_order_id'] staff_id = request.POST['staff_id'] vendor_id = request.POST['vendor_id'] description = request.POST['description'] purchaseorder = PurchaseOrder.objects.get(purchase_order_id = purchase_order_id) staff_info = Person.objects.get(person_id = staff_id) vendor_info = Vendor.objects.get(vendor_id = vendor_id) responses = request.read() print(responses) q= QueryDict(responses) items_id = q.getlist('item_id') print(items_id) items_name = q.getlist('item_name') print(items_name) items_quantity = q.getlist('quantity') print(items_quantity) items_unit_price = q.getlist('unit_price') print(items_unit_price) items_total_price = q.getlist('total_price') print(items_total_price) items = list() i = 0 items_length = len(items_id) grand_total = Decimal(0) while i < items_length: total= Decimal(items_quantity[i]) * Decimal(items_unit_price[i]) item_table = { 'item_name': items_name[i], 'item_id': items_id[i], 'quantity' : items_quantity[i], 'unit_price': items_unit_price[i], 'total_price': total } items.append(item_table) i = i + 1 grand_total = grand_total + total print(items) # push the data to the database current_time = datetime.datetime.now() print(current_time) inv_info = Invoice(invoice_id = inv_id, time_created = current_time, total_price = grand_total, person_id = staff_info, description = description, vendor_id = vendor_info, purchase_order_id = purchaseorder, ) inv_info.save() invoice = Invoice.objects.get(invoice_id = inv_id) for item in items: item_info = Item.objects.get(item_id = item['item_id']) inv_item_info = InvoiceItem(invoice_id = invoice, item_id = item_info, quantity = item['quantity'], unit_price = item['unit_price'], total_price = item['total_price']) inv_item_info.save() # info pass to html context = { 'title': 'Invoice Details', 'purchase_order_id' : purchase_order_id, 'invoice_id' : inv_id, 'staff_id' : staff_id, 'vendor_id' : vendor_id, 'rows' : items, 'staff_info' : staff_info, 'vendor_info' : vendor_info, 'grand_total': grand_total, 'time_created': current_time, 'description' : description } return render(request,'Invoice/invoicedetails.html',context)
def to_querydict(dictionary): querydict = QueryDict(mutable=True) for key, value in dictionary.items(): querydict[key] = value return querydict
def get(self, request, *args, **kwargs): request_meta_qs = request.META["QUERY_STRING"] request_get = request.GET response_qs = None if request_meta_qs: response_qs = request_meta_qs elif "oauth_token" in request_get and "oauth_verifier" in request_get: response_qs = request_get.urlencode() try: response_qs_parsed = urllib.parse.parse_qs(response_qs) assert "oauth_token" in response_qs_parsed assert "oauth_verifier" in response_qs_parsed except (AssertionError, TypeError): logger.exception("Did not receive a valid oauth response.") messages.add_message( request, messages.WARNING, # Translators: This warning message is shown to users when the response received from Wikimedia OAuth servers is not a valid one. _("Did not receive a valid oauth response."), ) raise PermissionDenied # Get the handshaker. It should have already been constructed by # OAuthInitializeView. domain = self.request.get_host() try: assert domain in settings.ALLOWED_HOSTS except (AssertionError, DisallowedHost): logger.exception("Domain is not an allowed host") messages.add_message( request, messages.WARNING, # Translators: This message is shown when the OAuth login process fails because the request came from the wrong website. Don't translate {domain}. _("{domain} is not an allowed host.").format(domain=domain), ) raise PermissionDenied try: handshaker = _get_handshaker() except AssertionError: # get_handshaker will throw AssertionErrors for invalid data. logger.exception("Could not find handshaker") messages.add_message( request, messages.WARNING, # Translators: This message is shown when the OAuth login process fails. _("Could not find handshaker."), ) raise PermissionDenied # Get the session token placed by OAuthInitializeView. session_token = request.session.pop("request_token", None) if not session_token: logger.info("No session token.") messages.add_message( request, messages.WARNING, # Translators: This message is shown when the OAuth login process fails. _("No session token."), ) raise PermissionDenied # Rehydrate it into a request token. request_token = _rehydrate_token(session_token) if not request_token: logger.info("No request token.") messages.add_message( request, messages.WARNING, # Translators: This message is shown when the OAuth login process fails. _("No request token."), ) raise PermissionDenied # See if we can complete the OAuth process. try: access_token = handshaker.complete(request_token, response_qs) except: logger.exception("Access token generation failed.") messages.add_message( request, messages.WARNING, # Translators: This message is shown when the OAuth login process fails. _("Access token generation failed."), ) raise PermissionDenied user = authenticate( request=request, access_token=access_token, handshaker=handshaker ) created = request.session.pop("user_created", False) if user and not user.is_active: # Do NOT log in the user. if created: messages.add_message( request, messages.WARNING, # fmt: off # Translators: If the user tries to log in, but their account does not meet certain requirements, they cannot login. _("Your Wikipedia account does not meet the eligibility criteria in the terms of use, so your Wikipedia Library Card Platform account cannot be activated."), # fmt: on ) else: messages.add_message( request, messages.WARNING, # fmt: off # Translators: If the user tries to log in, but their account does not meet certain requirements, they cannot login. Translate Wikipedia Library in the same way as the global branch is named (click through from https://meta.wikimedia.org/wiki/The_Wikipedia_Library). _("Your Wikipedia account no longer meets the eligibility criteria in the terms of use, so you cannot be logged in. If you think you should be able to log in, please email [email protected]."), # fmt: on ) return_url = reverse_lazy("terms") elif user: login(request, user) if created: messages.add_message( request, messages.INFO, # Translators: this message is displayed to users with brand new accounts. _("Welcome! Please agree to the terms of use."), ) return_url = reverse_lazy("terms") else: # We're using this twice. Not very DRY. # Send user either to the destination specified in the 'next' # parameter or to their own editor detail page. if user.userprofile.terms_of_use: try: # Create a QueryDict from the 'get' session dict. query_dict = QueryDict( urlencode(request.session["get"]), mutable=True ) # Pop the 'next' parameter out of the QueryDict. next = query_dict.pop("next") # Set the return url to the value of 'next'. Basic. return_url = next[0] # If there is anything left in the QueryDict after popping # 'next', append it to the return url. This preserves state # for filtered lists and redirected form submissions like # the partner suggestion form. if query_dict: return_url += "?" + urlencode(query_dict) logger.info( "User authenticated. Sending them on for " 'post-login redirection per "next" parameter.' ) except KeyError: return_url = reverse_lazy("homepage") logger.warning( 'User authenticated. No "next" parameter ' "for post-login redirection." ) else: messages.add_message( request, messages.INFO, # Translators: This message is shown when a user logs back in to the site after their first time and hasn't agreed to the terms of use. _("Welcome back! Please agree to the terms of use."), ) return_url = reverse_lazy("terms") else: return_url = reverse_lazy("homepage") return HttpResponseRedirect(return_url)
def invoiceconfirmation(request): context = {} inv_id = request.POST['invoice_id'] pur_id = request.POST['purchase_order_id'] staff_id = request.POST['staff_id'] vendor_id = request.POST['vendor_id'] description = request.POST['description'] inv_stat = request.POST.get('invoice_status',False) staff_info = Person.objects.get(person_id = staff_id) vendor_info = Vendor.objects.get(vendor_id= vendor_id) responses = request.read() print(responses) q= QueryDict(responses) items_id = q.getlist('item_id') print(items_id) items_name = q.getlist('item_name') print(items_name) items_quantity = q.getlist('quantity') print(items_quantity) items_unit_price = q.getlist('unit_price') print(items_unit_price) items_total_price = q.getlist('total_price') print(items_total_price) items = list() i = 0 items_length = len(items_id) grand_total = Decimal(0) while i < items_length: total = Decimal(items_quantity[i]) * Decimal(items_unit_price[i]) item_table = { 'item_name': items_name[i], 'item_id': items_id[i], 'quantity' : items_quantity[i], 'unit_price': items_unit_price[i], 'total_price': total } items.append(item_table) i = i + 1 grand_total = grand_total + total print(items) if len(items) <= 0: context = { 'error': 'Items cannot be empty!!', 'title': 'Invoice Form', 'itemOk': False } responsesItems = render(request,'Invoice/invoiceform.html',context).content return render(request,'Invoice/invoiceform.html',context) else: context = { 'title': 'Invoice Confirmation', 'purchase_order_id' :pur_id, 'invoice_id' : inv_id, 'staff_info' : staff_info, 'staff_id' : staff_id, 'description' : description, 'vendor_info' : vendor_info, 'vendor_id' : vendor_id, 'grand_total': grand_total, 'rows' : items, 'itemOk': True } return render(request,'Invoice/invoiceconfirmation.html',context)
def get(self, request, *args, **kwargs): # The site might be running under multiple URLs, so find out the current # one (and make sure it's legit). # The Sites framework was designed for different URLs that correspond to # different databases or functionality - it's not a good fit here. domain = self.request.get_host() try: assert domain in settings.ALLOWED_HOSTS # safety first! except (AssertionError, DisallowedHost): logger.exception() messages.add_message( request, messages.WARNING, # Translators: This message is shown when the OAuth login process fails because the request came from the wrong website. Don't translate {domain}. _("{domain} is not an allowed host.").format(domain=domain), ) raise PermissionDenied # Try to capture the relevant page state, including desired destination try: request.session["get"] = request.GET logger.info("Found get parameters for post-login redirection.") except: logger.warning("No get parameters for post-login redirection.") pass # If the user has already logged in, let's not spam the OAuth provider. if self.request.user.is_authenticated(): # We're using this twice. Not very DRY. # Send user either to the destination specified in the 'next' # parameter or to their own editor detail page. try: # Create a QueryDict from the 'get' session dict. query_dict = QueryDict(urlencode(request.session["get"]), mutable=True) # Pop the 'next' parameter out of the QueryDict. next = query_dict.pop("next") # Set the return url to the value of 'next'. Basic. return_url = next[0] # If there is anything left in the QueryDict after popping # 'next', append it to the return url. This preserves state # for filtered lists and redirected form submissions like # the partner suggestion form. if query_dict: return_url += "?" + urlencode(query_dict) logger.info( "User is already authenticated. Sending them on " 'for post-login redirection per "next" parameter.' ) except KeyError: return_url = reverse_lazy("homepage") logger.warning( 'User already authenticated. No "next" ' "parameter for post-login redirection." ) return HttpResponseRedirect(return_url) else: # Get handshaker for the configured wiki oauth URL. handshaker = _get_handshaker() logger.info("handshaker gotten.") try: redirect, request_token = handshaker.initiate() except: logger.exception("Handshaker not initiated.") raise local_redirect = _localize_oauth_redirect(redirect) logger.info("handshaker initiated.") self.request.session["request_token"] = _dehydrate_token(request_token) return HttpResponseRedirect(local_redirect)
def purchaserequisitiondetails(request): context = {} pr_id = request.POST['purchase_requisition_id'] staff_id = request.POST['person_id'] print(staff_id) staff = Person.objects.get(person_id=staff_id) responses = request.read() print(responses) q = QueryDict(responses) items_id = q.getlist('item_id') print(items_id) items_name = q.getlist('item_name') print(items_name) description = q.getlist('description') print(items_name) quantity = q.getlist('quantity') print(quantity) unit_price = q.getlist('unit_price') print(unit_price) total_price = q.getlist('total_price') print(total_price) items = list() i = 0 items_length = len(items_id) grand_total = Decimal(0) while i < items_length: total = Decimal(quantity[i]) * Decimal(unit_price[i]) item_table = { 'item_name': items_name[i], 'item_id': items_id[i], 'description': description[i], 'quantity': quantity[i], 'unit_price': unit_price[i], 'total_price': total } items.append(item_table) i = i + 1 grand_total = grand_total + total print(items) # push the data to the database current_time = datetime.datetime.now() print(current_time) pr_info = PurchaseRequisition( pr_id=pr_id, person_id=staff, time_created=current_time, total_price=grand_total, description=description, ) pr_info.save() purchase_requisition = PurchaseRequisition.objects.get(pr_id=pr_id) for item in items: itemitem = Item(item_id=item['item_id'], item_name=item['item_name']) itemitem.save() pr_item_info = PurchaseRequisitionItem(pr_id=purchase_requisition, item_id=itemitem, quantity=item['quantity'], unit_price=item['unit_price']) pr_item_info.save() # info pass to html context = { 'title': 'Purchase Requisition Details', 'purchase_requisition_id': pr_id, 'staff': staff, 'rows': items, 'grand_total': grand_total, 'time_created': current_time, } return render(request, 'PurchaseRequisition/purchaserequisitiondetails.html', context)
def replace_query_param(url, key, value): (scheme, netloc, path, params, query, fragment) = urlparse(url) query_dict = QueryDict(query).copy() query_dict[key] = value query = query_dict.urlencode() return urlunparse((scheme, netloc, path, params, query, fragment))
class Pagenation: def __init__(self, request, all_num, params=None, per_page=10, max_item=11): """ :param request: request请求对象 :param all_num: 需要分页的数据量 :param per_page: 每页需要展示的数据条数 :param max_item: 显示的页码 page:如果page为非数字需要进行异常处理,并设置其为1 """ try: page = int(request.GET.get('page', 1)) page = 1 if page <= 0 else page except Exception: page = 1 # 查询条件 self.params = params if not self.params: self.params = QueryDict(mutable=True) # total_page: 分的总页数 total_page, b = divmod(all_num, per_page) total_page = total_page + 1 if b else total_page # page 对超出边界的page进行限制 page = page if page < total_page else total_page # end和start表示显示的起始页码, views函数需要 self.end = page * per_page self.start = self.end - per_page half_item = max_item // 2 # 表示页码的起始数 self.start_page = page - half_item self.end_page = page + half_item # page表示当前页码 self.page = page self.max_item = max_item self.total_page = total_page self.start_page = 1 if self.start_page <= 0 else self.start_page if self.end_page > self.total_page: self.start_page = self.total_page - self.max_item + 1 self.end_page = self.start_page + self.max_item if self.start < 0: self.start = 1 self.end = 1 @property def show(self): li_li = [] self.params['page'] = 1 li_li.append( ' <li><a href="?{}" aria-label=""><span aria-hidden="true">首页</span></a></li>'.format( self.params.urlencode())) if self.start == self.end == 1: li_li.append('<li class="active"><a href="?{}">1</a></li>'.format(self.params.urlencode())) else: if self.page == 1: li_li.append( ' <li style="display:none"><span aria-hidden="true">«</span></li>') else: self.params['page'] = self.page - 1 li_li.append( ' <li><a href="?{}" aria-label="Previous"><span aria-hidden="true">«</span></a></li>'.format( self.params.urlencode())) if self.total_page < self.max_item: self.start_page = 1 self.end_page = self.total_page + 1 for i in range(self.start_page, self.end_page): self.params['page'] = i if self.page == i: li_li.append('<li class="active"><a href="?{}">{}</a></li>'.format(self.params.urlencode(), i)) else: li_li.append('<li><a href="?{}">{}</a></li>'.format(self.params.urlencode(), i)) if self.page == self.total_page: li_li.append( '<li style="display:none"><span aria-hidden="true">»</span></li>') else: self.params['page'] = self.page + 1 li_li.append( '<li><a href="?{}" aria-label="Next"><span aria-hidden="true">»</span></a></li>'.format( self.params.urlencode(), self.page + 1)) self.params['page'] = self.total_page li_li.append( ' <li><a href="?{}" aria-label="Previous"><span aria-hidden="true">尾页</span></a></li>'.format( self.params.urlencode())) return mark_safe(''.join(li_li))
def test_only_scheduled_all(self): job1, job2 = JobFactory.create_batch(2) job3 = JobFactory.create(publish_end=datetime(2019, 2, 2)) filtr = JobFilter(QueryDict(query_string='only_scheduled=all'), queryset=models.Job.objects.all()) self.assertEqual(set([job1, job2, job3]), set(filtr.qs))
def get(self, request, *args, **kwargs): request_meta_qs = request.META['QUERY_STRING'] request_get = request.GET response_qs = None if request_meta_qs: response_qs = request_meta_qs elif 'oauth_token' in request_get and 'oauth_verifier' in request_get: response_qs = request_get.urlencode() try: response_qs_parsed = urlparse.parse_qs(response_qs) assert 'oauth_token' in response_qs_parsed assert 'oauth_verifier' in response_qs_parsed except (AssertionError, TypeError): logger.exception('Did not receive a valid oauth response.') messages.add_message(request, messages.WARNING, _('Did not receive a valid oauth response.')) raise PermissionDenied # Get the handshaker. It should have already been constructed by # OAuthInitializeView. try: domain = self.request.get_host() assert domain in settings.ALLOWED_HOSTS except (AssertionError, DisallowedHost): logger.exception('Domain is not an allowed host') messages.add_message( request, messages.WARNING, _('{domain} is not an allowed host.').format(domain=domain)) raise PermissionDenied try: handshaker = _get_handshaker() except AssertionError: # get_handshaker will throw AssertionErrors for invalid data. logger.exception('Could not find handshaker') messages.add_message( request, messages.WARNING, # Translators: This message is shown when the OAuth login process fails. _('Could not find handshaker.')) raise PermissionDenied # Get the request token, placed in session by OAuthInitializeView. session_token = request.session.pop('request_token', None) request_token = _rehydrate_token(session_token) if not request_token: logger.info('No request token.') messages.add_message( request, messages.WARNING, # Translators: This message is shown when the OAuth login process fails. _('No request token.')) raise PermissionDenied # See if we can complete the OAuth process. try: access_token = handshaker.complete(request_token, response_qs) except: logger.exception('Access token generation failed.') messages.add_message( request, messages.WARNING, # Translators: This message is shown when the OAuth login process fails. _('Access token generation failed.')) raise PermissionDenied user = authenticate(request=request, access_token=access_token, handshaker=handshaker) created = request.session.pop('user_created', False) if not user.is_active: # Do NOT log in the user. if created: messages.add_message( request, messages.WARNING, # Translators: If the user tries to log in, but their account does not meet certain requirements, they cannot login. _('Your Wikipedia account does not meet the eligibility ' 'criteria in the terms of use, so your Wikipedia Library ' 'Card Platform account cannot be activated.')) else: # Translators: If the user tries to log in, but their account does not meet certain requirements, they cannot login. Translate Wikipedia Library in the same way as the global branch is named (click through from https://meta.wikimedia.org/wiki/The_Wikipedia_Library). messages.add_message( request, messages.WARNING, _('Your Wikipedia account no longer ' 'meets the eligibility criteria in the terms of use, so ' 'you cannot be logged in. If you think you should be ' 'able to log in, please email ' '[email protected].')) return_url = reverse_lazy('terms') else: login(request, user) if created: # Translators: this message is displayed to users with brand new accounts. messages.add_message( request, messages.INFO, _('Welcome! ' 'Please agree to the terms of use.')) return_url = reverse_lazy('terms') else: # Translators: This message is shown when a user logs back in to the site after their first time. messages.add_message(request, messages.INFO, _('Welcome back!')) # We're using this twice. Not very DRY. # Send user either to the destination specified in the 'next' # parameter or to their own editor detail page. try: # Create a QueryDict from the 'get' session dict. query_dict = QueryDict(urlencode(request.session['get']), mutable=True) # Pop the 'next' parameter out of the QueryDict. next = query_dict.pop('next') # Set the return url to the value of 'next'. Basic. return_url = next[0].encode('ascii', 'ignore') # If there is anything left in the QueryDict after popping # 'next', append it to the return url. This preserves state # for filtered lists and redirected form submissions like # the partner suggestion form. if query_dict: return_url += '?' + urlencode(query_dict) logger.info('User authenticated. Sending them on for ' 'post-login redirection per "next" parameter.') except KeyError: return_url = reverse_lazy('users:editor_detail', kwargs={'pk': user.editor.pk}) logger.warning('User authenticated. No "next" parameter ' 'for post-login redirection.') return HttpResponseRedirect(return_url)
def test_only_scheduled_false(self): job1 = JobFactory.create(publish_start=None, publish_end=None) JobFactory.create(publish_end=datetime(2019, 2, 2)) filtr = JobFilter(QueryDict(query_string='only_scheduled=false'), queryset=models.Job.objects.all()) self.assertEqual(set([job1]), set(filtr.qs))
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
def deserialize_form(data): return QueryDict(query_string=data)
def requestforquotationconfirmation(request): try: context = {} rfq_id = request.POST['request_for_quotation_id'] purchase_requisition_id = request.POST['purchase_requisition_id'] staff_id = request.user.id vendor_id = request.POST['vendor_id'] description = request.POST['description'] staff_info = Person.objects.get(user_id=staff_id) responses = request.read() print(responses) q = QueryDict(responses) items_id = q.getlist('item_id') print(items_id) items_name = q.getlist('item_name') print(items_name) items_quantity = q.getlist('quantity') print(items_quantity) items_unit_price = q.getlist('unit_price') print(items_unit_price) items_total_price = q.getlist('total_price') print(items_total_price) items = list() i = 0 items_length = len(items_id) grand_total = Decimal(0) while i < items_length: total = Decimal(items_quantity[i]) * Decimal(items_unit_price[i]) item_table = { 'item_name': items_name[i], 'item_id': items_id[i], 'quantity': items_quantity[i], 'unit_price': items_unit_price[i], 'total_price': total } items.append(item_table) i = i + 1 grand_total = grand_total + total print(items) try: vendor_info = Vendor.objects.get(vendor_id=vendor_id) context = { 'title': 'Request For Quotation Confirmation', 'purchase_requisition_id': purchase_requisition_id, 'request_for_quotation_id': rfq_id, 'staff_id': staff_id, 'vendor_id': vendor_id, 'grand_total': grand_total, 'rows': items, 'staff_info': staff_info, 'vendor_info': vendor_info, 'description': description } return render( request, 'RequestForQuotation/requestforquotationconfirmation.html', context) except Vendor.DoesNotExist: context = { 'error': 'Please insert valid vendor ID!', 'title': 'Request Of Quotation Form', 'purchase_requisition_id': purchase_requisition_id, 'request_for_quotation_id': rfq_id, 'staff_id': staff_id, 'grand_total': grand_total, 'rows': items, 'staff_info': staff_info, 'description': description } return render(request, 'RequestForQuotation/requestforquotationform.html', context) except decimal.InvalidOperation: context = { 'error': 'Please enter valid quantity value !', 'title': 'Request Of Quotation Form', 'purchase_requisition_id': purchase_requisition_id, 'request_for_quotation_id': rfq_id, 'staff_id': staff_id, 'grand_total': grand_total, 'rows': items, 'staff_info': staff_info, 'description': description } return render(request, 'RequestForQuotation/requestforquotationform.html', context)
def connect(self): """ 建立WebSocket连接,并实例化SSHBridge类,在这个对象中建立SSH连接,放在 self.ssh_channel 通道中 :return: """ self.host_id = self.scope['url_route']['kwargs'].get('host_id') # 获取session中的值 self.simple_user = self.scope["user"].username # print('【Web --websocket--> WS】建立WebSocket通道,当前连接用户:', self.simple_user) host_obj = Host.objects.get(id=self.host_id) self.accept() # WebSocket连接成功后,连接ssh query_string = self.scope.get('query_string') ws_args = QueryDict(query_string=query_string, encoding='utf-8') # # print(ws_args) # <QueryDict: {'user': ['admin'], 'host': ['192.168.96.20'], 'port': ['22'], 'auth': ['pwd'], 'pwd': ['ZGphbmdvYWRtaW4='], 'key': [''], 'width': ['113'], 'height': ['43']}> # 根据参数判断是否是协作 team = ws_args.get('team') if team: self.is_team = True self.team_name = "team_{}".format(self.host_id) # 加到这个通道组 async_to_sync(self.channel_layer.group_add)( self.team_name, self.channel_name ) # 用户连接时,同一群组发送消息 self.send_message_or_team(json.dumps( {'flag': 'user', 'message': '用户 {} 已连接本终端'.format(self.simple_user)})) width = ws_args.get('width') height = ws_args.get('height') width = int(width) height = int(height) # ssh连接要求int类型:required argument is an integer ssh_connect_dict = {} user = self.simple_user host = host_obj.ip port = host_obj.ssh_port port = int(port) auth = host_obj.ssh_user pwd = host_obj.ssh_passwd # if pwd: # pwd = base64.b64decode(pwd).decode('utf-8') sshkey_filename_path = host_obj.ssh_key.ssh_key.path if host_obj.ssh_key else None ssh_connect_dict = { 'host': host, 'user': auth, 'port': port, 'timeout': 30, 'pty_width': width, 'pty_height': height, 'pwd': pwd } if sshkey_filename_path: if not os.path.exists(sshkey_filename_path): self.send(json.dumps( {'flag': 'error', 'message': '密钥文件不存在'})) else: try: f = open(sshkey_filename_path, 'r', encoding='utf-8') key = f.read() string_io = StringIO() string_io.write(key) string_io.flush() string_io.seek(0) ssh_connect_dict['key'] = string_io # os.remove(sshkey_filename_path) # 用完之后删除key文件 except BaseException as e: # print('打开密钥文件出错', e) pass # 建立SSH连接 self.ssh = SSHBridge(websocket=self, simpleuser=self.simple_user) # print('【WS --SSHBridge--> SSH】连接SSH参数:', ssh_connect_dict) self.ssh.connect(**ssh_connect_dict)
def changelist_view(self,request): """ 查看列表 :param request: :return: """ #生成页面上:添加按钮 self.request = request #当前请求信息 result_lists = self.model_class.objects.filter(**self.get_change_list_condition(request.GET)) param_dict = QueryDict(mutable=True) #获取 字典 对象,改成可修改的类型 if request.GET: #如果有值 param_dict["_changelistfilter"] = request.GET.urlencode() #就把获取到的传值原封不动的 写入queryset对象中 # print(param_dict["_changelistfilter"]) #page=8&r=ooo urlencode()是把获取到的GET传值转换成url上可以应用的类型 base_add_url = reverse("{0}:{1}_{2}_add".format(self.site.namespace,self.app_label,self.model_name)) #反向获取添加操作的url add_url = "{0}?{1}".format(base_add_url,param_dict.urlencode()) #把值传给添加url,携带用以返回当前目录 # print(add_url) #分页 开始 # condition = {} from AdminPlugin.utils.my_page import PageInfo # all_count = self.model_class.objects.filter(**condition).count() all_count = result_lists.count() base_page_url = reverse("{0}:{1}_{2}_changelist".format(self.site.namespace,self.app_label,self.model_name)) #反向获取操作的url page_param_dict = copy.deepcopy(request.GET) #获取页面 URL GET方式传入的参数 page_param_dict._mutable = True #可更改 page_obj = PageInfo(request.GET.get("page"),all_count,base_page_url,page_param_dict) #获取数据生成页面上:表格 result_list = result_lists[page_obj.start:page_obj.end] #从数据库中获取数据 对象列表 #分页结束 ######Action操作#### #get请求,显示下拉框 action_list = [] for item in self.action_list: tpl = {"name":item.__name__,"text":item.text} action_list.append(tpl) if request.method == "POST": #1、获取action func_name_str = request.POST.get("action") ret = getattr(self,func_name_str)(request) action_url = reverse("{0}:{1}_{2}_changelist".format(self.site.namespace,self.app_label,self.model_name)) #反向获取添加操作的url if ret: action_url = "{0}?{1}".format(action_url,request.GET.urlencode()) return redirect(action_url) # ############ 组合搜索操作 ############## from AdminPlugin.utils.filter_code import FilterList filter_list = [] #先定义一个空列表,用于存放处理之后的信息 for option in self.filter_list:#循环列表,获取每个FilterOption对象 if option.is_func: #调用对象下的 is_func方法,判断是否传入的第一个参数是否为函数 data_list = option.field_or_func(self, option, request) #如果是函数,就把当前对象,请求信息交给该函数处理 else:#不是函数,那就是字段 from django.db.models import ForeignKey, ManyToManyField #用于验证 field = self.model_class._meta.get_field(option.field_or_func) #通过对象中传入的field_or_func参数,获取对应数据库中的field对象 #获取关联表的数据 if isinstance(field, ForeignKey): #判断字段类型,如果是外键或是字符串 # print(field.rel.model) # ug -> UserGroup表 #把当前FilterOption对象,对应的数据库数据,request请求传递给FilterList类,实例化得到一个对应的对象 data_list = FilterList(option, field.rel.model.objects.all(), request) elif isinstance(field, ManyToManyField):#判断时候是多对多类型的字段 # print(field.rel.model) # rm -> Role表 data_list = FilterList(option, field.rel.model.objects.all(), request) else: # print(field.model, self.model_class) #以上都不满足的话,就直接获取自己表的数据 data_list = FilterList(option, field.model.objects.all(), request) filter_list.append(data_list) #把实例化的 FilterList 对象添加到列表中,传递给前端 context = { "result_list":result_list, "list_display":self.list_display, "ygadmin_obj":self, "add_url":add_url, "page_str":page_obj.pager, "action_list":action_list, "filter_list":filter_list, } return render(request, "yg/change_list.html",context)
def deliveryorderdetails(request): context = {} do_id = request.POST['delivery_order_id'] po_id = request.POST['purchase_order_id'] shipping_inst = request.POST['shipping_inst'] staff_id = request.POST['staff_id'] vendor_id = request.POST['vendor_id'] description = request.POST['description'] po = PurchaseOrder.objects.get(purchase_order_id=po_id) staff_info = Person.objects.get(person_id=staff_id) vendor_info = Vendor.objects.get(vendor_id=vendor_id) responses = request.read() print(responses) q = QueryDict(responses) items_id = q.getlist('item_id') print(items_id) items_name = q.getlist('item_name') print(items_name) items_quantity = q.getlist('quantity') print(items_quantity) items_unit_price = q.getlist('unit_price') print(items_unit_price) items_total_price = q.getlist('total_price') print(items_total_price) items = list() i = 0 items_length = len(items_id) grand_total = Decimal(0) while i < items_length: total = Decimal(items_quantity[i]) * Decimal(items_unit_price[i]) item_table = { 'item_name': items_name[i], 'item_id': items_id[i], 'quantity': items_quantity[i], 'unit_price': items_unit_price[i], 'total_price': total } items.append(item_table) i = i + 1 grand_total = grand_total + total print(items) try: # push the data to the database current_time = datetime.datetime.now() print(current_time) do_info = DeliveryOrder(delivery_order_id=do_id, shipping_instructions=shipping_inst, time_created=current_time, total_price=grand_total, person_id=staff_info, description=description, vendor_id=vendor_info, purchase_order_id=po) do_info.save() delivery_order = DeliveryOrder.objects.get(delivery_order_id=do_id) for item in items: item_info = Item.objects.get(item_id=item['item_id']) do_item_info = DeliveryOrderItem(delivery_order_id=delivery_order, item_id=item_info, quantity=item['quantity'], unit_price=item['unit_price'], total_price=item['total_price']) do_item_info.save() # info pass to html context = { 'title': 'Delivery Order Details', 'purchase_order_id': po_id, 'delivery_order_id': do_id, 'staff_id': staff_id, 'vendor_id': vendor_id, 'shipping_inst': shipping_inst, 'rows': items, 'staff_info': staff_info, 'vendor_info': vendor_info, 'grand_total': grand_total, 'time_created': current_time, 'description': description } return render(request, 'DeliveryOrder/deliveryorderdetails.html', context) except IntegrityError: return render(request, 'DeliveryOrder/deliveryorderdetails.html', context)
def reverse_url(request, name, *args, **kwargs): base_url = reverse(name, args=args, kwargs=kwargs) next = request.get_full_path() dic = QueryDict(mutable=True) dic['next'] = next return "{}?{}".format(base_url, dic.urlencode())
def validate_list_not_empty(fieldname, querydict: QueryDict): if not querydict.getlist(fieldname): raise ValidationError(f'must pass some option on filter: {fieldname}')
def __init__(self, get): self.GET = QueryDict(get)
def search(request): pages = all_pages = Page.objects.all().prefetch_related('content_type').specific() q = MATCH_ALL content_types = [] pagination_query_params = QueryDict({}, mutable=True) ordering = None if 'ordering' in request.GET: if request.GET['ordering'] in ['title', '-title', 'latest_revision_created_at', '-latest_revision_created_at', 'live', '-live']: ordering = request.GET['ordering'] if ordering == 'title': pages = pages.order_by('title') elif ordering == '-title': pages = pages.order_by('-title') if ordering == 'latest_revision_created_at': pages = pages.order_by('latest_revision_created_at') elif ordering == '-latest_revision_created_at': pages = pages.order_by('-latest_revision_created_at') if ordering == 'live': pages = pages.order_by('live') elif ordering == '-live': pages = pages.order_by('-live') if 'content_type' in request.GET: pagination_query_params['content_type'] = request.GET['content_type'] try: app_label, model_name = request.GET['content_type'].split('.') except ValueError: raise Http404 try: selected_content_type = ContentType.objects.get_by_natural_key(app_label, model_name) except ContentType.DoesNotExist: raise Http404 pages = pages.filter(content_type=selected_content_type) else: selected_content_type = None if 'q' in request.GET: form = SearchForm(request.GET) if form.is_valid(): q = form.cleaned_data['q'] pagination_query_params['q'] = q # Parse query filters, query = parse_query_string(q, operator='and', zero_terms=MATCH_ALL) # Live filter live_filter = filters.get('live') or filters.get('published') live_filter = live_filter and live_filter.lower() if live_filter in ['yes', 'true']: all_pages = all_pages.filter(live=True) pages = pages.filter(live=True) elif live_filter in ['no', 'false']: all_pages = all_pages.filter(live=False) pages = pages.filter(live=False) # Search all_pages = all_pages.search(query, order_by_relevance=not ordering) pages = pages.search(query, order_by_relevance=not ordering) # Facets if pages.supports_facet: content_types = [ (ContentType.objects.get(id=content_type_id), count) for content_type_id, count in all_pages.facet('content_type_id').items() ] else: form = SearchForm() paginator = Paginator(pages, per_page=20) pages = paginator.get_page(request.GET.get('p')) if request.is_ajax(): return TemplateResponse(request, "wagtailadmin/pages/search_results.html", { 'pages': pages, 'all_pages': all_pages, 'query_string': q, 'content_types': content_types, 'selected_content_type': selected_content_type, 'ordering': ordering, 'pagination_query_params': pagination_query_params.urlencode(), }) else: return TemplateResponse(request, "wagtailadmin/pages/search.html", { 'search_form': form, 'pages': pages, 'all_pages': all_pages, 'query_string': q, 'content_types': content_types, 'selected_content_type': selected_content_type, 'ordering': ordering, 'pagination_query_params': pagination_query_params.urlencode(), })
def purchaseorderdetails(request): context = {} po_id = request.POST['purchase_order_id'] quotation_id = request.POST['quotation_id'] shipping_inst = request.POST['shipping_inst'] vendor_id = request.POST['vendor_id'] description = request.POST['description'] staff_id = request.user.id staff = Person.objects.get(user_id=staff_id) quotation = Quotation.objects.get(quotation_id=quotation_id) vendor_info = Vendor.objects.get(vendor_id=vendor_id) responses = request.read() print(responses) q = QueryDict(responses) items_id = q.getlist('item_id') print(items_id) items_name = q.getlist('item_name') print(items_name) items_quantity = q.getlist('quantity') print(items_quantity) items_unit_price = q.getlist('unit_price') print(items_unit_price) items_total_price = q.getlist('total_price') print(items_total_price) items = list() i = 0 items_length = len(items_id) grand_total = Decimal(0) while i < items_length: total = Decimal(items_quantity[i]) * Decimal(items_unit_price[i]) item_table = { 'item_name': items_name[i], 'item_id': items_id[i], 'quantity': items_quantity[i], 'unit_price': items_unit_price[i], 'total_price': total } items.append(item_table) i = i + 1 grand_total = grand_total + total print(items) # push the Purchase Order data to the database current_time = datetime.datetime.now() print(current_time) po_info = PurchaseOrder(purchase_order_id=po_id, shipping_instructions=shipping_inst, time_created=current_time, total_price=grand_total, person_id=staff, description=description, vendor_id=vendor_info, quotation_id=quotation) po_info.save() # push the Purchase Order item data to the database purchase_order = PurchaseOrder.objects.get(purchase_order_id=po_id) for item in items: item_info = Item.objects.get(item_id=item['item_id']) po_item_info = PurchaseOrderItem(purchase_order_id=purchase_order, item_id=item_info, quantity=item['quantity'], unit_price=item['unit_price'], total_price=item['total_price']) po_item_info.save() #sending email to vendor x = PrettyTable() x.field_names = [ "Item ID", "Item Name", "Quantity", "Unit Price", "Total Price" ] for item in items: x.add_row([ item['item_id'], item['item_name'], item['quantity'], item['unit_price'], item['total_price'] ]) subject = 'PURCHASE ORDER INFORMATION: ' + po_id message = 'This is the Purchase Order Information: \n' + 'Person In Charge: ' + staff.person_name + '\n' + 'Ship to:' + staff.person_address + '\n' + 'Purchase Order Number: ' + po_id + '\n' + 'Quotation ID: ' + quotation.quotation_id + '\n' + 'Time Issued: ' + str( current_time ) + '\n' + 'Vendor ID: ' + vendor_id + '\n' + 'Description: ' + description + '\n' + 'Shipping Instructions: ' + shipping_inst + '\n' + str( x) + '\n' email_from = settings.EMAIL_HOST_USER recipient_list = [ vendor_info.vendor_email, ] send_mail(subject, message, email_from, recipient_list) # info pass to html context = { 'title': 'Purchase Order Details', 'quotation_id': quotation_id, 'purchase_order_id': po_id, 'vendor_id': vendor_id, 'shipping_inst': shipping_inst, 'rows': items, 'staff': staff, 'vendor_info': vendor_info, 'grand_total': grand_total, 'time_created': current_time, 'description': description } return render(request, 'PurchaseOrder/purchaseorderdetails.html', context)
def test01tableView(self): self.createTestMeasurements() self.request.method = 'GET' self.request.GET = QueryDict('') res = json.loads(views.tables(self.request, 1).content.decode('utf-8')) self.assertListEqual(res['header'], [{ 'name': 'DEPTH_FROM' }, { 'name': self.test_meaning_name + '1', 'unit': self.test_unit + '1' }, { 'name': self.test_meaning_name + '2', 'unit': self.test_unit + '2' }, { 'name': self.test_meaning_name + '3', 'unit': 'DICT' }, { 'name': self.test_meaning_name + '4', 'unit': 'DICT' }]) self.assertListEqual(res['data'][0], [100, 0.5, '', '', '']) self.assertListEqual(res['data'][1], [101, '', 1.5, self.test_dict_value + '1', '']) self.assertListEqual(res['data'][2], [102, '', '', '', self.test_dict_value + '2']) meaning = MeaningValue.objects.create( name=self.test_meaning_name + 'a', unit=self.test_unit + 'b', section=MeaningSection.objects.create(name=self.test_section_name + 'c')) RealMeasurement.objects.create(value=self.test_value + 100, meaning=meaning, borehole=Borehole.objects.get(id=1), depth_from=100, depth_to=101, geophysical_depth=99) res = json.loads(views.tables(self.request, 1).content.decode('utf-8')) self.assertListEqual(res['header'], [ { 'name': 'DEPTH_FROM' }, { 'name': self.test_meaning_name + '1', 'unit': self.test_unit + '1' }, { 'name': self.test_meaning_name + '2', 'unit': self.test_unit + '2' }, { 'name': self.test_meaning_name + '3', 'unit': 'DICT' }, { 'name': self.test_meaning_name + '4', 'unit': 'DICT' }, { 'name': self.test_meaning_name + 'a', 'unit': self.test_unit + 'b' }, ]) self.assertListEqual(res['data'][0], [1, '', '', '', '', self.test_value + 100]) self.assertListEqual(res['data'][1], [100, 0.5, '', '', '', '']) self.assertListEqual( res['data'][2], [101, '', 1.5, self.test_dict_value + '1', '', '']) self.assertListEqual(res['data'][3], [102, '', '', '', self.test_dict_value + '2', '']) self.assertEqual(len(res['data']), 4) self.request.GET = QueryDict('stop_depth=101').copy() res = json.loads(views.tables(self.request, 1).content.decode('utf-8')) self.assertListEqual(res['header'], [{ 'name': 'DEPTH_FROM' }, { 'name': self.test_meaning_name + '1', 'unit': self.test_unit + '1' }, { 'name': self.test_meaning_name + '2', 'unit': self.test_unit + '2' }, { 'name': self.test_meaning_name + '3', 'unit': 'DICT' }, { 'name': self.test_meaning_name + 'a', 'unit': self.test_unit + 'b' }]) self.assertListEqual(res['data'][0], [1, '', '', '', self.test_value + 100]) self.assertListEqual(res['data'][1], [100, 0.5, '', '', '']) self.assertListEqual(res['data'][2], [101, '', 1.5, self.test_dict_value + '1', '']) self.assertEqual(len(res['data']), 3) self.request.GET['start_depth'] = 50 res = json.loads(views.tables(self.request, 1).content.decode('utf-8')) self.assertListEqual(res['header'], [{ 'name': 'DEPTH_FROM' }, { 'name': self.test_meaning_name + '1', 'unit': self.test_unit + '1' }, { 'name': self.test_meaning_name + '2', 'unit': self.test_unit + '2' }, { 'name': self.test_meaning_name + '3', 'unit': 'DICT' }]) self.assertListEqual(res['data'][0], [100, 0.5, '', '']) self.assertListEqual(res['data'][1], [101, '', 1.5, self.test_dict_value + '1']) self.assertEqual(len(res['data']), 2) self.request.GET = QueryDict( 'start_depth=50&stop_depth=5000&filter=1&filter=3&strat=3').copy() res = json.loads(views.tables(self.request, 1).content.decode('utf-8')) self.assertListEqual(res['header'], [{ 'name': 'DEPTH_FROM' }, { 'name': self.test_meaning_name + '1', 'unit': self.test_unit + '1' }, { 'name': self.test_meaning_name + '3', 'unit': 'DICT' }]) self.assertListEqual(res['data'][0], [100, 0.5, '']) self.assertListEqual(res['data'][1], [101, '', self.test_dict_value + '1']) self.assertEqual(len(res['data']), 2)