示例#1
0
文件: wfastcgi.py 项目: yuts/PTVS
def read_wsgi_handler(physical_path):
    global APPINSIGHT_CLIENT
    env = get_environment(physical_path)
    os.environ.update(env)
    for path in (v for k, v in env.items() if k.lower() == 'pythonpath'):
        # Expand environment variables manually.
        expanded_path = re.sub('%(\\w+?)%',
                               lambda m: os.getenv(m.group(1), ''), path)
        sys.path.extend(fs_encode(p) for p in expanded_path.split(';') if p)

    handler = get_wsgi_handler(os.getenv("WSGI_HANDLER"))
    instr_key = os.getenv("APPINSIGHTS_INSTRUMENTATIONKEY")
    if instr_key:
        try:
            # Attempt the import after updating sys.path - sites must
            # include applicationinsights themselves.
            from applicationinsights.requests import WSGIApplication
        except ImportError:
            maybe_log("Failed to import applicationinsights: " +
                      traceback.format_exc())
        else:
            handler = WSGIApplication(instr_key, handler)
            APPINSIGHT_CLIENT = handler.client
            # Ensure we will flush any remaining events when we exit
            on_exit(handler.client.flush)

    return env, handler
示例#2
0
    def _init_request_logging(self, app):
        """
        Sets up request logging unless ``APPINSIGHTS_DISABLE_REQUEST_LOGGING``
        is set in the Flask config.

        Args:
            app (flask.Flask). the Flask application for which to initialize the extension.
        """
        enabled = not app.config.get(CONF_DISABLE_REQUEST_LOGGING, False)

        if not enabled:
            return

        self._requests_middleware = WSGIApplication(
            self._key, app.wsgi_app, telemetry_channel=self._channel)

        app.wsgi_app = self._requests_middleware
示例#3
0
class AppInsights(object):
    """ This class represents a Flask extension that enables request telemetry,
    trace logging and exception logging for a Flask application. The telemetry
    will be sent to Application Insights service using the supplied
    instrumentation key.

    The following Flask config variables can be used to configure the extension:

    - Set ``APPINSIGHTS_INSTRUMENTATIONKEY`` to a string to provide the
      instrumentation key to send telemetry to application insights.
      Alternatively, this value can also be provided via an environment variable
      of the same name.

    - Set ``APPINSIGHTS_ENDPOINT_URI`` to a string to customize the telemetry
      endpoint to which Application Insights will send the telemetry.

    - Set ``APPINSIGHTS_DISABLE_REQUEST_LOGGING`` to ``False`` to disable
      logging of Flask requests to Application Insights.

    - Set ``APPINSIGHTS_DISABLE_TRACE_LOGGING`` to ``False`` to disable logging
      of all log traces to Application Insights.

    - Set ``APPINSIGHTS_DISABLE_EXCEPTION_LOGGING`` to ``False`` to disable
      logging of all exceptions to Application Insights.

    .. code:: python

            from flask import Flask
            from applicationinsights.flask.ext import AppInsights

            # instantiate the Flask application
            app = Flask(__name__)
            app.config['APPINSIGHTS_INSTRUMENTATIONKEY'] = '<YOUR INSTRUMENTATION KEY GOES HERE>'

            # log requests, traces and exceptions to the Application Insights service
            appinsights = AppInsights(app)

            # define a simple route
            @app.route('/')
            def hello_world():
                return 'Hello World!'

            # run the application
            if __name__ == '__main__':
                app.run()
    """
    def __init__(self, app=None):
        """
        Initialize a new instance of the extension.

        Args:
            app (flask.Flask). the Flask application for which to initialize the extension.
        """
        self._key = None
        self._endpoint_uri = None
        self._channel = None
        self._requests_middleware = None
        self._trace_log_handler = None
        self._exception_telemetry_client = None

        if app:
            self.init_app(app)

    def init_app(self, app):
        """
        Initializes the extension for the provided Flask application.

        Args:
            app (flask.Flask). the Flask application for which to initialize the extension.
        """
        self._key = app.config.get(CONF_KEY) or getenv(CONF_KEY)

        if not self._key:
            return

        self._endpoint_uri = app.config.get(CONF_ENDPOINT_URI)
        sender = AsynchronousSender(self._endpoint_uri)

        queue = AsynchronousQueue(sender)
        self._channel = TelemetryChannel(None, queue)

        self._init_request_logging(app)
        self._init_trace_logging(app)
        self._init_exception_logging(app)

    @property
    def context(self):
        """
        Accesses the telemetry context.

        Returns:
            (applicationinsights.channel.TelemetryContext). The Application Insights telemetry context.
        """
        return self._channel.context

    def _init_request_logging(self, app):
        """
        Sets up request logging unless ``APPINSIGHTS_DISABLE_REQUEST_LOGGING``
        is set in the Flask config.

        Args:
            app (flask.Flask). the Flask application for which to initialize the extension.
        """
        enabled = not app.config.get(CONF_DISABLE_REQUEST_LOGGING, False)

        if not enabled:
            return

        self._requests_middleware = WSGIApplication(
            self._key, app.wsgi_app, telemetry_channel=self._channel)

        app.wsgi_app = self._requests_middleware

    def _init_trace_logging(self, app):
        """
        Sets up trace logging unless ``APPINSIGHTS_DISABLE_TRACE_LOGGING`` is
        set in the Flask config.

        Args:
            app (flask.Flask). the Flask application for which to initialize the extension.
        """
        enabled = not app.config.get(CONF_DISABLE_TRACE_LOGGING, False)

        if not enabled:
            return

        self._trace_log_handler = LoggingHandler(
            self._key, telemetry_channel=self._channel)

        app.logger.addHandler(self._trace_log_handler)

    def _init_exception_logging(self, app):
        """
        Sets up exception logging unless ``APPINSIGHTS_DISABLE_EXCEPTION_LOGGING``
        is set in the Flask config.

        Args:
            app (flask.Flask). the Flask application for which to initialize the extension.
        """
        enabled = not app.config.get(CONF_DISABLE_EXCEPTION_LOGGING, False)

        if not enabled:
            return

        exception_telemetry_client = TelemetryClient(
            self._key, telemetry_channel=self._channel)

        @app.errorhandler(Exception)
        def exception_handler(exception):
            if HTTPException and isinstance(exception, HTTPException):
                return exception

            try:
                raise exception
            except Exception:
                exception_telemetry_client.track_exception()
            finally:
                raise exception

        self._exception_telemetry_client = exception_telemetry_client

    def flush(self):
        """Flushes the queued up telemetry to the service.
        """
        if self._requests_middleware:
            self._requests_middleware.flush()

        if self._trace_log_handler:
            self._trace_log_handler.flush()

        if self._exception_telemetry_client:
            self._exception_telemetry_client.flush()
