示例#1
0
def get_queue(queue_name, create_queue, clear_queue):
    ''' Note that generating the queueclient does not mean there must a queue there as one of the properties of queueclient is "create_queue", so it's 
    really a representation of a queue which may or may not exist yet. '''
    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")
    account_url = "https://thecupstore.queue.core.windows.net/"
    queueclient = QueueClient(account_url=account_url,
                              queue_name=queue_name,
                              credential=data_access_key.value,
                              message_encode_policy=TextBase64EncodePolicy(),
                              message_decode_policy=TextBase64DecodePolicy())
    # Check that the queue exists and if not create it if the create switch has been passed as True
    try:
        queueclient.get_queue_properties()
    except:
        if create_queue:
            queueclient.create_queue()
        else:
            message = "Queue does not exist"
    else:
        if clear_queue:
            queueclient.clear_messages()

    if 'message' in locals():  # checks for existence of message variable
        return message
    else:
        return queueclient
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...')

metadata = queue_client.get_queue_properties()
print('Number of messages in the queue: ' +
      str(metadata.approximate_message_count))

time.sleep(1)

###
# Use the Azure Storage Storage SDK for Python to read each message from the Queue
###
print(
    '\nWith some messages in our Azure Storage Queue, let\'s read the first message in the Queue to signal we start to process that customer\'s order.'
)
raw_input('Press Enter to continue...')

# When you get each message, they become hidden from other parts of the applications being able to see it.
# Once you have successfully processed the message, you then delete the message from the Queue.
示例#3
0
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')