miguelgrinberg / Flask-SocketIO

Socket.IO integration for Flask applications.
MIT License
5.36k stars 890 forks source link

gevent - cannot enter into function. #2020

Closed BuckLearnsCode closed 11 months ago

BuckLearnsCode commented 11 months ago

Hey, I'm new to coding, but feel like I've gotten a total crash course while trying to get the following working:

I have 'gevent' added to async_mode. I'm spawning greenlets.

My issue is that as soon as I switch a function to async, it won't enter the function. I can't figure out what's wrong and neither can chatgpt. I've been working on this for 3 days, I figured I'd ask.

Notes:

from gevent import monkey, get_hub, spawn, getcurrent import gevent monkey.patch_all() from flask import Flask, request from flask_socketio import join_room, SocketIO from flask_cors import CORS

app = Flask(name, static_folder="front/build", static_url_path="/") socketio = SocketIO( app, cors_allowed_origins="*", load_balancer=True, engineio_logger=True, logger=True, async_mode='gevent' )

@socketio.on("send_message", namespace=GAME_NAMESPACE) async def handle_message(data): print(Fore.RED + 'Handle Message Accessed.') print(f"Current Thread ID: {getcurrent()}") try: user_input = data["message"] user_inputs_buffer.append(user_input)

    # Get the lobby_id for the current sid
    current_lobby_id = lobby_manager.player_to_lobby_map.get(request.sid)

    # If the current sid has no associated lobby_id (unexpected behavior), simply return
    if not current_lobby_id:
        return

    # Retrieve the lobby object from the lobby manager
    current_lobby = lobby_manager.get_lobby_by_id(current_lobby_id)

    # If the lobby doesn't exist, just return
    if not current_lobby:
        return

    # Retrieve the number of players for the current lobby
    current_lobby_players_count = len(current_lobby.members)
    print(f"Number of players: {current_lobby_players_count}")

    # If inputs received == number of players in the current lobby, then process the batch
    if len(user_inputs_buffer) == current_lobby_players_count:
        # Join all messages from the buffer
        batched_input = " ".join(user_inputs_buffer)

        # Clear the buffer for the next set of inputs
        user_inputs_buffer.clear()

        # Now, we process the batched input instead of individual user_input
        if batched_input.lower() in ["exit", "quit"]:
            return

        memory.chat_memory.add_user_message(
            batched_input
        )  # Add batched input to memory
        game_commands = get_game_commands(
            batched_input, game_engine
        )  # Use batched input

        engine_output = game_engine.calculate_output(game_commands)
        game_state["previous_message"] = batched_input  # Use batched input

        response = generate_gm_response(
            game_state, game_engine, engine_output, campaign_outline
        )
        memory.chat_memory.add_ai_message(response)
        socketio.emit(
            "receive_message",
            {"message": response},
            namespace=GAME_NAMESPACE,
            room=current_lobby_id,
        )

except Exception as e:
    print(f"An error occurred: {e}")
    raise

if name == "main": port = int(os.environ.get("PORT", 5001)) socketio.run(app, host="127.0.0.1", port=port, debug=True)

miguelgrinberg commented 11 months ago

Please do not write issues when you have a question about your own application. The issues board helps me track bugs in this package. Use the discussions board to ask questions or seek help.

With regards to your problem, gevent does not work with async def, you are confusing two different asynchronous solutions that do not work with each other.