def users(request): if request.method == 'GET': users = User.objects.all() return Response(json.dumps([{'username': user.username} for user in users])) elif request.method == 'POST': user = User.objects.create(username='******') return Response(json.dumps({'username': user.username}))
def enter(request): if request.method == 'POST': login = request.POST.get('login') password = request.POST.get('password') try: enter = Users.objects.get(login=login, password=password) except: return Response("Not Exist") return Response("{0}:{1}".format(enter.admin, enter.id))
def post(self, request): body_unicode = request.body.decode('utf-8') body = json.loads(body_unicode) if (not body['name'] or not body['website']): return Response('The correct fields were not available', status=400) # Save to Django database expert = Expert(name=body['name'], website=body['website']) expert.save() # Get updated data to return experts = Expert.objects.all() serializer = ExpertSerializer(experts, many=True) return Response(json.dumps(serializer.data))
def userProfileView(request, un): tasks = User_Profile.objects.filter(username=un) serializer = user_profile_serializer(tasks, many=True) #problem pos = Post.objects.filter(username=un) serializer2 = PostSerializer(pos, many=True) #solution sol = Solution.objects.filter(username=un) serializer3 = SolutionSerializer(sol, many=True) #user_personal personal = User_Personal.objects.filter(username=un) serializer4 = user_personal_serializer(personal, many=True) #user_professional professional = User_Professional.objects.filter(username=un) serializer5 = user_professional_serializer(professional, many=True) #email em = CustomUser.objects.filter(id=un) serializer6 = LoginSerializer(em, many=True) content = {"email": serializer6.data[0].get('email')} Serializer_list = [ serializer.data, serializer2.data, serializer3.data, serializer4.data, serializer5.data, content ] return Response(Serializer_list, safe=False) # returns list of json
def fournisseurs(self, request, pk=None, *args, **kwargs): if request.method == 'GET': """ LIST ALL PROVIDERS OF AN USER """ queryset = Fournisseur.objects.filter(id_user=pk) if not queryset: return Response('[]') serializer = UserFournisseurDetailSerializer(queryset, many=True) return Response(json.dumps(serializer.data[0])) elif request.method == 'POST': """ ADD A PROVIDER TO AN USER """ data = request.data.copy() data['id'] = pk serializer = UserFournisseurSerializer(data=data) serializer.is_valid(raise_exception=True) serializer.save() return Response(json.dump(serializer.data[0]), status=status.HTTP_201_CREATED)
def giveFile(req): if req.method == 'POST': file = FILE() file.directions = 'Colonko_Server/static/file/' file.file_name = req.FILES['sendFile'] file.file_clear_name = file.file_name.name #print(file.file_name.name) file.save() return Response("200(Ok)")
def post(self, request): data = json.loads(request.body) for path in data: if not path.get('ignore'): name = path.get('name') tree = Tree.objects.get(name=name) TreePath.objects.filter(tree=tree).delete() self.build_path(path, tree) return Response({})
def solutionSubmissionView(request): pid = request.POST.get("problemId") serializer = SolutionSerializer(data=request.data) if serializer.is_valid(): serializer.save() c = (serializer.data["problemId"]) d = Post.objects.get(problemId=c) d.sol_count += 1 d.save() return Response(serializer.data)
def NetworkGivenResult(request): #все что ниже это заглушки if request.method == 'POST': length = request.POST.get('length') array_value_param = [] for i in range(int(length)): array_value_param.append(request.POST.get('param_{0}'.format(i))) return Response('{0}'.format(array_value_param))
def get(self, request, name): """ Get tree. """ tree = get_object_or_404(Tree, name=name) root_path = tree.start_node.children.filter(tree=tree) dicts = [] for n in root_path: result = path_to_json(n, tree) if result: dicts.append(result) return Response(dicts, safe=False)
def registration(request): if request.method == 'POST': person = Users() person.login = request.POST.get('login') person.password = request.POST.get('password') person.admin = request.POST.get('admin') person.save() return Response("sucess")
def change_password(self, request, pk=None): """ CHANGE THE PASSWORD OF THE USER """ usr = User.objects.filter(id_user=pk) pwd = request.query_params.get('pwd') usr.set_password(pwd) try: usr.save() return Response(json.dumps({'status': 'password set'})) except: error = "Une erreur est survenue" return RESTResp({'error': error}, status=status.HTTP_400_BAD_REQUEST)
def File_exel(request): if request.method == 'POST': id_network = request.POST.get('id_network') network = NETWORKS.objects.get(id=id_network) files = FILE_EXEL() files.id_network = network files.file = request.FILES['sender_file_exel'] files.save() return Response('success')
def NetworkTeaching(request): if request.method == 'POST': id_networks = request.POST.get('id_network') network = NETWORKS.objects.get(id=id_networks) file = FILE_EXEL.objects.get(id_network=id_networks) params = PARAMS.objects.get(id_network=id_networks) user = network.id_admin phase = 'train' #нужно будит придумать как разделять запуски train и test n_hiddens = params.amount_params n_layers = params.amount_layers f_activation = params.name_function data_path = os.path.join( os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "{0}".format(file.file)) #target_column = params.amount_params max_seconds = params.max_time min_loss = params.accuracy task_type = params.classs output_size = params.amount_exit_class seed = 0 verbose = True print(' output_size={0} \n n_layers = {1} \n f_activation = {2} \n data_path = {3} '\ .format(output_size,n_layers,f_activation,data_path)) builder = PipelineBuilder() # Train builder.set_model(output_size, n_hiddens, n_layers, f_activation, task_type) builder.set_dataset(data_path) #, args.target_column) #weights_filename = 'username' + 'netname and idUser' + '.pth' #TODO weights_filename = '{0}{1}{2}.pth'.format(user.login, params.name, user.id) #logs_filename = 'username' + 'netname' + '.csv' #TODO logs_filename = '{0}{1}{2}.csv'.format(user.login, params.name, user.id) builder.set_filenames(weights_filename, logs_filename) builder.build() if phase == 'train': builder.train(max_seconds, min_loss, seed, verbose) elif phase == 'test': builder.test() else: print('Unknown phase!') return Response('{0}'.format(data_path))
def Text(request): if request.method == 'POST': id_network = request.POST.get('id_network') network = NETWORKS.objects.get(id=id_network) descriptions = DESCRIPTIONS() descriptions.id_network = network descriptions.short_text = request.POST.get('short_text') descriptions.long_text = request.POST.get('long_text') descriptions.save() return Response('success')
def get_response(request): # 第一种创建response对象 # response = Response('我就是想测试响应!') # response = Response('<xml><name>sdfsd</name></xml>', content_type='text/xml') # 第二种创建response对象 # 创建一个响应对象 response = Response() # response.write('<p>aaaaaaaaaa</p>') # response.write('<p>bbbbbbbbbb</p>') # response.write('<p>cccccccccc</p>') # 测试图片展示 # # 设置响应类型 # response['content-type'] = 'image/png' # # 设置响应的状态码 # response.status_code = 404 # with open('111.png', 'rb') as f: # # 读取文件内容 # fileInfo = f.read() # # 设置响应正文 # response.content = fileInfo my_data = '' # 测试表格 # 可以加一些业务逻辑 比如 判断会员是否已经购买当前资源,或会员是否登录 with open('1902.xlsx', 'rb') as f: # 读取文件内容 my_data = f.read() response = Response(my_data, content_type='application/vnd.ms-excel') response['Content-Disposition'] = 'attachment; filename="foo.xls"' # 设置编码 # response.charset = 'utf-8 ' return response
def clients(self, request, pk=None, *args, **kwargs): if request.method == 'GET': """ LIST ALL CUSTOMERS OF AN USER """ # SELECT userclients.id_client, concat(firstname, " ", lastname) as nom # FROM clients # INNER JOIN invoicebook_user on userclients.id = invoicebook_user.id # WHERE invoicebook_user.id=1 queryset = Client.objects.filter(id_user=pk) if not queryset: return Response('[]') serializer = UserClientDetailSerializer(queryset, many=True) return Response(json.dumps(serializer.data[0])) elif request.method == 'POST': """ ADD A CUSTOMER TO AN USER """ data = request.data.copy() data['user_id'] = pk serializer = UserClientSerializer(data=data) serializer.is_valid(raise_exception=True) serializer.save() queryset = Client.objects.filter(lastname=data['lastname'], firstname=data['firstname']) return Response(json.dumps(serializer.data[0]), status=status.HTTP_201_CREATED)
def login_token(self, request, *args, **kwargs): """ AUTHENTICATE AN USER W/ TOKEN """ token = request.query_params.get('token') try: decoded_payload = jwt_decode_handler(token) id_user = decoded_payload['user_id'] queryset = User.objects.filter(id=id_user) if queryset: serializer = UserLoginSerializer(queryset, many=True) return Response(serializer.data) else: error = "Invalid token" return RESTResp({'error': error}, status=status.HTTP_404_NOT_FOUND) except: error = "Invalid token" return RESTResp({'error': error}, status=status.HTTP_404_NOT_FOUND)
def Comment(request): if request.method == 'POST': id_network = request.POST.get('id_network') network = NETWORKS.objects.get(id=id_network) lengnth = request.POST.get('length') for i in range(int(lengnth)): comments = COMMENTS() comments.id_network = network comments.number_param = i comments.comment = request.POST.get('comment_{0}'.format(i)) comments.save() return Response('success')
def AllNetwork(request): networks = NETWORKS.objects.all() listNetwork = [] for net in networks: name = PARAMS.objects.get(id_network=net.id).name short = DESCRIPTIONS.objects.get(id_network=net.id).short_text longs = DESCRIPTIONS.objects.get(id_network=net.id).long_text comment = COMMENTS.objects.filter(id_network=net.id) listComment = [] for com in comment: listComment.append(com.comment) dictin = {\ 'id' : net.id , 'name' : name ,'created' : net.id_admin.login ,\ 'short_text':short, 'long_text':longs, 'comments':listComment} listNetwork.append(dictin) return Response(json.dumps(listNetwork))
def makeDataMarkets(req): if req.method == 'POST': data = DataMarket() data.id_station = req.POST.get("id_station") #получаю текущую дату current_data = datetime.now() data.year = str(current_data.year) data.month = str(current_data.month) data.day = str(current_data.day) data.hours = str(current_data.hour) data.minutes = str(current_data.minute) data.seconds = str(current_data.second) data.save() return Response("200(Ok)")
def login(self, request, *args, **kwargs): """ AUTHENTICATE AN USER W/O TOKEN """ email = request.query_params.get('email') pwd = request.query_params.get('pwd') serializer = authenticate(username=email, password=pwd) queryset = User.objects.filter(email=email) if queryset: user = queryset.get() if serializer is not None: login(request, serializer) user.token = self.create_token(user) queryset = set() queryset.add(user) serializer = UserLoginGetTokenSerializer(queryset, many=True) update_last_login(self, user=user) return Response(json.dumps(serializer.data[0])) else: error = "Credential error : your username or password may be wrong" return RESTResp({'error': error}, status=status.HTTP_401_UNAUTHORIZED) else: error = "Credential error : your username or password may be wrong" return RESTResp({'error': error}, status=status.HTTP_401_UNAUTHORIZED)
def KakaoPay(request): url = "https://kapi.kakao.com/v1/payment/ready" data = request.POST.get("data") data_dic = literal_eval(data) name = data_dic['name'] total_fee = data_dic['total_fee'] size = data_dic['size'] user_name = data_dic['user_name'] now = datetime.now() formatted_date = now.strftime('%Y%m%d%H%M%S') payload = "cid=TC0ONETIME&partner_order_id=1001&partner_user_id=gorany&item_name=" + name + "&quantity=" + size + "&total_amount=" + total_fee + "&tax_free_amount=0&approval_url=http://172.16.16.136:8000/KakaoPaySuccess/?random=" + formatted_date + user_name + "&cancel_url=http://172.16.16.136:8000/KakaoPayCancel/&fail_url=http://172.16.16.136:8000/KakaoPayFail/" payload.encode('UTF-8') headers = { 'Authorization': 'KakaoAK 07bd56b63267b53895005b8792088d79', 'Content-Type': 'application/x-www-form-urlencoded', 'Content-Type': 'application/x-www-form-urlencoded' } response = requests.request("POST", url, headers=headers, data=payload.encode('UTF-8')) json_string = response.text.encode('utf8') str_json = json_string.decode('utf-8') dict_json = json.loads(str_json) tid = dict_json['tid'] #인증 쌍 만들기 random = formatted_date + user_name result = forpay(random_no=random, tid=tid) result.save() request.session['tid'] = tid print(tid, "33333333333333", request.session.get('tid')) return Response(response)
def NetworkParams(request): if request.method == 'POST': id_admin = request.POST.get('id_admin') network = NETWORKS() network.id_admin = Users.objects.get(id=id_admin) network.save() params = PARAMS() params.id_network = network params.name = request.POST.get('name') params.amount_params = request.POST.get('amount_params') params.amount_network = request.POST.get('amount_network') params.amount_layers = request.POST.get('amount_layers') params.name_function = request.POST.get('name_function') params.accuracy = request.POST.get('accuracy') params.max_time = request.POST.get('max_time') params.classs = request.POST.get('classs') params.amount_exit_class = request.POST.get('amount_exit_class') params.save() return Response('{0}'.format(network.id))
def create(self, request, *args, **kwargs): """ CREATE A NEW USER """ username=request.query_params.get('username') email = request.query_params.get('email') pwd = request.query_params.get('password') serializer = User.objects.create_user(username=username, email=email, password=pwd) serializer.last_name = request.query_params.get('last_name') serializer.first_name = request.query_params.get('first_name') try: serializer.save() queryset = User.objects.filter(email=email) user = queryset.get() user.token = self.create_token(user) queryset = set() queryset.add(user) group = Group.objects.get(name='IsAuthenticated') user.groups.add(group) serializer = UserLoginGetTokenSerializer(queryset, many=True) mkdir(path.join(BASE_DIR, "media/" + user.username)) return Response(json.dumps(serializer.data[0]), status=status.HTTP_201_CREATED) except IntegrityError as exception: if "unique_email" in str(exception): error = "This email address already exist" return RESTResp({'error': error}, status=status.HTTP_409_CONFLICT)
def Forgot(request): return Response( "<h1><b>Page 404 Not Found</h1></b><br>The Email Service is Under Development<br>Sorry for the Inconvenience" )
def list(self, request): """ LIST ALL USERS """ queryset = User.objects.all() serializer = UserSerializer(queryset, many=True) return Response(json.dumps(serializer.data))
def retrieve(self, request, pk=None): """ GET AN USER PROFILE BY ID """ queryset = User.objects.all() user = get_object_or_404(queryset, pk=pk) serializer = UserSerializer(user) return Response(json.dumps(serializer.data))
def names(self, request, *args, **kwargs): """ GET ALL USERS NAMES """ queryset = User.objects.all() serializer = NomSerializer(queryset, many=True) return Response(serializer.data)
def index(request): return Response("<h1 align = 'center'>All works</h1>")