ECONNRESET Error response getting from flask python - python

I'm not getting the proper response for this particular API. Also , In actual implementation, I'm getting the proper 200 jsonify response when all things are running fine but if their is any exception and If I want to send back the response with 500 status code : the postman say Could not get response : "Error: read ECONNRESET" and in my console it display as "127.0.0.1 - - [04/Aug/2020 23:57:22] "←[37mPOST /hi HTTP/1.1←[0m" 500 -"
can someone please tell me , where I'm going wrong ?
from flask import Flask, jsonify, request, abort, json
from werkzeug.utils import secure_filename
from werkzeug.exceptions import HTTPException
from flask_cors import CORS, cross_origin
import traceback
app = Flask(__name__)
cors = CORS(app)
app.config['CORS_HEADERS'] = 'Content-Type'
#app.route("/hi", methods=['POST'])
def hi():
val = 500
dict_json = {"messgae": "lets work it out {} ".format(val)}
return jsonify(dict_json), val

I had this problem today and found that it seems to be an issue with the flask server. It works fine usually however sometimes requests with postman would time out with the error you've mentioned.
Can you try hosting it instead with waitress?
To do that add this to the top of your file
from waitress import serve
then instead of running app.run() you run serve(app, host='localhost', port=7777)
oh, and for waitress to work you will of course need to run pip install waitress first!

Related

Flask Lazy loding with waitress

im was working with my flask app on my development server, but now i want to move that same application to a production enviroment. The thing is that when i was running that same application with flask run, i got the lazy loading message so i move to waitress in order to avoid this behaviour. When i use waitress the message dissapears but the behaviour is the same. The app is slow at the first request and then works properly.
Bellow you can find part of my code :
import flask
import io
import string
import time
import os
from flask import Flask, jsonify, request
import load_model
import prepare_image
from flask_cors import CORS
from waitress import serve
from paste.translogger import TransLogger
app = Flask(__name__)
#control archivo mayor a 16 mb
app.config['MAX_CONTENT_LENGTH'] = 4096 * 4096
cors = CORS(app, resources={r"/*": {"origins": "*"}})
#app.route('/predict', methods=['POST'])
blablabla
if __name__ == '__main__':
serve(TransLogger(app, setup_console_handler=False),port=5000)
Thanks in advance
when the app is served with weitress the lazy loading mode doesnt seem to disappear.

Unable to modify custom error message for Error code 405

My goal is to change the default 405 error code from "The method is not allowed for the requested URL" to "Not allowed method". However my code below doesn't work (this code was also used to other error code and they seem to work fine)
from flask import Flask, make_response, jsonify, request
app = Flask(__name__)
#app.errorhandler(405)
def method_not_allowed(error):
return make_response(jsonify(Error = 'Not allowed method'), 405)
What seems to be the problem?

No response from a Flask application using Apache server

I have created a flask application and am hosting it on a Ubuntu server. I know that my apache config is correct since I am able serve the example flask application. However, this one seems to be giving me trouble. The code is below:
from flask import Flask, render_template, request, url_for
import pickle
import engine
import config
# Initialize the Flask application
app = Flask(__name__)
model = pickle.load(open(config.MODEL_PATH, "rb"))
collection = engine.Collection(config.DATABASE_PATH)
search_engine = engine.SearchEngine(model, collection)
#app.route('/')
def form():
return render_template('index.html')
#app.route('/search/', methods=['POST'])
def search():
query = request.form['query']
results = search_engine.query(query)
return render_template('form_action.html', query=query, results=results)
#app.route('/retrieve/<int:item_number>', methods=['GET'])
def retrieve(item_number):
item = engine.Product(item_number, collection.open_document(str(item_number)))
return render_template('document.html', item=item)
if __name__ == '__main__':
app.run()
When running the file directly through the python interpreter, it works fine and I can access. However, when starting through apache and wsgi, I get no response from the server. It just hangs when making a request and nothing is available on the logs.
I suspect that my issue may have something to do with the three objects I initialize at the beginning of the program. Perhaps it gets stuck running those?
Update: I have tried commenting out certain parts of the code to see what is causing it to stall. Tracing it out to the engine module, importing NearestNeighbors seems to be causing the issue.
import sqlite3
import config
from sklearn.neighbors import NearestNeighbors
from preprocessor import preprocess_document
from collections import namedtuple

Can't set the strategy="moving-window" for Flask-Limiter

I want to limit IP connection to a server (currently implemented locally).
Here is my code
from flask import Flask, request
from flask.ext.cors import CORS, cross_origin
import time
import redis
from flask.ext.limiter.extension import Limiter
from flask.ext.limiter.util import get_ipaddr
app = Flask(__name__)
cors=CORS(app)
limiter = Limiter(
app,
key_func=get_ipaddr,
global_limits=[str(LIMITPERDAY) + " per day", str(LIMITPERMINUTE) + " per minute"],
storage_uri ="redis://127.0.0.1:6379",
#strategy="moving-window",
headers_enabled=True
)
#app.errorhandler(429)
def ratelimit_handler(e):
return "Ratelimit exceeded : " + e.description, 429
if __name__ == '__main__':
app.run(host="0.0.0.0",port=10005,threaded=True )
If I comment out the strategy part, when I connect to the server using curl or plain html, I keep getting error 500: Internal Server Error. When I comment out the strategy, the code can work. However from what I read in
http://flask-limiter.readthedocs.org/en/latest/#flask_limiter.Limiter
I need to use "moving-window" to connect to redis, otherwise it's "fixed-window" by default. I really don't know what's wrong with my code.
I run redis-server on Windows 10. I run my Flask on cygwin-64.
Thanks!
After I activate the debug, I found out the error is
File "C:\Users\lita\Anaconda2\lib\site-packages\redis\connection.py", line 582, in read_response
raise response
ResponseError: unknown command 'EVALSHA'
I check on https://github.com/nvie/rq/issues/398 and it's because Redis >= 2.6.0 is required. After I upgrade my Redis, the problem is solved.

How do I get flask-cor to return Access-Control-Allow-Origin on Google App Engine?

My python app does not throw any errors on Google App Engine, but the Allow-Control-Access-Origin header is never sent. How can I ensure that I am sending it with flask-cors?
import MySQLdb
import os
import webapp2
import json
import flask
from flask import Flask, jsonify, render_template, request
from flask.ext.cors import CORS, cross_origin
app = Flask(__name__)
#app.route('/')
#cross_origin()
def do_search():
if (os.getenv('SERVER_SOFTWARE') and
os.getenv('SERVER_SOFTWARE').startswith('Google App Engine/')):
db = MySQLdb.connect(unix_socket='/cloudsql/my-instance-name:storeaddressdb', db='store_locator', user='myuser', passwd='password')
else:
db = MySQLdb.connect(host='localhost', user='root')
cursor = db.cursor()
query = 'SELECT * FROM stores WHERE 1 LIMIT 5'
cursor.execute(query)
resp = jsonify(data=cursor.fetchall())
return resp
db.close()
It appears that this code actually does work, although I do not see the Allow-Control-Access-Origin header when I use cURL to test the url. The logs in Google App Engine show CORS selectively adding the header unless the client specifically skipped it. Also, the Javascript client is no longer showing an error, and receives the data. It may not be the prettiest python code, but it is functionally correct for my purposes.

Categories

Resources