Exemple #1
3
from flask import Flask, render_template, request
from flask import url_for
from bandsintown import Client
from healthcheck import HealthCheck, EnvironmentDump

import urllib


app = Flask(__name__)


health = HealthCheck(app, "/healthcheck")

def website_available():
	code = urllib.urlopen("http://130.211.90.87:5000").getcode()
	print code
	if code == 200:
		return True, "Website up"
	else:
		return False, "Something is wrong!"

health.add_check(website_available)


@app.route('/')
def index_form():
    return render_template("index.html")

@app.route('/events', methods=['GET','POST'])
def event_form():
	if request.method == 'GET':
Exemple #2
0
def register_health_check(app, db):

    health = HealthCheck(app, "/healthcheck")

    def db_available():
        try:
            result = db.engine.execute('SELECT 1')
            if result:
                return True, 'Database OK'
        except Exception as e:
            app.logger.exception(e)

        return False, 'Database Issue'

    health.add_check(db_available)
Exemple #3
0
class Health(object):

    def __init__(self, app, endpoint='/health', checks=[]):
        self.health = HealthCheck(app, endpoint)

        # extra health checks
        [self.health.add_check(check) for check in checks if callable(check)]
 def __init__(self, app, endpoint='/health', checks=[]):
     self.health = HealthCheck(app, endpoint)
     [self.health.add_check(check) for check in checks if callable(check)]
# from exceptions.exception_logger import create_logger
# from log import configure_logger, DE_LOG_FILE_PATH


class DataExtractorJSONEncoder(json.JSONEncoder):
    def default(self, o):
        if isinstance(o, Decimal):
            return float(o)
        return json.JSONEncoder.default(self, o)


class DEConfig:
    RESTFUL_JSON = {"cls": DataExtractorJSONEncoder}


de_health = HealthCheck()

app = Flask(DE_APPLICATION_NAME)
# configure_logger(app.logger, logging.INFO, DE_LOG_FILE_PATH)
# create_logger(DE_LOG_FILE_PATH)
app.config.from_object(DEConfig)
CORS(app)

api = Api(app, catch_all_404s=True)


# Extract data API for Machines and Scanned PDF.
@app.route('/', methods=["GET"])
def home_page_route():
    resp = send_from_directory("static", "index.html")
    return resp
Exemple #6
0
from bookshelf.config import config
from flask import Flask
from healthcheck import HealthCheck, EnvironmentDump
import os

app = Flask(__name__)
config_name = os.getenv('FLASK_CONFIGURATION', 'default')
app.config.from_object(config[config_name])
app.config.from_pyfile('config.cfg', silent=True)

health = HealthCheck(app, "/healthcheck")
envdump = EnvironmentDump(app,
                          "/environment",
                          include_python=True,
                          include_os=False,
                          include_process=False,
                          include_config=True)


def sqlite_available():
    # add precise check against the database
    return True, "sqlite ok"


health.add_check(sqlite_available)


