How to use request_operation method in localstack

Best Python code snippet using localstack_python

Customer.py

Source:Customer.py Github

copy

Full Screen

1#2# Customer.py3#4# Marco Ermini - March 2021 for ASU CSE531 Course5# Do not leech!6# Built with python 3.8 with GRPC and GRPC-tools libraries; may work with other Python versions7'''Implementation of a banking's branches/customers RPC synchronisation using GRPC, multiprocessing and Python8Customer Class'''9import time10import datetime11import multiprocessing12#import array13import json14from concurrent import futures15from Util import setup_logger, MyLog16import grpc17import banking_pb218import banking_pb2_grpc19#from Main import get_operation, get_operation_name, get_result_name20ONE_DAY = datetime.timedelta(days=1)21logger = setup_logger("Customer")22class Customer:23 def __init__(self, ID, events):24 # unique ID of the Customer25 self.id = ID26 # events from the input27 self.events = events28 # a list of received messages used for debugging purpose29 self.recvMsg = list()30 # pointer for the stub31 self.stub = None32 # Create stub for the customer, matching them with their respective branch33 #34 def createStub(self, Branch_address, THREAD_CONCURRENCY):35 """Start a client (customer) stub."""36 37 MyLog(logger, f'Initializing customer stub to branch stub at {Branch_address}')38 39 self.stub = banking_pb2_grpc.BankingStub(grpc.insecure_channel(Branch_address))40 client = grpc.server(futures.ThreadPoolExecutor(max_workers=THREAD_CONCURRENCY,),)41 #banking_pb2_grpc.add_BankingServicer_to_server(Customer, client)42 client.start()43 # Iterate through the list of the customer events, sends the messages,44 # and output to the JSON file45 #46 def executeEvents(self, output_file):47 """Execute customer events."""48 49 # DEBUG50 #MyLog(logger,f'Executing events for Customer #{self.id}')51 52 record = {'id': self.id, 'recv': []}53 for event in self.events:54 request_id = event['id']55 request_operation = get_operation(event['interface'])56 request_amount = event['money']57 response = self.stub.MsgDelivery(58 banking_pb2.MsgDeliveryRequest(59 S_ID=request_id,60 OP=request_operation,61 Amount=request_amount,62 D_ID=self.id,63 )64 )65 MyLog(logger,66 f'Customer {self.id} sent request {request_id} to Branch {response.ID} '67 f'interface {get_operation_name(request_operation)} result {get_result_name(response.RC)} '68 f'money {response.Amount}')69 values = {70 'interface': get_operation_name(request_operation),71 'result': get_result_name(response.RC),72 }73 if request_operation == banking_pb2.QUERY:74 values['money'] = response.Amount75 record['recv'].append(values)76 if record['recv']:77 # DEBUG78 #MyLog(logger,f'Writing JSON file on #{output_file}')79 with open(f'{output_file}', 'a') as outfile:80 json.dump(record, outfile)81 outfile.write('\n')82 # Spawn the Customer process client. No need to bind to a port here; rather, we are connecting to one.83 #84 def Run_Customer(self, Branch_address, output_file, THREAD_CONCURRENCY):85 """Start a client (customer) in a subprocess."""86 # DEBUG87 #MyLog(logger,f'Processing Customer #{self.id} with Events:' )88 #for e in self.events:89 # MyLog(logger,f' #{e["id"]} = {e["interface"]}, {e["money"]}' )90 91 MyLog(logger,f'Running client customer #{self.id} connecting to server {Branch_address}...')92 Customer.createStub(self, Branch_address, THREAD_CONCURRENCY)93 Customer.executeEvents(self, output_file)94 # Wait one day until keypress95 #try:96 # while True:97 # time.sleep(ONE_DAY.total_seconds())98 #except KeyboardInterrupt:99 # server.stop(None)100 101 MyLog(logger,f'Client customer #{self.id} connecting to server {Branch_address} exiting successfully.')102# Utility functions, used for readability103#104def get_operation(operation):105 """Returns the message type from the operation described in the input file."""106 if operation == 'query':107 return banking_pb2.QUERY108 if operation == 'deposit':109 return banking_pb2.DEPOSIT110 if operation == 'withdraw':111 return banking_pb2.WITHDRAW112def get_operation_name(operation):113 """Returns the operation type from the message."""114 if operation == banking_pb2.QUERY:115 return 'QUERY'116 if operation == banking_pb2.DEPOSIT:117 return 'DEPOSIT'118 if operation == banking_pb2.WITHDRAW:119 return 'WITHDRAW'120def get_result_name(name):121 """Return state of a client's operation."""122 if name == banking_pb2.SUCCESS:123 return 'SUCCESS'124 if name == banking_pb2.FAILURE:125 return 'FAILURE'126 if name == banking_pb2.ERROR:...

Full Screen

Full Screen

1.py

Source:1.py Github

copy

Full Screen

...6Если пользователь вводит неверный знак (не '0', '+', '-', '*', '/'), то программа должна сообщать ему об ошибке7и снова запрашивать знак операции. Также сообщать пользователю о невозможности деления на ноль, если он ввел 08в качестве делителя.9"""10def request_operation():11 allow_operations = ['0', '+', '-', '*', '/']12 operation = str(input('знак операции или 0 для прекращения: '))13 if operation not in allow_operations:14 print(f'-- допустимые значения операции {allow_operations}, еще раз --')15 operation = request_operation()16 return operation17while True:18 dig1, dig2 = map(int, input('введите два числа: ').split())19 operation = request_operation()20 if operation == '0':21 break22 elif operation == '/' and dig2 == 0:23 print('нельзя делить на ноль!')24 else:25 # if operation == '+':26 # res = dig1 + dig227 # elif operation == '-':28 # res = dig1 - dig229 # elif operation == '*':30 # res = dig1 * dig231 # else:32 # res = dig1 / dig233 res = eval(f'{dig1} {operation} {dig2}')...

Full Screen

Full Screen

youtube_api.py

Source:youtube_api.py Github

copy

Full Screen

...38 }39 request_operation = dic.get(method, None)40 if request_operation:41 if method == "get":42 response = request_operation(url, params=params, headers=headers)43 elif not file:44 response = request_operation(url, params=params, headers=headers,45 json=body)46 else:47 response = request_operation(url, params=params, headers=headers,48 json=body, files=file)49 if response_file:50 save_file(response_file, response)51 return response52if __name__ == "__main__":53 scope = ['https://www.googleapis.com/auth/youtube',54 'https://www.googleapis.com/auth/youtube.force-ssl']55 client_secret_file = 'client_secret.json'56 info = read_config()57 credentials = get_credential_token()58 # For authentication59 info['headers']['Authorization'] = 'Bearer {}'.format(credentials)60 response = request(info['method'],61 info['url'],...

Full Screen

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run localstack automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful