def generateDummyData(self): brandsList = [] for brandDict in TempoDict.brands: brand = user_pb2.Brand( brand_name=brandDict['brand_name'], type=brandDict['type'] ) brandsList.append(brand) user = user_pb2.User( username='******', userID='000', type=user_pb2.User.MANAGER, brands=brandsList ) self.table('users').put(user) brandsList = [] for brandDict in TempoDict.brands2: brand = user_pb2.Brand( brand_name=brandDict['brand_name'], type=brandDict['type'] ) brandsList.append(brand) user = user_pb2.User( username='******', userID='111', type=user_pb2.User.MANAGER, brands=brandsList ) self.table('users').put(user) brandsList = [] for brandDict in TempoDict.brands3: brand = user_pb2.Brand( brand_name=brandDict['brand_name'], type=brandDict['type'] ) brandsList.append(brand) user = user_pb2.User( username='******', userID='222', type=user_pb2.User.MANAGER, brands=brandsList ) self.table('users').put(user) brandsList = [] for brandDict in TempoDict.brands4: brand = user_pb2.Brand( brand_name=brandDict['brand_name'], type=brandDict['type'] ) brandsList.append(brand) user = user_pb2.User( username='******', userID='333', type=user_pb2.User.MANAGER, brands=brandsList ) self.table('users').put(user)
def updateUser(): updateUserRequest = user_pb2.UpdateUserRequest() updateUserRequest.ParseFromString(request.get_data()) user = dynamoDbHelper.table('users').get( {'username': updateUserRequest.username}, user_pb2.User()) brands = user.brands finalBrands = [] for brand in brands: if brand in updateUserRequest.brands_to_remove: continue if brand not in updateUserRequest.brands_to_add: finalBrands.append(brand) for brand in updateUserRequest.brands_to_add: finalBrands.append(brand) dynamoDbHelper.table('users') \ .update({ 'username': "******" }, finalBrands) updatedUser = dynamoDbHelper.table('users') \ .get({ 'username': "******" }, user_pb2.User()) return user_pb2.UpdateUserResponse(user=updatedUser).SerializeToString()
def run(): time.sleep(15) channel = grpc.insecure_channel('server:50051') user_probuf_list = [] stub = user_pb2_grpc.UserServiceStub(channel) for i in range(1, 11): # read json data and convert into dictionary json_file = open('users/{}.json'.format(i)) json_str = json_file.read() json_data = json.loads(json_str) # populate the probuf list by converting json items into probuf user_probuf_list.clear() for j in range(len(json_data)): user_probuf_list.append( user_pb2.User(id=json_data[j]["id"], first_name=json_data[j]["first_name"], last_name=json_data[j]["last_name"], email=json_data[j]["email"], gender=json_data[j]["gender"], ip_address=json_data[j]["ip_address"], user_name=json_data[j]["user_name"], agent=json_data[j]["agent"], country=json_data[j]["country"])) for x in user_probuf_list: #print(x.email) response = stub.Add(x) print("Message from the server: {} ".format(response.repl_msg)) close(channel)
def addUser(): addUserRequest = user_pb2.AddUserRequest() addUserRequest.ParseFromString(request.get_data()) user = user_pb2.User(username=addUserRequest.username, userID=addUserRequest.user_id, type=addUserRequest.user_type, brands=addUserRequest.brands) dynamoDbHelper.table('users') \ .put(user) addedUser = dynamoDbHelper.table('users') \ .get({ 'username': addUserRequest.username }, user_pb2.User()) return user_pb2.AddUserResponse(user=addedUser).SerializeToString()
def create_default_user(user_id): pb_object = user_pb2.User() pb_object.id = user_id pb_object.last_signing_time.CopyFrom(create_default_time()) pb_object.today_study_date = 0 pb_object.last_studied_word_id = -1 pb_object.today_studying_words_index = 0 pb_object.today_testing_words_index = 0 return pb_object
def GetUserById(self, req, ctx): user_id = req.user_id user = User.get_by_id(user_id, _id=False) if user is None: return user_pb2.Empty() res = user_pb2.User(**user) return res
def getCurrentUser(): getCurrentUserRequest = user_pb2.GetCurrentUserRequest() getCurrentUserRequest.ParseFromString(request.get_data()) user = dynamoDbHelper.table('users') \ .get({ 'username': getCurrentUserRequest.username }, user_pb2.User()) return user_pb2.GetCurrentUserResponse(user=user).SerializeToString()
def GetUserList(self, req, ctx): user_list = [] retrive = User.get_all({}, _id=False) if len(retrive) < 1: return user_pb2.Empty() for user in retrive: user_list.append(user_pb2.User(**user)) res = user_pb2.UserList(users=user_list) return res
def GetUserList(self, req, ctx): usr_list = [] if not req.user_list: return user_pb2.Empty() for usr in user.get_user_list(): usr_list.append(user_pb2.User(first_name=usr['first_name'],last_name=usr['last_name'],\ email=usr['email'],age=usr['age'])) res = user_pb2.UserList(users=usr_list) return res
def getUser(self, request, context): user_id = request.id if str(user_id) not in users: return user_pb2.UserResponse(error=True, message="not found") user = users[str(user_id)] result = user_pb2.User() result.id = user["id"] result.name = user["name"] return user_pb2.UserResponse(error=False, user=result)
async def hello(websocket, path): buf = await websocket.recv() l = (buf[0] << 24) + (buf[1] << 16) + (buf[2] << 8) + buf[3] print('l=', l) format = ">%us" % l data = struct.unpack(format, buf[4:]) print(data) user = user_pb2.User() user.ParseFromString(buf[4:]) print("服务器收到名字, name=", user.name) greeting = f"I received!" await websocket.send(greeting) print(f"> {greeting}")
async def hello(): uri = "ws://localhost:8765" async with websockets.connect(uri) as websocket: user = user_pb2.User() user.name = "张三" data = user.SerializeToString() l = len(data) format = ">I%us" % l print("format=", format) buf = struct.pack(format, l, data) await websocket.send(buf) print(f"> {user.name}") ret = await websocket.recv() print(f"< {ret}")
def get(self, request, context): pprint.pprint(request) user_id = request.id if str(user_id) not in users: return user_pb2.UserResponse(error=True, message="not found") user = users[str(user_id)] result = user_pb2.User() result.id = user["id"] result.nickname = user["nickname"] result.mail_address = user["mail_address"] result.user_type = user_pb2.User.UserType.Value(user["user_type"]) return user_pb2.UserResponse(error=False, user=result)
def main(args): topic = args.topic schema_registry_conf = {'url': args.schema_registry} schema_registry_client = SchemaRegistryClient(schema_registry_conf) protobuf_serializer = ProtobufSerializer(user_pb2.User, schema_registry_client, {'use.deprecated.format': True}) producer_conf = { 'bootstrap.servers': args.bootstrap_servers, 'key.serializer': StringSerializer('utf_8'), 'value.serializer': protobuf_serializer } producer = SerializingProducer(producer_conf) print("Producing user records to topic {}. ^C to exit.".format(topic)) while True: # Serve on_delivery callbacks from previous calls to produce() producer.poll(0.0) try: user_name = input("Enter name: ") user_favorite_number = int(input("Enter favorite number: ")) user_favorite_color = input("Enter favorite color: ") user = user_pb2.User(name=user_name, favorite_color=user_favorite_color, favorite_number=user_favorite_number) producer.produce(topic=topic, partition=0, key=str(uuid4()), value=user, on_delivery=delivery_report) except (KeyboardInterrupt, EOFError): break except ValueError: print("Invalid input, discarding record...") continue print("\nFlushing records...") producer.flush()
def run(): with grpc.insecure_channel('localhost:50051') as channel: stub = user_pb2_grpc.UserServiceStub(channel) response = stub.GetUserInfo(user_pb2.User(id=1, name="ishakdolek")) print(response)
import user_pb2 filename = '../user.bin' with open(filename, 'rb') as f: msg = user_pb2.User().FromString(f.read()) print(msg)
import user_pb2 u1 = user_pb2.User() u1.name = "user1" u1.age = 24 p1 = u1.products.add() p1.id = 1 p1.name = "product1" p1.price = 1300 p2 = user_pb2.Product() p2.id = 2 p2.name = "product2" p2.price = 5100 u1.products.append(p2) data = u1.SerializeToString() user = user_pb2.User() user.ParseFromString(data) print(user)