Armen Babakanian
Armen Babakanian

Reputation: 2305

python flask socket send call never returns

I wrote a flask view function that send a query to a local service via sockets and then processes the data and returns it after rendering.

@app.route('/_search', methods=["GET", "POST"])
@app.route('/_search/', methods=["GET", "POST"])
def searchQuery():

    # get the argument that were passed using get
    t_query = request.args.get('query')

    print(t_query)

    t_s = get_searchserver_socket()
    t_s.send("C, something")

    t_data = t_s.recv(1024)
    print(t_data)
    return t_data

    #abort(404)

I just use the global variable in flask to hold the socket so it doesn't recreated it everytime:

def get_searchserver_socket():
    t_socket = getattr(g, '_socket', None)
    if t_socket is None:
        t_socket = g._socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        t_socket.connect((search_server_ip, search_server_port))
    return t_socket

the problem with this is that in the view function, the socket send call (t_s.send) gets stuck and actually never sends the data. Why is this?

Thanks

Upvotes: 1

Views: 170

Answers (1)

Ryan O'Donnell
Ryan O'Donnell

Reputation: 617

flask.g is only available for the current request. It exists in the application context, which you can read more about here: http://flask.pocoo.org/docs/0.10/appcontext/

You still will be re-creating this socket each time. If you want it to be persistent you'll have to create the socket outside of the Flask application context (outside of your Flask app) and then use it from there.

Upvotes: 1

Related Questions