예제 #1
0
async def add_game(request, persistence):
    """
    Create a new game.

    The user will become the moderator of the game.
    """
    json = await request.json(loads=loads_or_empty)

    try:
        available_cards = json['cards']
    except KeyError:
        return json_response({'error': 'No card set provided.'}, status=400)

    moderator_name = json.get('moderator_name', '')
    if moderator_name == '':
        return json_response({'error': 'Moderator name not provided.'}, status=400)

    if len(available_cards) < 2:
        return json_response({'error': 'Cannot play with less than 2 cards.'}, status=400)

    moderator_session = await get_session(request)
    # Get or assign the moderator id:
    moderator_id = get_or_assign_id(moderator_session)
    game_id = get_random_id()
    persistence.add_game(game_id, moderator_id, moderator_name, coerce_cards(available_cards))

    return json_response({'game_id': game_id, 'game': persistence.serialize_game(game_id)})
예제 #2
0
def get_or_assign_id(session: Session) -> str:
    """Return client's ID, and if it doesn't exist, assign it and return."""
    client_id = session.setdefault(CLIENT_ID_KEY, get_random_id())
    return client_id