"""
The flask application package.
"""

from flask import Flask
from os import environ
from applicationinsights.requests import WSGIApplication
app = Flask(__name__)
#app.wsgi_app = WSGIApplication(environ.get('APPINSIGHTS_INSTRUMENTATIONKEY'), app.wsgi_app)
app.wsgi_app = WSGIApplication("703a7d6b-285b-4a27-b7fe-aad4a029fd1e",
                               app.wsgi_app)
import python_webapp_flask.views
class AppInsights(object):
    """This class represents a Flask extension that enables request telemetry,
    trace logging and exception logging for a Flask application. The telemetry
    will be sent to Application Insights service using the supplied
    instrumentation key.

    The following Flask config variables can be used to configure the extension:

    - Set ``APPINSIGHTS_INSTRUMENTATIONKEY`` to a string to provide the
      instrumentation key to send telemetry to application insights.
      Alternatively, this value can also be provided via an environment variable
      of the same name.

    - Set ``APPINSIGHTS_ENDPOINT_URI`` to a string to customize the telemetry
      endpoint to which Application Insights will send the telemetry.

    - Set ``APPINSIGHTS_DISABLE_REQUEST_LOGGING`` to ``False`` to disable
      logging of Flask requests to Application Insights.

    - Set ``APPINSIGHTS_DISABLE_TRACE_LOGGING`` to ``False`` to disable logging
      of all log traces to Application Insights.

    - Set ``APPINSIGHTS_DISABLE_EXCEPTION_LOGGING`` to ``False`` to disable
      logging of all exceptions to Application Insights.

    .. code:: python

            from flask import Flask
            from ai4e_app_insights import AppInsights

            # instantiate the Flask application
            app = Flask(__name__)
            app.config['APPINSIGHTS_INSTRUMENTATIONKEY'] = '<YOUR INSTRUMENTATION KEY GOES HERE>'

            # log requests, traces and exceptions to the Application Insights service
            appinsights = AppInsights(app)

            # define a simple route
            @app.route('/')
            def hello_world():
                return 'Hello World!'

            # run the application
            if __name__ == '__main__':
                app.run()
    """
    def __init__(self, app=None, context=None):
        """
        Initialize a new instance of the extension.

        Args:
            app (flask.Flask). the Flask application for which to initialize the extension.
        """
        socket.setdefaulttimeout(30)
        self._appinsights_key = None
        self._endpoint_uri = None
        self._channel = None
        self._requests_middleware = None
        self._trace_log_handler_grantee = None
        self._trace_log_handler_ai4e = None
        self._exception_telemetry_client_grantee = None
        self._exception_telemetry_client_ai4e = None

        if app:
            self.init_app(app, context)

    def init_app(self, app, context):
        """
        Initializes the extension for the provided Flask application.

        Args:
            app (flask.Flask). the Flask application for which to initialize the extension.
        """
        print("Starting application insights module.")
        self._appinsights_key = app.config.get(
            APPINSIGHTS_INSTRUMENTATIONKEY) or getenv(
                APPINSIGHTS_INSTRUMENTATIONKEY)

        if self._appinsights_key and len(self._appinsights_key.strip()) > 0:
            self._appinsights_key = self._appinsights_key.strip()
        else:
            self._appinsights_key = None

        # Set the application insights key for production use.
        if self._appinsights_key:
            print("Application insights key set.")

        self._endpoint_uri = app.config.get(CONF_ENDPOINT_URI)

        if self._endpoint_uri:
            sender = AsynchronousSender(self._endpoint_uri)
        else:
            sender = AsynchronousSender()

        queue = AsynchronousQueue(sender)

        if not context:
            context = AI4ETelemetryContext()

        self._channel = TelemetryChannel(context, queue)

        self._init_request_logging(app)
        self._init_trace_logging(app)
        self._init_exception_logging(app)

    def _init_request_logging(self, app):
        """
        Sets up request logging unless ``APPINSIGHTS_DISABLE_REQUEST_LOGGING``
        is set in the Flask config.

        Args:
            app (flask.Flask). the Flask application for which to initialize the extension.
        """
        enabled = not app.config.get(CONF_DISABLE_REQUEST_LOGGING, False)

        if not enabled:
            return

        wsgi_key = self._appinsights_key

        self._requests_middleware = WSGIApplication(
            wsgi_key, app.wsgi_app, telemetry_channel=self._channel)

        app.wsgi_app = self._requests_middleware

    def _init_trace_logging(self, app):
        """
        Sets up trace logging unless ``APPINSIGHTS_DISABLE_TRACE_LOGGING`` is
        set in the Flask config.

        Args:
            app (flask.Flask). the Flask application for which to initialize the extension.
        """
        enabled = not app.config.get(CONF_DISABLE_TRACE_LOGGING, False)

        if not enabled:
            return

        if self._appinsights_key:
            self._trace_log_handler_grantee = LoggingHandler(
                self._appinsights_key, telemetry_channel=self._channel)

            app.logger.addHandler(self._trace_log_handler_grantee)

    def _init_exception_logging(self, app):
        """
        Sets up exception logging unless ``APPINSIGHTS_DISABLE_EXCEPTION_LOGGING``
        is set in the Flask config.

        Args:
            app (flask.Flask). the Flask application for which to initialize the extension.
        """
        enabled = not app.config.get(CONF_DISABLE_EXCEPTION_LOGGING, False)

        if not enabled:
            return

        if self._appinsights_key:
            self._exception_telemetry_client_grantee = TelemetryClient(
                self._appinsights_key, telemetry_channel=self._channel)

        @app.errorhandler(Exception)
        def exception_handler(exception):
            try:
                raise exception
            except Exception:
                if self._exception_telemetry_client_grantee:
                    self._exception_telemetry_client_grantee.track_exception()

                if self._exception_telemetry_client_ai4e:
                    self._exception_telemetry_client_ai4e.track_exception()
            finally:
                raise exception

    def flush(self):
        """Flushes the queued up telemetry to the service."""
        print("trying all flush")
        if self._requests_middleware:
            self._requests_middleware.flush()

        if self._trace_log_handler_grantee:
            self._trace_log_handler_grantee.flush()

        if self._trace_log_handler_ai4e:
            print("Trying trace flush...")
            self._trace_log_handler_ai4e.flush()
            print("Trace flush finsihed.")

        if self._exception_telemetry_client_grantee:
            self._exception_telemetry_client_grantee.flush()

        if self._exception_telemetry_client_ai4e:
            self._exception_telemetry_client_ai4e.flush()
