Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flask API not receiving requests all of a sudden

I am trying to create a REST API in Flask. The thing is it runs perfectly for a few days and then all of a sudden it STOPS receiving requests altogether. Forget about not responding to requests; it just doesn't receive any requests at the first place. This is my script:

from flask import Flask, jsonify
from flask_restful import Resource, Api
from flask_restful import reqparse
from sqlalchemy import create_engine
from flask.ext.httpauth import HTTPBasicAuth
from flask.ext.cors import CORS

conn_string = "mssql+pyodbc://x"
e = create_engine(conn_string)

auth = HTTPBasicAuth()

@auth.get_password
def get_password(username):
    if username == 'x':
        return 'x'
    return None

app = Flask(__name__)
cors = CORS(app)
api = Api(app)

class Report(Resource):
    decorators = [auth.login_required]

    def get(self):
        parser = reqparse.RequestParser()
        parser.add_argument('start', type = str)
        parser.add_argument('end', type = str)
        args = parser.parse_args()

        conn = e.connect()

        stat = """
        select a, b from report where c < ? and d > ?
        """

        query = conn.execute(stat, [args['start'], args['end']])

        json_dict = []

        for i in query.cursor.fetchall():


            res = {'aa': i[0], 'bb':i[1]}
            json_dict.append(res)

        conn.close()
        return jsonify(results=json_dict)

api.add_resource(Report, '/report')

if __name__ == '__main__':
    app.run(host='0.0.0.0')

I've tried to debug the issue and following are my observations:

1) Flask API is running on port 5000 and when I psping the VM on port 5000 I'm able to connect which means the process is actually running properly on the VM.

2) On checking my logs, the GET requests are not even being received by the API. If there was some db error then I'd have gotten a 500 error message but the requests are not even going to the API at the first place.

3) If I call the API locally then still the issue persists.

4) If I do a netstat for port 5000 (where my flask API is running on) I'm getting the following:

enter image description here

For some reason I think its not closing socket connections. I'm getting lots of "CLOSE_WAIT". Is this what is causing the problem? How can I fix this in my code?

like image 386
90abyss Avatar asked Dec 13 '15 08:12

90abyss


1 Answers

Usually, when you get lots CLOSE_WAIT status, it means there are socket connections unclosed. And It seems that you have found the answer at Flask / Werkzeug - sockets stuck in CLOSE_WAIT , which leverages Tornado http://flask.pocoo.org/docs/0.10/deploying/wsgi-standalone/#tornado to build a non-blocking web server.

like image 125
Gary Liu Avatar answered Oct 17 '22 18:10

Gary Liu