Weird “is_xhr” error when deploying Flask app to H

2020-08-09 05:16发布

问题:

I have a flask app which I've deployed to Heroku, one of the routes is the following

def get_kws():
    seed_kw = request.json['firstParam']
    audience_max = request.json['secondParam']
    interest_mining_service = InterestMiningService(seed_kw, audience_max)
    query_result = interest_mining_service.query_keyword().tolist()
    if seed_kw in query_result:
        print ("yes")
        return jsonify(
            {
             'keyword_data' : interest_mining_service.find_kws().to_json(orient='records'),
             'query_results': query_result
            }
        )

When I test this endpoint locally, I have no issues when sending POST and GET requests to that endpoint. However, when I deploy to Heroku, I get the following error:

File "/app/server/controller.py", line 24, in get_kws
2020-02-08T22:31:05.893850+00:00 app[web.1]: 'query_results': query_result
2020-02-08T22:31:05.893850+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/flask/json.py", line 298, in jsonify
2020-02-08T22:31:05.893851+00:00 app[web.1]: if current_app.config['JSONIFY_PRETTYPRINT_REGULAR'] and not request.is_xhr:
2020-02-08T22:31:05.893851+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/werkzeug/local.py", line 347, in __getattr__
2020-02-08T22:31:05.893852+00:00 app[web.1]: return getattr(self._get_current_object(), name)
2020-02-08T22:31:05.893858+00:00 app[web.1]: AttributeError: 'Request' object has no attribute 'is_xhr'

I've never seen this error Request object has no attribute 'is_xhr' before and it only seems to be happening when I deploy to Heroku. Any guidance on what I should look into?

There also doesn't seem to be an issue with the json key keyword_data - the issue seems limited to query_results which is a list.

回答1:

The Werkzeug library (dependency from Flask) recently received a major update (0.16.1 --> 1.0.0) and it looks like Flask (<=0.12.4) does not restrict the version of Werkzeug that is fetched.

You have 2 options:

  • Stick with your current version of Flask and restrict the Werkzeug version that is fetched explicitly in your application's setup.py or requirements.txt by specifying werkzeug<1.0 or werkzeug==0.16.1

  • Upgrade to a recent version of Flask (>=1.0.0), which is running fine with latest Werkzeug



回答2:

Or you can just forcefully install the bustard again by calling

pip install Werkzeug==0.16.1


回答3:

I have faced with this problem too.

Just temporarily fixed by directly checking in request header

request.headers.get("X-Requested-With") == "XMLHttpRequest"

not sure this help ...



标签: heroku flask