I am not able to get http://127.0.0.1:5000/movie Url from the browser.
Every time it gives 404. The only time it worked was with URL from hello world.
I am trying to run a recommender system deployment solution with flask, based on https://medium.com/analytics-vidhya/build-a-movie-recommendation-flask-based-deployment-8e2970f1f5f1.
I have tried uninstall flask and install again but nothing seems to work.
Thank you!
from flask import Flask,request,jsonify
from flask_cors import CORS
import recommendation
app = Flask(__name__)
CORS(app)
#app.route('/movie', methods=['GET'])
def recommend_movies():
res = recommendation.results(request.args.get('title'))
return jsonify(res)
if __name__=='__main__':
app.run(port = 5000, debug = True)
http://127.0.0.1:5000/movie
be careful not writing '/' after movie like http://127.0.0.1:5000/movie/
Related
I'm using Flask to serve a static folder:
from flask import Flask, send_from_directory
from flask_httpauth import HTTPBasicAuth
app = Flask(__name__,
static_url_path='',
static_folder='html_files')
...
#app.route('/')
#auth.login_required
def send_html_files():
return send_from_directory('html_files', 'main.html')
I used the first example in Flask-HTTPAuth docs in order to add basic authentication to my website. Just a regular username and password is enough for me.
The problem is that the authentication dialog is not showing when the user go directly to http://localhost:5000/a/b/c (it works on http://localhost:5000/)
What is the proper way of doing this? On the other hand, what is the quick and dirty way?
#app.route('/') matches your root path only.
Try something like this to match every path:
#app.route('/<path:filename>')
#auth.login_required
def send_html_files(filename):
return send_from_directory('html_files', filename)
I have created a Flask prediction app (within Google Colab) and when I am trying to run it post adding all the dependencies within the colab environment I am getting the url but when I click on it it show site cannot be reached.
I have the Procfile, the pickled model and the requirements text file but for some reason its not working. Also, I tried deploying this app using Heroku and it met the same fate where I got the app error.
For more context please visit my github repo.
Any help or guidance will be highly appreciated.
from flask import Flask, url_for, redirect, render_template, jsonify
from pycaret.classification import*
import pandas as pd
import numpy as np
import pickle
app = Flask(__name__)
model = load_model('Final RF Model 23JUL2021')
cols = ['AHT','NTT','Sentiment','Complaints','Repeats']
#app.route('/')
def home():
return render_template("home.html")
#app.route('/predict',methods=['POST'])
def predict():
int_features = [x for x in request.form.values()]
final = np.array(int_features)
data_unseen = pd.DataFrame([finak], columns = cols)
prediction = predict_model(model, data=data_unseen, round=0)
prediction = int(prediction.Label[0])
return render_template('home.html',pred='Predicted Maturiy Level is{}'.format(prediction))
#app.route('/predict_api',methods=['POST'])
def predict_api():
data = request.get_json(force=True)
data_unseen = pd.DataFrame([data])
prediction = predict_model(model, data=data_unseen)
output = prediction.Label[0]
return jsonify(output)
if __name__ == '__main__':
app.run(debug=True)
You cannot run flask app same as in your machine. You need to use flask-ngrok.
!pip install flask-ngrok
from flask_ngrok import run_with_ngrok
[...]
app = Flask(__name__)
run_with_ngrok(app)
[...]
app.run()
You can't use debug=True parameter in ngrok.
I am currently deploying a Flask app to AWS Beanstalk, and I am trying to log out some stuff in the application (print), but I am not sure how to view it within Beanstalk, do guide me along, thank you!
The print should be in /var/log/web.output.log. However, they can show up with a delay. Thus, I found that its easier to hook up into gunicorn logger from flask which update web.output.log in real time.
Below is sample application.py that you can test it out and see how to set it up:
import os
from flask import Flask, Blueprint
from flask_restful import Api
from datetime import datetime
import logging
application = Flask(__name__)
#application.route("/")
def hello():
current_time = datetime.now().strftime("%H:%M:%S")
print(f"print from the app {current_time}")
application.logger.info(f"info from hello {current_time}")
application.logger.error(f"error from hello {current_time}")
return "<h1 style='color:blue'>Hello There!</h1>"
if __name__ == '__main__':
application.run()
else:
gunicorn_logger = logging.getLogger('gunicorn.error')
application.logger.handlers = gunicorn_logger.handlers
application.logger.setLevel(logging.INFO)
I am trying to deploy a machine learning model on AWS EC2 instance using Flask. These are sklearn's fitted Random Forest models that are pickled using joblib. When I host Flask on localhost and load them into memory everything runs smoothly. However, when I deploy it on the apache2 server using mod_wsgi, joblib works sometimes(i.e. the models are loaded using joblib sometimes) and the other times the server just hangs. There is no error in logs. Any ideas would be appreciated.
Here is the relevant code that I am using:
# In[49]:
from flask import Flask, jsonify, request, render_template
from datetime import datetime
from sklearn.externals import joblib
import pickle as pkl
import os
# In[50]:
app = Flask(__name__, template_folder="/home/ubuntu/flaskapp/")
# In[51]:
log = lambda msg: app.logger.info(msg, extra={'worker_id': "request.uuid" })
# Logger
import logging
handler = logging.FileHandler('/home/ubuntu/app.log')
handler.setLevel(logging.ERROR)
app.logger.addHandler(handler)
# In[52]:
#app.route('/')
def host_template():
return render_template('Static_GUI.html')
# In[53]:
def load_models(path):
model_arr = [0]*len(os.listdir(path))
for filename in os.listdir(path):
f = open(path+"/"+filename, 'rb')
model_arr[int(filename[2:])] = joblib.load(f)
print("Classifier ", filename[2:], " added.")
f.close()
return model_arr
# In[54]:
partition_limit = 30
# In[55]:
print("Dictionaries being loaded.")
dict_file_path = "/home/ubuntu/Dictionaries/VARR"
dictionaries = pkl.load(open(dict_file_path, "rb"))
print("Dictionaries Loaded.")
# In[56]:
print("Begin loading classifiers.")
model_path = "/home/ubuntu/RF_Models/"
classifier_arr = load_models(model_path)
print("Classifiers Loaded.")
if __name__ == '__main__':
log("/home/ubuntu/print.log")
print("Starting API")
app.run(debug=True)
I was stuck with this for quite sometime. Posting the answer in case someone runs into this problem. Using print statements and looking at logs I narrowed the problem down to joblib.load statement. I found this awesome blog: http://blog.rtwilson.com/how-to-fix-flask-wsgi-webapp-hanging-when-importing-a-module-such-as-numpy-or-matplotlib
The idea of using a global process group fixed the problem. That forced the use of main interpreter just as the top comment on that blog page mentions.
I am trying to use mod-wsgi with Apache 2.2
I have the following directory structure:
scheduling-algos
-lib
-common
-config
-config.json
resources
-Optimization.py
optimization.wsgi
optimization_app.py
My optimization_app.py is the following:
from flask import Flask
from flask_restful import Api
from resources.Optimization import OptimizationAlgo
def optimizeInstances():
optimization_app = Flask(__name__)
api = Api(optimization_app)
api.add_resource(OptimizationAlgo, '/instances')
if __name__ == '__main__':
optimizeInstances()
optimization_app.run(host='0.0.0.0', debug=True)
My Optimization.py code looks like the following:
class OptimizationAlgo(Resource):
def post(self):
return "success"
When I make a POST request to the url http://<host>:5000/instances, it works just as expected. I want make this work using WSGI. I have mod-wsgi installed with Apache 2.2.
My optimization.wsgi file looks like the following
import sys
sys.path.insert(0, '<path to app>')
from optimization_app import optimizeInstances as application
I get the following error: TypeError: optimizeInstances() takes no arguments (2 given) . Apparently this is not the correct way to use WSGI. What is the correct way to use WSGI?
Apparently, this is not the correct way to use WSGI.
As I told you in your other question, you should perhaps go back and read the Flask documentation again. That way you will learn and understand properly. By ignoring advice and expecting others to tell you, it only annoys people and they will stop helping you. Would suggest you take heed of that rather than leave a trail of separate questions hoping someone will solve your problems for you.
That said, I can't see how the code you give can even work with the Flask development server as you claim. The problem is that optimization_app = Flask(__name__) is setting a local variable within function scope. It isn't setting a global variable. As a result the call of optimization_app.run(host='0.0.0.0', debug=True) should fail with a LookupError as it will not see a variable called optimization_app. Not even sure why you are bothering with the function.
If you go look at the Flask documentation, the pattern it would likely use is:
# optimisation.wsgi
import sys
sys.path.insert(0, '<path to app>')
# We alias 'app' to 'application' here as mod_wsgi expects it to be called 'application'.
from optimization_app import app as application
# optimization_app.py
from flask import Flask
from flask_restful import Api
from resources.Optimization import OptimizationAlgo
app = Flask(__name__)
api = Api(app)
api.add_resource(OptimizationAlgo, '/instances')
if __name__ == '__main__':
app.run(host='0.0.0.0', debug=True)