def application_data():
    return {
        "maintainer": "Damyan Bogoev",
        "git_repo": "https://github.com/damyanbogoev/flask-bookshelf"
Exemple #7
0
#!/usr/bin/env python3
"""Main entry for Bottle application."""

import json
import os
import atexit
from apscheduler.schedulers.background import BackgroundScheduler
from apscheduler.triggers.interval import IntervalTrigger
from healthcheck import HealthCheck, EnvironmentDump
import bottle
from bottle import request, response

app = application = bottle.Bottle()

health = HealthCheck()
envdump = EnvironmentDump()


@app.route("/healthz")
def healthcheck():
    """Health check."""
    message, status, headers = health.run()
    return bottle.HTTPResponse(body=message, status=status, headers=headers)


@app.route("/environment.x")
def environmentdump():
    """Environment exposer."""
    message, status, headers = envdump.run()
    return bottle.HTTPResponse(body=message, status=status, headers=headers)
    def __init__(self, app, endpoint='/health', checks=[]):
        self.health = HealthCheck(app, endpoint)

        # extra health checks
        [self.health.add_check(check) for check in checks if callable(check)]
Exemple #9
0
from app import app
from flask import jsonify
import os, requests
from flask import Flask, render_template, url_for, json
from healthcheck import HealthCheck

app.config['JSONIFY_PRETTYPRINT_REGULAR'] = True


@app.route('/')
def home():
    return "hello world"


@app.route('/meta')
def status():
    SITE_ROOT = os.path.realpath(os.path.dirname(__file__))
    json_url = os.path.join(SITE_ROOT, "static/data", "metadata.json")
    data = json.load(open(json_url))
    return jsonify(data)


health = HealthCheck(app, "/healthcheck")


def healthy():
    return True, 'OK'


health.add_check(healthy)
Exemple #10
0
"""
Main module of the server file
"""

# 3rd party moudles
from flask import render_template
from healthcheck import HealthCheck
import connexion

# Create the application instance
app = connexion.App(__name__, specification_dir="./")

# wrap the flask app and give a heathcheck url
health = HealthCheck(app, "/api/health")

# Read the swagger.yml file to configure the endpoints
app.add_api("swagger.yml")


# create a URL route in our application for "/"
@app.route("/", methods=['POST', 'GET'])
def home():
    """
    This function just responds to the browser URL
    localhost:5000/

    :return:        the rendered template "home.html"
    """
    return render_template("home.html")

Exemple #11
0
 def test_basic_check(self):
     message, status, headers = HealthCheck().run()
     self.assertEqual(200, status)
from __future__ import absolute_import

from flask_login import LoginManager
from flask_mail import Mail
from flask_menu import Menu
from flask_script import Manager
from flask_security import Security
from healthcheck import HealthCheck, EnvironmentDump

healthcheck = HealthCheck()
environment_dump = EnvironmentDump()
login_manager = LoginManager()
mail = Mail()
manager = Manager()
menu = Menu()
security = Security()
Exemple #13
0
def create_app():
    app = Flask(__name__,
                template_folder=os.path.join(os.path.dirname(__file__),
                                             'templates'),
                static_url_path='')

    app.config.from_object(CONFIG)
    app.wsgi_app = ProxyFix(app.wsgi_app)
    app.health = HealthCheck(app, "/healthcheck")
    db.init_app(app)

    # add your own check function to the healthcheck
    def db_available():
        try:
            result = db.engine.execute("SELECT 1")
            result.close()
            return True, "db ok"
        except Exception as exp:
            app.logger.error("Exception occurred", exc_info=True)
            sentry_sdk.capture_exception(exp)
            return False, "db failure"

    app.health.add_check(db_available)

    @app.route('/')
    def root():
        return render_template('index.html', data=dict())

    @app.route('/slack/events/subscription', methods=['GET', 'POST'])
    def subscription():
        try:
            slack_event = request.json
            if slack_event['token'] != CONFIG.SLACK_TOKEN:
                return ('', 403)

            if slack_event['type'] == 'url_verification':
                return slack_event['challenge']

            if CONFIG.DEBUG:
                from pprint import pprint
                pprint(slack_event)

            if slack_event['type'] == 'event_callback':
                event = slack_event['event']
                if 'subtype' in event:
                    return ''

                if event['type'] == 'app_mention':
                    user_id, message = parse_direct_mention(event["text"])
                    if message:
                        handle_command(slack_event['team_id'], message,
                                       event["channel"])
                if event['type'] == 'message':
                    user_id, message = parse_direct_mention(event["text"])
                    if not message:
                        save_user(event)
                        save_message(event)
        except Exception as exp:
            app.logger.error("Exception occurred", exc_info=True)
            sentry_sdk.capture_exception(exp)
            return ('', 500)

        return ''

    return app
Exemple #14
0
from flask import Flask, request
from flask import request
from services.grafana_search import *
from healthcheck import HealthCheck
from services.grafana_service import GrafanaService

app = Flask(__name__)
health = HealthCheck()
api = Api(app)
service = GrafanaService()


def grafana():
    service.get('/api/health', None)
    return True, "Grafana esta de pé e respondendo"


health.add_check(grafana)

api.add_resource(GrafanaSearch, '/grafana/search')

app.add_url_rule("/hc", "healthcheck", view_func=lambda: health.run())

if __name__ == '__main__':
    app.run(host='0.0.0.0', port='5000')
def register_healthcheck(app):
    HealthCheck(app, '/health')
import google.cloud.logging

client = google.cloud.logging.Client()
client.setup_logging()

app = Flask(__name__)
path = Path('')
learn = load_learner(path)

#For flask
#logging.basicConfig(filename="flask.log", level=logging.DEBUG, format='%(asctime)s %(levelname)s %(name)s %(threadName)s : %(message)s')
logging.info("Model and vocab loaded")
print("Model Loaded")


health = HealthCheck(app, "/hcheck")

def healthcheck_func():
    return True, "Everything is up and running"

health.add_check(healthcheck_func)


def predict_func(text):
  result = learn.predict(text)
  return result


@app.route('/seclassifier', methods=['POST'])
def predict_sentiment():
    text = request.get_json()['text']
Exemple #17
0
from flask import request
from flask_pymongo import PyMongo
import yaml
import os
import random
import psutil
import string
from healthcheck import HealthCheck, EnvironmentDump
from prometheus_flask_exporter import PrometheusMetrics

import socket
import requests

app = Flask(__name__)
metrics = PrometheusMetrics(app)
health = HealthCheck()

metrics.info('app_info', 'Application info', version='1.0.3')

SHEDDER_HOST = "0.0.0.0"
SHEDDER_PORT = "3004"

with open(r'./config.yaml') as file:
    locationMappings = yaml.load(file, Loader=yaml.FullLoader)

# app.config['MONGO_DBNAME'] = locationMappings["db"]["name"]
# app.config['MONGO_URI'] = 'mongodb://' + locationMappings["db"]["url"] + ':' + str(locationMappings["db"]["port"]) + '/'+ locationMappings["db"]["name"]


def is_running():
    return True, "is running"
Exemple #18
0
 def test_failing_check(self):
     hc = HealthCheck(checkers=[self.check_throws_exception])
     message, status, headers = hc.run()
     self.assertEqual(500, status)
     jr = json.loads(message)
     self.assertEqual("failure", jr["status"])
Exemple #19
0
@force_scheme('https')
@homepage_blueprint.route('files', methods=['GET', 'POST'])
def list_files():
	path = str(request.form.get('path', '')) if request.method=='POST' \
	else str(request.args.get('path', ''))
	files = []
	if path:
		if not path[0]=='/':
			path = '/%s'%path
		files = list_dirs_files(path, PROJECT_ROOT)
		if not files:
			if request.method=='POST':
				return json.dumps({'success':True, 'ret': 'No such folder or empty'})
				files = []
		if request.method=='POST':
			return json.dumps({'success':True, 'ret':files})
	return render_template(
		'list_files.html',
		ret=files,
		file_scope=PROJECT_ROOT
	)


# set healthcheck URL
from dotcom import app
health = HealthCheck(app, "/statuses")
health.add_check(mongo_available)
health.add_check(flask_available)


Exemple #20
0
 def test_success_check(self):
     hc = HealthCheck(checkers=[self.check_that_works])
     message, status, headers = hc.run()
     self.assertEqual(200, status)
     jr = json.loads(message)
     self.assertEqual("success", jr["status"])
Exemple #21
0
from flask import Flask

from healthcheck import EnvironmentDump
from healthcheck import HealthCheck

app = Flask(__name__)

health = HealthCheck(app, '/healthcheck')
envdump = EnvironmentDump(app, '/environment')


def application_data():
    return {
        'maintainer': 'Charlie Lewis',
        'git_repo': 'https://github.com/IQTLabs/poseidon',
        'app': 'poseidon-api'
    }


envdump.add_section('application', application_data)
Exemple #22
0
# Count how many predictions are being served with an auto increment counter
counter = Value('i', 0)

app = Flask("repeat_customer_visits")

# Load the Model
model_object = os.path.join("./model_files", config.MODEL_PATH)
# Load the feature engineered pipeline containing numerical and categorical transformations
features_object = os.path.join("./model_files",
                               config.FEATURE_TRANSFORMATION_OBJECT_PATH)

features_transform_pipe = joblib.load(features_object)
model = joblib.load(model_object)

# Creating a healthcheck url to monitor the health check and heartbeat of the application
health = HealthCheck(app, "/hcheck")


def healthCheckApp():
    """
    Function to check the health of the application
    This function can be customized in production to check whether the database is being served,
    monitor cpu and memory resource of flask app. We can ping this dummy url to ensure the app is
    up and running


    Returns: A boolean indicating if application is up or down
    """
    return True, "I am alive"

    return app


current_app = create_app()
init_filters(app)


# http://stackoverflow.com/questions/26724623/
@app.before_request
def track_user():
    if current_user.is_authenticated:
        current_user.update_lat()


# Health-check
health = HealthCheck(current_app, "/health-check")
health.add_check(health_check_celery)
health.add_check(health_check_db)
with current_app.app_context():
    current_app.config['MIGRATION_STATUS'] = check_migrations()
health.add_check(health_check_migrations)

# register celery tasks. removing them will cause the tasks to not function. so don't remove them
# it is important to register them after celery is defined to resolve circular imports

from .api.helpers import tasks

celery = tasks.celery
# register scheduled jobs
from app.api.helpers.scheduled_jobs import setup_scheduled_task
padding_size = 1000
model = tf.keras.models.load_model(
    r'C:\Users\saish\PycharmProjects\sentiment analysis deployment\venv\sentiment_analysis.hdf5'
)
text_encoder = tfds.features.text.TokenTextEncoder.load_from_file(
    r"C:\Users\saish\PycharmProjects\sentiment analysis deployment\venv\sa_encoder.vocab"
)

logging.basicConfig(
    filename="sentimentAnalysis.log",
    level=logging.DEBUG,
    format='%(asctime)s %(levelname)s %(name)s %(threadName)s : %(message)s')

logging.info('Model and Vocabulary loaded.........')

health = HealthCheck(app, "/hcheck")


def howami():
    return True, " I am good"


health.add_check(howami)


def pad_to_size(vec, size):
    zeros = [0] * (size - len(vec))
    vec.extend(zeros)
    return vec

def set_health_check(app):
    health = HealthCheck(app, '/health')

    health.add_check(mongo_health)
Exemple #26
0
 def __init__(self, app):
     health = HealthCheck(app, "/tensor-bridge/v1/health")
     health.add_check(self.check_model_server)
Exemple #27
0
ignore_logger("root")

sentry_sdk.init(os.getenv("SENTRY_DSN"))
SERVICE_NAME = os.getenv("SERVICE_NAME")
SERVICE_PORT = int(os.getenv("SERVICE_PORT"))
RANDOM_SEED = int(os.getenv("RANDOM_SEED", 2718))

logging.basicConfig(
    format=
    "%(asctime)s - %(pathname)s - %(lineno)d - %(levelname)s - %(message)s",
    level=logging.INFO)
logger = logging.getLogger(__name__)

app = Flask(__name__)
health = HealthCheck(app, "/healthcheck")
logging.getLogger("werkzeug").setLevel("WARNING")

DF = main_dialogflow.composite_dialogflow


def handler(requested_data, random_seed=None):
    st_time = time.time()
    dialog_batch = requested_data.get("dialog_batch", [])
    human_utter_index_batch = requested_data.get("human_utter_index_batch",
                                                 [0] * len(dialog_batch))
    state_batch = requested_data.get(f"{SERVICE_NAME}_state_batch",
                                     [{}] * len(dialog_batch))
    dff_shared_state_batch = requested_data.get(f"dff_shared_state_batch",
                                                [{}] * len(dialog_batch))
    entities_batch = requested_data.get("entities_batch",
Exemple #28
0
client = google.cloud.logging.client()

client.setup_logging()

app = Flask(__name__)
padding_size = 1000
model = tf.keras.models.load_model('sentiment_analysis.hdf5')
text_encoder = tfds.features.text.TokenTextEncoder.load_from_file(
    "sa_encoder.vocab")

#ogging.basicConfig(filename = "flask.log", level=logging.DEBUG,
#                    format = '%(asctime)s %(levelname)s %(name)s %(threadName)s : %(message)s')
logging.info('Model and vocabulory loaded')

health = HealthCheck(app, '/hcheck')


def howami():
    return True, 'I am Good'


health.add_check(howami)
'''
Function crestes padding to the vector such that each batch will have vectors of
maximum size.

args: vector, size of vector

returns: padded vector
'''
Exemple #29
0
from flask import Flask
from healthcheck import HealthCheck

app = Flask(__name__)
health = HealthCheck()


@app.route('/')
def hello():
    return "base-image-slim flask app... Hello World!"


app.add_url_rule("/healthz", "healthz", view_func=lambda: health.run())

if __name__ == '__main__':
    app.run(host='0.0.0.0')
Exemple #30
0
def hello():
    return "Countries Services App!"

@app.route('/v1/countries')
def query_example():

    target = request.args.get('target')

    # being a restfull api and needing to look up information based on requests it natural to have a db but, I will add it to a db like PostgreSql - there wasn't enough time

    if target == "source":
        return jsonify(
            [{"name": "United Kingdom", "isoCode": "GB"}, {"name": "Ireland", "isoCode": "IE"}, {"name": "France", "isoCode": "FR"}]
        )
    elif target == "destinations":
        return jsonify(
            [{"name": "Spain", "isoCode": "ES"}, {"name": "Ireland", "isoCode": "IE"}, {"name": "France", "isoCode": "FR"}]
        )
    else:
        return 'API request not valid!'

health = HealthCheck(app, "/healthcheck")

def app_health():
	return True, "Health OK"

health.add_check(app_health)

if __name__ == '__main__':
    app.run(debug=True, host="0.0.0.0", port=8080)
from flask.ext.cors import CORS
import byu_ws_sdk as byu_ws
from datetime import datetime
import requests
import config
import json
import sys
import logging

logging.basicConfig(level=logging.DEBUG,
                    format='%(asctime)s %(levelname)s %(message)s',
                    filename='/tmp/timekeeper-import-ms.log',
                    filemode='w')

app = Flask(__name__)
health = HealthCheck(app, '/healthcheck')
envdump = EnvironmentDump(app, '/environment')
CORS(app)
api = Api(app)

def pretty_print_POST(req):
    """
    At this point it is completely built and ready
    to be fired; it is "prepared".

    However pay attention at the formatting used in
    this function because it is programmed to be pretty
    printed and may differ from the actual request.
    """
    return '{}\n{}\n{}\n\n{}'.format(
        '-----------START-----------',
from flask import Flask
from healthcheck import HealthCheck
import logging
from src.settings import BASE_PATH

log = logging.getLogger('werkzeug')
log.disabled = True

app = Flask(__name__)

health = HealthCheck()


def app_available():
    return True, "application ok"


health.add_check(app_available)
app.add_url_rule(f"{BASE_PATH}/health-check",
                 "healthcheck",
                 view_func=lambda: health.run())
Exemple #33
0
import os
from flask import Flask
from healthcheck import HealthCheck, EnvironmentDump
from bookshelf.config import config


app = Flask(__name__)
config_name = os.getenv('FLASK_CONFIGURATION', 'default')
app.config.from_object(config[config_name])
app.config.from_pyfile('config.cfg', silent=True)

health = HealthCheck(app, "/healthcheck")
envdump = EnvironmentDump(app, "/environment",
                          include_python=True, include_os=False,
                          include_process=False, include_config=True)


def sqlite_available():
    # add precise check against the database
    return True, "sqlite ok"


health.add_check(sqlite_available)


def application_data():
    return {"maintainer": "Damyan Bogoev",
            "git_repo": "https://github.com/damyanbogoev/flask-bookshelf"}


envdump.add_section("application", application_data)
Exemple #34
0
from flask import Flask, make_response, jsonify
from healthcheck import HealthCheck
from api.model.base_model import db
from flask_migrate import Migrate
from flask_migrate import upgrade
from flasgger import Swagger
from flask_cors import CORS
import os

environ = os.getenv("APP_ENV", "Development") if \
    os.getenv("APP_ENV", "Development") in ["Development", "Production", "Testing"] \
    else "Development"

app = Flask(__name__)

health = HealthCheck(app, "/api/ping")

CORS(app)
app.config.from_object('api.settings.config.{}Config'.format(environ))

app.config['SWAGGER'] = {
    'title': 'Quality Engine API',
    'uiversion': 3
}

swagger_template = {
    "swagger": "2.0",
    "info": {
        "title": "TD-QE",
        "description": "TD-QE API",
        "version": "0.0.1"
        def __call__(self, *args, **kwargs):
            if current_app.config['TESTING']:
                with app.test_request_context():
                    return task_base.__call__(self, *args, **kwargs)
            with app.app_context():
                return task_base.__call__(self, *args, **kwargs)

    celery.Task = ContextTask
    return celery


celery = make_celery(current_app)

# Health-check
health = HealthCheck(current_app, "/health-check")
envdump = EnvironmentDump(current_app, "/environment", include_config=False)
health.add_check(health_check_celery)
health.add_check(health_check_db)
with current_app.app_context():
    current_app.config['MIGRATION_STATUS'] = check_migrations()
health.add_check(health_check_migrations)


# http://stackoverflow.com/questions/9824172/find-out-whether-celery-task-exists
@after_task_publish.connect
def update_sent_state(sender=None, body=None, **kwargs):
    # the task may not exist if sent using `send_task` which
    # sends tasks by name, so fall back to the default result backend
    # if that is the case.
    task = celery.tasks.get(sender)
import base64
import uuid
import cv2
import requests
import connexion
from config.kafka_producer_config import producer
from controller import *
from flask import request, jsonify
from healthcheck import HealthCheck
from keras.models import load_model
from flask_cors import CORS

# Configure Healthcheck
health = HealthCheck()


# Main Method. Will be called by Connexion and Connected with Swagger
def tampered_image_processing():
    try:
        requested_model = request.form['model']

        if choose_model(requested_model) == 'error':
            val = {
                'status': 'error',
                'message': 'Model Not Found!'
            }
            return jsonify(val), 400

        # Load the model
        model = load_model(choose_model(requested_model))
Exemple #37
0
#!flask/bin/python
from flask import Flask, request, abort
import json
import redis
import random
import string
from healthcheck import HealthCheck

health = HealthCheck()


def randomword(length):
    return ''.join(random.choice(string.ascii_letters) for i in range(length))


app = Flask(__name__)
r = redis.StrictRedis(host='redis', port=6379, db=0)


def redis_available():
    info = r.info()
    assert info, "problems"
    return True, "redis ok"


health.add_check(redis_available)
app.add_url_rule("/healthcheck", view_func=lambda: health.run())


@app.route("/", methods=['POST'])
def register():
from flask import Flask, request, render_template
# from utils import upload_to_aws,bucket_name
from healthcheck import HealthCheck
import os

application = app = Flask(__name__, template_folder='templates')

App_path = os.path.dirname(os.path.abspath(__file__))


@app.route('/home')
def home():
    return render_template('index.html')


def app_status():
    """
    added health check
    """
    return True, "App is up and running"


health = HealthCheck(app, "/healthcheck")
health.add_check(app_status)

if __name__ == '__main__':
    app.run(debug=True, host='0.0.0.0', port=5000)