示例#6
0
"""
The flask application package.
"""

from flask import Flask
from os import environ
from applicationinsights.requests import WSGIApplication
app = Flask(__name__)
app.wsgi_app = WSGIApplication(environ.get('APPINSIGHTS_INSTRUMENTATIONKEY'), app.wsgi_app)
import python_webapp_flask.views




示例#7
0
import os
import time
import random
from eval import *
from flask import Flask, jsonify, request, abort
from applicationinsights import TelemetryClient
from applicationinsights.requests import WSGIApplication
from applicationinsights.exceptions import enable
from src.miscc.config import cfg
#from werkzeug.contrib.profiler import ProfilerMiddleware

enable(os.environ["TELEMETRY"])
app = Flask(__name__)
app.wsgi_app = WSGIApplication(os.environ["TELEMETRY"], app.wsgi_app)


@app.route('/api/v1.0/bird', methods=['POST'])
def create_bird():
    if not request.json or not 'caption' in request.json:
        abort(400)

    caption = request.json['caption']

    t0 = time.time()
    urls = generate(caption, wordtoix, ixtoword, text_encoder, netG,
                    blob_service)
    t1 = time.time()

    response = {
        'small': urls[0],
        'medium': urls[1],
示例#8
0
def get_application_insights_hook():
    return WSGIApplication('104f9dca-6034-42a1-a646-7c66230710e7', application)
示例#9
0
文件: api.py 项目: dhermyt/WONS
from voluptuous import Required, Schema, All, Length, MultipleInvalid, In, Optional

from configuration.appsettings import Settings

sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))

from flask import Flask, redirect
from flask_restful import Resource, Api, reqparse
from applicationinsights.requests import WSGIApplication

app = Flask(__name__, static_folder='assets')
if os.environ.get(
        'APPSETTING_APPLICATION_INSIGHTS_INSTRUMENTATION_KEY') is not None:
    app.wsgi_app = WSGIApplication(
        os.environ.get('APPSETTING_APPLICATION_INSIGHTS_INSTRUMENTATION_KEY'),
        app.wsgi_app)
api = Api(app)


class SentimentAnalysis(Resource):
    parser = reqparse.RequestParser()
    parser.add_argument('text')
    schema = Schema({Required('text'): All(str, Length(min=1, max=1000))})
    toolbox = SentimentAnalysisToolbox()
    decoder = SettingsDecoder()
    settings = toolbox.load_json('default', Settings())
    settings.LEMMATIZER_TYPE = decoder.decode_type(settings.LEMMATIZER_TYPE)
    settings.CLASSIFIER_TYPE = decoder.decode_classifier(
        settings.CLASSIFIER_TYPE)
    classifier = settings.CLASSIFIER_TYPE()
示例#10
0
    return template('servicelist',
                    update_list=list_db,
                    request=request,
                    pageinfo=dict({
                        "page": page,
                        "condition": condition,
                        "itemnum": itemnum,
                        "max_pagenum": max_pagenum
                    }),
                    prev_page_query=prev_page_query,
                    next_page_query=next_page_query,
                    product_list=dropdown_list[DROP_DOWN_ID['product']],
                    updatetype_list=dropdown_list[DROP_DOWN_ID['updateType']],
                    platform_list=dropdown_list[DROP_DOWN_ID['platform']],
                    service_type_list=dropdown_list['service-type'])


@route('/static/<file_path:path>')
def static(file_path):
    return static_file(file_path, root=BASE_DIR + '/static')


if __name__ == '__main__':
    # コマンドから"python3 index.py"で起動した場合
    run(host='0.0.0.0', port=8080, debug=True)

else:
    # uWSGIから起動した場合
    application = WSGIApplication('d81d5112-0abe-4629-90f6-643911773e45',
                                  default_app())
示例#11
0
import hy
from bottle import DEBUG, default_app
from sushy.config import DEBUG_MODE, INSTRUMENTATION_KEY
import sushy.routes

import newrelic.agent
newrelic.agent.initialize()

DEBUG = DEBUG_MODE

if INSTRUMENTATION_KEY:
    from applicationinsights.requests import WSGIApplication
    app = WSGIApplication(INSTRUMENTATION_KEY, default_app())
else:
    app = default_app()
示例#12
0
import jwt
from flask import Flask, redirect, url_for, session, request, render_template
from flask_oauthlib.client import OAuth, OAuthException, log
from applicationinsights.requests import WSGIApplication
from applicationinsights import TelemetryClient

# from flask_sslify import SSLify


import configparser
CONFIG = configparser.SafeConfigParser()
CONFIG.read('config')

app = Flask(__name__)
#sslify = SSLify(app)
app.wsgi_app = WSGIApplication(CONFIG.get('setting', 'APPLICATION_INSIGHTS_KEY'), app.wsgi_app)
app.debug = True
app.secret_key = 'development'
oauth = OAuth(app)

tc = TelemetryClient(CONFIG.get('setting', 'APPLICATION_INSIGHTS_KEY'))


from logging import basicConfig, getLogger
logger = getLogger(__name__)
debug_level = CONFIG.get('setting', 'LOGLEVEL')
basicConfig(level=debug_level,
            format='* %(asctime)s:%(levelname)s:%(name)s:%(lineno)s:%(message)s')


# Put your consumer key and consumer secret into a config file