def test_message_base64_decode_fails(self, resource_group, location, storage_account, storage_account_key): # Arrange qsc = QueueServiceClient(self._account_url(storage_account.name), storage_account_key) queue = QueueClient( account_url=self._account_url(storage_account.name), queue_name=self.get_resource_name(TEST_QUEUE_PREFIX), credential=storage_account_key, message_encode_policy=None, message_decode_policy=BinaryBase64DecodePolicy()) try: queue.create_queue() except ResourceExistsError: pass message = u'xyz' queue.send_message(message) # Action. with self.assertRaises(DecodeError) as e: queue.peek_messages() # Asserts self.assertNotEqual( -1, str(e.exception).find('Message content is not valid base 64'))
def test_message_text_fails(self, storage_account_name, storage_account_key): # Arrange qsc = QueueServiceClient(self.account_url(storage_account_name, "queue"), storage_account_key) queue = QueueClient( account_url=self.account_url(storage_account_name, "queue"), queue_name=self.get_resource_name(TEST_QUEUE_PREFIX), credential=storage_account_key, message_encode_policy=BinaryBase64EncodePolicy(), message_decode_policy=BinaryBase64DecodePolicy()) # Action. with self.assertRaises(TypeError) as e: message = u'xyz' queue.send_message(message) # Asserts self.assertTrue(str(e.exception).startswith('Message content must be bytes'))
def upload(globpath, container, queue, sas_token_env, storage_account_uri): try: sas_token_env = sas_token_env sas_token = os.getenv(sas_token_env) if sas_token is None: getLogger().error( "Sas token environment variable {} was not defined.".format( sas_token_env)) return 1 files = glob(globpath, recursive=True) for infile in files: blob_name = get_unique_name(infile, os.getenv('HELIX_WORKITEM_ID')) getLogger().info("uploading {}".format(infile)) blob_client = BlobClient( account_url=storage_account_uri.format('blob'), container_name=container, blob_name=blob_name, credential=sas_token) with open(infile, "rb") as data: blob_client.upload_blob(data, blob_type="BlockBlob", content_settings=ContentSettings( content_type="application/json")) if queue is not None: queue_client = QueueClient( account_url=storage_account_uri.format('queue'), queue_name=queue, credential=sas_token, message_encode_policy=TextBase64EncodePolicy()) queue_client.send_message(blob_client.url) getLogger().info("upload complete") return 0 except Exception as ex: getLogger().error('{0}: {1}'.format(type(ex), str(ex))) getLogger().error(format_exc()) return 1
response = queue_client.create_queue() if response == True: print('Storage Queue: pizzaqueue created successfully.\n') else: print('Error creating Storage Queue.\n') ### # Use the Azure Storage Storage SDK for Python to drop some messages in our Queue ### print( 'Now let\'s drop some messages in our Queue.\nThese messages could indicate a take-out order being received for a customer ordering pizza.' ) raw_input('Press Enter to continue...') # This basic example creates a message for each pizza ordered. The message is *put* on the Queue. queue_client.send_message(u'Veggie pizza ordered.') queue_client.send_message(u'Pepperoni pizza ordered.') queue_client.send_message(u'Hawiian pizza ordered.') queue_client.send_message(u'Pepperoni pizza ordered.') queue_client.send_message(u'Pepperoni pizza ordered.') time.sleep(1) ### # Use the Azure Storage Storage SDK for Python to count how many messages are in the Queue ### print( '\nLet\'s see how many orders we have to start cooking! Here, we simply examine how many messages are sitting the Queue. ' ) raw_input('Press Enter to continue...')
def main(trigger: func.QueueMessage): ''' The function has to use imported code libraries to write to the queue because otherwise writes are only done when the function has finished. ''' logging.info('matchengine triggered') message = trigger.get_body().decode( ) # to decode to utf-8 and remove leading b' # The message coming in has to be just text for base 64 decoding, so expect a string of team names in fixture list order. team_list = message.split(",") # Remove the first element as this tells us whether we're playing normal or extra time or penalties game_stage = team_list.pop(0) query_string = "" for team in team_list: query_string += "Name eq \'" + team + "\' or " query_string = query_string[:-4] # Remove trailing ' or ' # Get the team stats from the table keyVaultName = os.environ["KEY_VAULT_NAME"] keyVault_URI = "https://" + keyVaultName + ".vault.azure.net" credential = DefaultAzureCredential() client = SecretClient(vault_url=keyVault_URI, credential=credential) data_access_key = client.get_secret("thecupstore-key") table_service = TableService(account_name='thecupstore', account_key=data_access_key.value) team_stats = table_service.query_entities('Teams', filter=query_string) # Set up the queue to write goals and timer intervals to account_url = "https://thecupstore.queue.core.windows.net/" queue_name = "goalqueue" goal_queue = QueueClient(account_url=account_url, queue_name=queue_name, credential=data_access_key.value, message_encode_policy=TextBase64EncodePolicy()) # Get in fixture list format and create the current round ready to play fixtures = create_fixtures(team_list) current_round = Round(fixtures, team_stats) matches = current_round.get_matches() if game_stage == "normal": MATCH_LENGTH = 90 match_time = 1 elif game_stage == "extra": MATCH_LENGTH = 120 match_time = 91 else: match_time = 120 if game_stage == "normal" or game_stage == "extra": while match_time <= MATCH_LENGTH: for match in matches: for team in match: if goal_chance(team["goal_chance"]): # goal chance created. Check if saved. if goal_saved(team["keeping"]): pass else: # goal scored goal_queue.send_message(team["name"]) logging.info('writing timer to queue ' + str(match_time)) goal_queue.send_message(str(match_time)) # Check if the goalqueue is clear before continuing. This is to keep the matchengine in sync with the user form. This way they should see a smooth # progression of the timer. Without this check matchengine tends to run fast and multiple second jumps are observed. while goal_queue.get_queue_properties( ).approximate_message_count > 0: time.sleep(0.05) match_time += 1 elif game_stage == "penalties": # each team has 5 penalty kicks for penalty_number in range(5): for match in matches: for team in match: if penalty_goal(75): goal_queue.send_message(team["name"]) # add a message to inform game that penalties have completed goal_queue.send_message("done") elif game_stage == "suddendeath": # sudden death penalties for match in matches: for team in match: if penalty_goal(75): goal_queue.send_message(team["name"]) # add a message to inform game that a round of sudden death penalties have completed goal_queue.send_message("done") logging.info('matchengine complete')