No response from a Flask application using Apache server - python

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

Related

Using Reserved Ngrok Domain with Flask-Ngrok

I have written a simple API using Flask. It works when run on my local machine and when testing using Ngrok. The issue I have is that Ngrok changes the IP each time the API is run.
I have a paid Ngrok plan and have reserved a domain but I can't work out how to point the API to the domain.
I can't see anything in the docs but it seems fairly basic functionality so I'm at a bit of a loss.
What am I missing?
Here's my code (go easy, I'm a beginner):
from flask import *
from flask_ngrok import run_with_ngrok
import json, time
app = Flask(__name__)
run_with_ngrok(app)
#app.route('/', methods=['GET'])
def test_data():
json_address_details = open('address_details.json')
address_details = json.load(address_bet_details)
print(address_details)
json_address_details.close()
json_dump = json.dumps(address_details)
return json_dump
if __name__ == '__main__':
app.run()

How to check my metrics using prometheus_flask_exporter lib

I want to keep track of metrics in my flask application using the lib prometheus_flask_exporter.
For what i could understand this lib already tracks default metrics in the /metrics endpoint.
But when i try to access the http://localhost:5000/metrics I get 404 Not Found.
So i tried to set a histogram metric on the user_list, but i get the same 404 not Found when i try to access the http://localhost:5000/metrics
init.py:
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flasgger import Swagger
from flask_caching import Cache
from prometheus_flask_exporter import PrometheusMetrics
app = Flask(__name__)
app.debug = True
app.config.from_object('dev_maintenance.yaml_config_loader')
cache = Cache(app)
db = SQLAlchemy(app)
swagger = Swagger(app)
metrics = PrometheusMetrics(app)
import dev_maintenance.mesos_callback
import dev_maintenance.db_model
import dev_maintenance.active_directory
import dev_maintenance.user_list
import dev_maintenance.audit
import dev_maintenance.machines
import dev_maintenance.yaml_config_loader
import dev_maintenance.roles
import dev_maintenance.user_details
if __name__ == '__main__':
app.run(debug=True)
user_list.py
from dev_maintenance import app
from flask import jsonify, request
from flask_simpleldap import LDAP
from flask_jwt_extended import jwt_required
from dev_maintenance import metrics
ldap = LDAP(app)
#app.route('/api/user', methods=['GET'])
#metrics.do_not_track()
#metrics.histogram('requests_by_status_and_path', 'Request latencies by status and path',
labels={'status': lambda r: r.status_code, 'path': lambda: request.path})
def user_list():
user_list = []
users = ldap.get_group_members('ship_crew')
for user in users:
user_list.append(str(user, encoding='utf-8').split(",")[0].split("=")[1])
return jsonify(user_list)
Do i need to create a /metrics route? Because in the git documentation does not say anything about that, so i suppose this is already set behind the scenes.
Instead of "app.run(debug=True)" use "app.run(debug=False)". debug=True was breaking things.
From:https://github.com/rycus86/prometheus_flask_exporter/blob/master/README.md
Please note, that changes being live-reloaded, when running the Flask app with debug=True, are not going to be reflected in the metrics. See https://github.com/rycus86/prometheus_flask_exporter/issues/4 for more details.
Alternatively - since version 0.5.1 - if you set the DEBUG_METRICS environment variable, you will get metrics for the latest reloaded code. These will be exported on the main Flask app. Serving the metrics on a different port is not going to work most probably - e.g. PrometheusMetrics.start_http_server(..) is not expected to work.

Access flask app endpoints in another python file?

