def setUp(self): kwargs1 = {} kwargs2 = {} try: Client._meta.get_field('domain_url') except FieldDoesNotExist: pass else: kwargs1 = {'domain_url': 'test1.test.com'} kwargs2 = {'domain_url': 'test2.test.com'} self.tenant1 = Client(name='test1', schema_name='test1', **kwargs1) self.tenant1.save() self.tenant2 = Client(name='test2', schema_name='test2', **kwargs2) self.tenant2.save() connection.set_tenant(self.tenant1) self.dummy1 = DummyModel.objects.create(name='test1') connection.set_tenant(self.tenant2) self.dummy2 = DummyModel.objects.create(name='test2') connection.set_schema_to_public()
def register(request): serializer = CustomUserSerializer(data=request.data) if serializer.is_valid(): user = serializer.save() user.set_password(serializer.data['password']) user.save() token, _ = Token.objects.get_or_create(user=user) context = { 'key': token.key, } if user.user_type == CLIENT: client = Client(user=user) client.save() context['client_id'] = user.client.pk elif user.user_type == MASTER: salon_id = int(request.data.get('salon_id')) salon = Salon.objects.get(pk=salon_id) master = Master(user=user, salon=salon) # user.save() master.save() context['master_id'] = user.master.pk elif user.user_type == PARTNER: partner = Partner(user=user) partner.save() context['partner_id'] = user.partner.pk if user: user.save() return Response(context) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
def client_create(request): client = Client(email=request.data.get("email"), password=request.data.get("pass"), firstname=request.data.get("fname"), surname=request.data.get("lname"), phone=request.data.get("phone")) client.save() report = {"token": client.token} return Response(report)
def create(self, validated_data): print(validated_data) client = Client(email=validated_data['email'], fullname=validated_data['fullname'], phone=validated_data['phone'], cardno=validated_data['cardno'], password=validated_data['password']) client.save() return client
def addClient(request): if not request.user.is_authenticated(): return HttpResponseRedirect("/") if request.method == 'POST': # If the form has been submitted... form = ClientForm(request.POST) # A form bound to the POST data if form.is_valid(): # All validation rules pass # Process the data in form.cleaned_data firstName = form.cleaned_data['firstName'] middleName = form.cleaned_data['middleName'] lastName = form.cleaned_data['lastName'] dateOfBirth = form.cleaned_data['dateOfBirth'] street = form.cleaned_data['street'] city = form.cleaned_data['city'] stateID = form.cleaned_data['state'] zipCode = form.cleaned_data['zipCode'] phone = form.cleaned_data['phone'] email = form.cleaned_data['email'] clientAddress = Address() clientAddress.street = street clientAddress.city = city theState = State.objects.filter(id=stateID) if len(theState)==1: theState = theState[0] clientAddress.state = theState clientAddress.zipCode = zipCode clientAddress.save() aClient = Client() aClient.firstName = firstName aClient.middleName = middleName aClient.lastName = lastName aClient.dateOfBirth = dateOfBirth aClient.address = clientAddress aClient.phone = phone aClient.email = email aClient.save() return HttpResponseRedirect('/clients/') # Redirect after POST else: form = ClientForm() # An unbound form context = { 'form': form, } return render(request, 'addClient.html', context)
def create(self, validated_data): user_data = validated_data.pop('user') user = UserSerializer.create(UserSerializer(), validated_data=user_data) instance = Client() instance.user = user instance.cpf = validated_data.pop('cpf') instance.birthday = validated_data.pop('birthday') instance.gender = validated_data.pop('gender') instance.phone_number = validated_data.pop('phone_number') instance.save() return instance
def post(self, request, *args, **kwargs): #print('request.GET', request.GET, type(request.GET)) #print('request.data', request.data, type(request.data)) params = request.data # проверка параметров error = None if 'balance' not in params: error = 'Не указан параметр balance' if 'currency' not in params: error = 'Не указан параметр currency' if 'email' not in params: error = 'Не указан параметр email' if 'password' not in params: error = 'Не указан параметр password' if error is not None: res_json = json.dumps({ 'result': 'error', 'error_text': error }, ensure_ascii=False) return HttpResponse(res_json, content_type="application/json") # проверка валюты currency = params['currency'] if not Currency.objects.filter(code=currency).exists(): error = 'Валюта [%s] в системе отсутствует' % currency res_json = json.dumps({ 'result': 'error', 'error_text': error }, ensure_ascii=False) return HttpResponse(res_json, content_type="application/json") # проверка наличия такого клиента email = params['email'] if Client.objects.filter(email=email).exists(): error = 'Клиент с e-mail [%s] уже пристутствует в системе' % email res_json = json.dumps({ 'result': 'error', 'error_text': error }, ensure_ascii=False) return HttpResponse(res_json, content_type="application/json") # создание клиента client = Client() client.email = params['email'] client.password = params['password'] client.token = uuid.uuid1() client.save() # создание счета account = Account() account.client = client account.currency_id = params['currency'] account.amount = params['balance'] account.save() res_json = json.dumps({'result': 'ok'}, ensure_ascii=False) return HttpResponse(res_json, content_type="application/json")
def test_when_allowed_roles_access_token_exists(self): client = Client.create_client('test', 'test', 'admin') access_token = client.generate_access_token() self.client.cookies['access_token'] = access_token response = self.client.get(self.url) self.assertEqual(response.status_code, 200) self.assertTemplateUsed(response, 'website/common_daftar_page.html')
def test_when_access_token_exist_but_unallowed_roles(self): client = Client.create_client('test', 'test', 'apotek') access_token = client.generate_access_token() self.client.cookies['access_token'] = access_token response = self.client.get(self.url) self.assertEqual(response.status_code, 403) self.assertTemplateUsed(response, 'website/login.html')
def test_when_access_token_exist_and_valid(self): client = Client.create_client('test', 'test', 'loket') access_token = client.generate_access_token() self.client.cookies['access_token'] = access_token response = self.client.get(self.url) self.assertEqual(response.status_code, 200) self.assertTemplateUsed(response, 'website/mainpage.html')
def wrapper(request, *args, **kwargs): try: token = request.COOKIES['access_token'] user = Client.authenticate_access_token(token) check_if_user_has_role(user, roles) return func(request, *args, **kwargs) except Exception as e: response = {'response': 'Exception ' + e.__str__()} return render(request, 'website/login.html', status=403)
def handle(self, *args, **options): Client.objects.all().delete() print('Load client') c = Client() c.name = 'wezom' c.secret = '123' c.save()
def update_client(request): status = 'Error' address = '' phone = '' if request.method == 'POST': json_client = json.loads(request.body.decode('utf-8')) print json_client username = json_client.get('username') firstname = json_client.get('firstname') lastname = json_client.get('lastname') email = json_client.get('email') address = json_client.get('address') phone = json_client.get('phone') try: userModel = User.objects.get(username=username) userModel.first_name = firstname userModel.last_name = lastname userModel.email = email userModel.save() try: client = Client.objects.get(user__username=username) client.address = address client.phone = phone client.active = 1 client.save() except ObjectDoesNotExist: if(address <> "" or phone <> ""): client = Client() client.user = userModel client.address = address client.phone = phone client.active = 1 client.save() else: print 'No existe info adicional de cliente.' status = 'OK' except ObjectDoesNotExist: status = 'Usuario no existe.' else: status = 'Metodo no POST.' return JsonResponse({'status': status})
class CeleryTasksTests(TenantTestCase): @classmethod def setUpClass(cls): pass @classmethod def tearDownClass(cls): pass def setUp(self): kwargs1 = {} kwargs2 = {} try: Client._meta.get_field('domain_url') except FieldDoesNotExist: pass else: kwargs1 = {'domain_url': 'test1.test.com'} kwargs2 = {'domain_url': 'test2.test.com'} self.tenant1 = Client(name='test1', schema_name='test1', **kwargs1) self.tenant1.save() self.tenant2 = Client(name='test2', schema_name='test2', **kwargs2) self.tenant2.save() connection.set_tenant(self.tenant1) self.dummy1 = DummyModel.objects.create(name='test1') connection.set_tenant(self.tenant2) self.dummy2 = DummyModel.objects.create(name='test2') connection.set_schema_to_public() def tearDown(self): connection.set_schema_to_public() def test_basic_model_update(self): # We should be in public schema where dummies don't exist. for dummy in self.dummy1, self.dummy2: # Test both async and local versions. with self.assertRaises(DummyModel.DoesNotExist): update_task.apply_async(args=(dummy.pk, 'updated-name')) with self.assertRaises(DummyModel.DoesNotExist): update_task.apply(args=(dummy.pk, 'updated-name')) connection.set_tenant(self.tenant1) update_task.apply_async(args=(self.dummy1.pk, 'updated-name')) self.assertEqual(connection.schema_name, self.tenant1.schema_name) # The task restores the schema from before running the task, so we are # using the `tenant1` tenant now. model_count = DummyModel.objects.filter(name='updated-name').count() self.assertEqual(model_count, 1) connection.set_tenant(self.tenant2) model_count = DummyModel.objects.filter(name='updated-name').count() self.assertEqual(model_count, 0) def test_task_retry(self): # Schema name should persist through retry attempts. connection.set_tenant(self.tenant1) update_retry_task.apply_async(args=(self.dummy1.pk, 'updated-name')) model_count = DummyModel.objects.filter(name='updated-name').count() self.assertEqual(model_count, 1) def test_restoring_schema_name(self): update_task.apply_async( args=(self.dummy1.pk, 'updated-name'), kwargs={'_schema_name': self.tenant1.schema_name} ) self.assertEqual(connection.schema_name, get_public_schema_name()) connection.set_tenant(self.tenant1) update_task.apply_async( args=(self.dummy2.pk, 'updated-name'), kwargs={'_schema_name': self.tenant2.schema_name} ) self.assertEqual(connection.schema_name, self.tenant1.schema_name) connection.set_tenant(self.tenant2) # The model does not exist in the public schema. with self.assertRaises(DummyModel.DoesNotExist): update_task.apply_async( args=(self.dummy2.pk, 'updated-name'), kwargs={'_schema_name': get_public_schema_name()} ) self.assertEqual(connection.schema_name, self.tenant2.schema_name)
def add_user(request): if request.user.is_authenticated: if request.is_ajax() and request.method == 'POST': name = request.POST['name'] surname = request.POST['surname'] email = request.POST['email'].lower() status = request.POST['status'] username = request.POST['username'] password = request.POST['password'] client = Client.objects.get(account=request.user) if client.status != 'a': status = 'user' if len(User.objects.filter(username=username)) != 0: result = { 'status': 'Not accepted', 'message': 'Existing username' } return return_json_response(result) elif len(Client.objects.filter(email=email)) != 0: result = { 'status': 'Not accepted', 'message': 'Existing email' } return return_json_response(result) else: html_message = f'Congratulations, {name}!<br><br>\ Somebody (probably you) registered you in our\ <a href = "https://127.0.0.1:8000/" style = "color: blue; text-decoration: none;">small developing site</a><br><br>\ Your username: {username}<br>\ Your password: {password}<br><br>\ Enjoy!' send_mail('Account verification', 'Lol', 'Kek', [email], html_message=html_message) new_user = User.objects.create_user(username=username, password=password) if status == 'admin': new_user.is_staff = True new_user.save() if not request.user.is_authenticated: auth.login(request, new_user) new_client = Client(name=name, surname=surname, email=email, status=status[0], account=new_user) new_client.save() print('\n\nNew client was created\n\n') result = {'status': 'accepted', 'message': 'OK'} return return_json_response(result, 201) else: result = {'status': 'Not accepted', 'message': 'Wrong method'} return return_json_response(result, 400) else: result = { 'status': 'Not accepted', 'message': 'Authentication required' } return return_json_response(result, 401)
def add_user(request): if request.is_ajax() and request.method == 'POST': name = request.POST['name'] email = request.POST['email'].lower() status = request.POST['status'] username = request.POST['username'] password = request.POST['password'] if request.user.is_authenticated: client = Client.objects.get(account=request.user) if client.status != 'a': status = 'user' else: status = 'user' if len(User.objects.filter(username=username)) != 0: result = { 'status': 'Not accepted', 'message': 'This username is already taken' } return return_json_response(result) elif len(Client.objects.filter(email=email)) != 0: result = { 'status': 'Not accepted', 'message': 'This email is already taken' } return return_json_response(result) else: html_message = f'Congratulations, {name}!<br><br>\ Somebody (probably you) registered you in our\ <a href = "http://pdf.truckdispatch.pro" style = "color: blue; text-decoration: none;">site</a><br><br>\ Your username: {username}<br>\ Your password: {password}<br><br>\ Please send us your user experience to this email [email protected] most reasonable things will be implemented ASAP' send_mail('Scan PDF Account Registration', '', '', [email], html_message=html_message) new_user = User.objects.create_user(username=username, password=password) if status == 'admin': new_user.is_staff = True new_user.is_superuser = True new_user.save() if not request.user.is_authenticated: auth.login(request, new_user) new_client = Client( name=name, email=email, status=status[0], account=new_user, ) new_client.save() print('\n\nNew client was created\n\n') result = {'status': 'Accepted', 'message': 'OK'} return return_json_response(result, 201) else: result = {'status': 'Not accepted', 'message': 'Wrong method'} return return_json_response(result, 400)
def get_client(request): access_token = request.COOKIES.get('access_token') client = Client.authenticate_access_token(access_token) return client
SALES_COLUMN_IDX_FOR_INVOICE) == 'Invoice': break startRow += 1 for rowIdx in range(startRow, sheet.nrows): if sheet.cell_value(rowIdx, 0) == '': break if sheet.cell_value(rowIdx, SALES_COLUMN_IDX_FOR_INVOICE) == 'Invoice': name = sheet.cell_value(rowIdx, SALES_COLUMN_IDX_FOR_CLIENT_NAME) if (name in dic): client = dic[name] else: client = Client( name=sheet.cell_value(rowIdx, SALES_COLUMN_IDX_FOR_CLIENT_NAME), region=random.choice(regions), salesman=random.choice(salesmans), ) dic[name] = client clients.append(client) time_tuple = xlrd.xldate_as_tuple( sheet.cell_value(rowIdx, SALES_COLUMN_IDX_FOR_DATE), 0) date = datetime.datetime(*time_tuple) else: name = sheet.cell_value(rowIdx, SALES_COLUMN_IDX_FOR_PRODUCT_NAME) if name in ProductDic: product = ProductDic[name] else: product = Product(name=sheet.cell_value(