I have a python file which defines some endpoints using flask each doing some computation and return a JSON (POST method). I want to do unit testing on this in order to do this I want to be able to access the app I created in one python file in another file so I can test my endpoints.
I see a lot of this on the internet :
from source.api import app
from unittest import TestCase
class TestIntegrations(TestCase):
def setUp(self):
self.app = app.test_client()
def test_thing(self):
response = self.app.get('/')
assert <make your assertion here>
It doesn't explain how I can define and access my app in another file. This might be a stupid question but I really don't see how.
My app is defined as follows:
from flasgger import Swagger
from flask import Flask, jsonify, request
from flask_cors import CORS
import os
def init_deserializer_restful_api():
# Initiate the Flask app
app = Flask(__name__)
Swagger(app)
CORS(app)
# Handler for deserializer
#app.route("/deserialize", methods=['POST'])
def handle_deserialization_request():
pass
I have many other end points in this fashion. Should i just do:
import my_file_name
Thanks!!
Check out this question: What does if __name__ == "__main__": do?
As long as you have that in your python program, you can both treat it as a module and you can call it directly.

python flask return prior execution of reboot

for reasons I want to trigger the reboot of an raspberry pi using a REST api.
My REST api is coded in python flask like this:
from flask import Flask
from flask import jsonify
import subprocess
app = Flask(__name__)
#app.route('/api/reboot')
def reboot():
subprocess.call("/sbin/reboot")
return jsonify(triggered='reboot')
if __name__ == '__main__':
app.run(debug=True,host="0.0.0.0")
the code is working perfectly fine. But due to its a reboot the return will not be send (because the system is rebooting obviously).
Is there a way to trigger the reboot some kind of async with a delay of a couple milliseconds, that allows to return some value (in my case just an custom 'ack') prior the actual reboot?
Try threading.Timer:
For example:
from flask import Flask
from flask import jsonify
import subprocess
import threading
app = Flask(__name__)
def _reboot():
subprocess.call("/sbin/reboot")
#app.route('/api/reboot')
def reboot():
t = threading.Timer(1, _reboot)
t.start()
return jsonify(triggered='reboot')
if __name__ == '__main__':
app.run(debug=True,host="0.0.0.0")

Trouble Hosting flask app on pythonanywhere

I am a first time user of pythonanywhere
I first started by doing a git clone of my code from github through the bash console. I did not use a virtual environment. My WSGI app was invoked in my app.py file. Also, my code uses sqlalchemy to interact with my database.
Basically, the flask app was like a custom api that returned JSON for GET and POST requests and I am having trouble viewing the JSON output. I am not sure what exactly I am doing wrong or missing.
Code in app.py file:
#!flask/bin/python
from flask import Flask
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from sqlalchemy_declarative import Base, Quote
from flask import request
from flask import abort
import json
#connect to database
engine = create_engine("sqlite:///quotes.db")
Base.metadata.bind = engine
DBSession = sessionmaker(bind=engine)
session = DBSession()
app = Flask(__name__)
#app.route("/trumptext/api/quotes", methods=["GET"])
def get_quotes():
quoteList = session.query(Quote).all()
result = []
for q in quoteList:
my_dict = {}
my_dict["id"] = q.id
my_dict["quote"] = q.quote
result.append(my_dict)
return json.dumps(result,ensure_ascii=False).encode('utf8')
#app.route("/trumptext/api/quotes", methods=["POST"])
def add_quote():
if not request.json or not "quote" in request.json:
abort(400)
new_quote = request.json["quote"]
q = Quote(quote=new_quote)
session.add(q)
session.commit()
quoteList = session.query(Quote).all()
last = quoteList[-1]
result = []
my_dict = {}
my_dict["id"] = last.id
my_dict["quote"] = last.quote
result.append(my_dict)
return json.dumps(result,ensure_ascii=False).encode('utf8'), 201
if __name__ == "__main__":
app.run()
Also, code in /var/www/nnelson_pythonanywhere_com_wsgi.py:
import os
import sys
path = '/home/nnelson/trumptextapi'
if path not in sys.path:
sys.path.append(path)
from app import app as application
If I enter something like :
http://nnelson.pythonanywhere.com/trumptext/api/quotes (to perform a GET request)
It should ideally return all the quotes stored in the quotes.db database in JSON format, however all I get it output that looks like this: [] I tested my code on localhost using the curl tool and it works just fine. I am having trouble hosting it though
Any help is appreciated.
You're using a relative path to your database, so it's probably looking at a database that you don't expect. Use a full path to the database or make it relative to the path of your app.py file so that you know where it's getting the database from.

Categories

Resources