Beispiel #1
0
def log_analytics(request, event, properties):
    try:
        import analytics
        from ipware.ip import get_ip as get_ip

        if settings.DEBUG: return
        if not hasattr(settings, "SEGMENT_IO_KEY"):
            logger.warning("Cannot send analytics. No Segment IO Key has been set")
            return

        if "pingdom" in request.META.get("HTTP_USER_AGENT", ""):
            logger.warning("Not recording analytics. Ignored pingdom bot")
            return

        api_key = settings.SEGMENT_IO_KEY

        ip = get_ip(request)

        name = names.get_full_name()
        uid = request.session.get("uid", name)
        request.session["uid"] = uid
        analytics.init(api_key)
        analytics.identify(uid,
            {
                "$name" : uid,
            },
            { "$ip" : ip}
        )
        analytics.track(uid, event=event, properties=properties)
    except Exception, e:
        logger.exception("Error handling analytics")
def run():
    """
    Executed during django startup
    """
    django_utils_translation.patch()

    autostartup()

    add_mimetypes()

    if settings.FEATURES.get('USE_CUSTOM_THEME', False):
        enable_stanford_theme()

    if settings.FEATURES.get('USE_MICROSITES', False):
        enable_microsites()

    if settings.FEATURES.get('ENABLE_THIRD_PARTY_AUTH', False):
        enable_third_party_auth()

    # Initialize Segment.io analytics module. Flushes first time a message is received and
    # every 50 messages thereafter, or if 10 seconds have passed since last flush
    if settings.FEATURES.get('SEGMENT_IO_LMS') and hasattr(settings, 'SEGMENT_IO_LMS_KEY'):
        analytics.init(settings.SEGMENT_IO_LMS_KEY, flush_at=50)

    # register any dependency injections that we need to support in edx_proctoring
    # right now edx_proctoring is dependent on the openedx.core.djangoapps.credit
    # as well as the instructor dashboard (for deleting student attempts)
    if settings.FEATURES.get('ENABLE_PROCTORED_EXAMS'):
        # Import these here to avoid circular dependencies of the form:
        # edx-platform app --> DRF --> django translation --> edx-platform app
        from edx_proctoring.runtime import set_runtime_service
        from instructor.services import InstructorService
        from openedx.core.djangoapps.credit.services import CreditService
        set_runtime_service('credit', CreditService())
        set_runtime_service('instructor', InstructorService())
Beispiel #3
0
def run():
    """
    Executed during django startup
    """

    # Patch the xml libs.
    from safe_lxml import defuse_xml_libs
    defuse_xml_libs()

    django_utils_translation.patch()

    autostartup()

    add_mimetypes()

    if settings.FEATURES.get('USE_CUSTOM_THEME', False):
        enable_theme()

    if settings.FEATURES.get('USE_MICROSITES', False):
        enable_microsites()

    if settings.FEATURES.get('ENABLE_THIRD_PARTY_AUTH', False):
        enable_third_party_auth()

    # Initialize Segment.io analytics module. Flushes first time a message is received and 
    # every 50 messages thereafter, or if 10 seconds have passed since last flush
    if settings.FEATURES.get('SEGMENT_IO_LMS') and hasattr(settings, 'SEGMENT_IO_LMS_KEY'):
        analytics.init(settings.SEGMENT_IO_LMS_KEY, flush_at=50)
Beispiel #4
0
def run():
    """
    Executed during django startup
    """
    django_utils_translation.patch()

    autostartup()

    add_mimetypes()

    if settings.FEATURES.get('USE_CUSTOM_THEME', False):
        enable_theme()

    if settings.FEATURES.get('USE_MICROSITES', False):
        enable_microsites()

    if settings.FEATURES.get('ENABLE_THIRD_PARTY_AUTH', False):
        enable_third_party_auth()

    # Initialize Segment.io analytics module. Flushes first time a message is received and
    # every 50 messages thereafter, or if 10 seconds have passed since last flush
    if settings.FEATURES.get('SEGMENT_IO_LMS') and hasattr(
            settings, 'SEGMENT_IO_LMS_KEY'):
        analytics.init(settings.SEGMENT_IO_LMS_KEY, flush_at=50)

    # Monkey patch the keyword function map
    if keyword_substitution.keyword_function_map_is_empty():
        keyword_substitution.add_keyword_function_map(
            get_keyword_function_map())
        # Once keyword function map is set, make update function do nothing
        keyword_substitution.add_keyword_function_map = lambda x: None
Beispiel #5
0
def log_analytics(session, event, properties):
    if settings.DEBUG: return
    import analytics
    analytics.init('wdfkolf5dkr7gwh12jq7')
    analytics.track(user_id=session.session_key,
                    event=event,
                    properties=properties)
Beispiel #6
0
def run():
    """
    Executed during django startup
    """
    django_utils_translation.patch()

    autostartup()

    add_mimetypes()

    if settings.FEATURES.get('USE_CUSTOM_THEME', False):
        enable_theme()

    if settings.FEATURES.get('USE_MICROSITES', False):
        enable_microsites()

    if settings.FEATURES.get('ENABLE_THIRD_PARTY_AUTH', False):
        enable_third_party_auth()

    # Initialize Segment.io analytics module. Flushes first time a message is received and
    # every 50 messages thereafter, or if 10 seconds have passed since last flush
    if settings.FEATURES.get('SEGMENT_IO_LMS') and hasattr(settings, 'SEGMENT_IO_LMS_KEY'):
        analytics.init(settings.SEGMENT_IO_LMS_KEY, flush_at=50)

    # Monkey patch the keyword function map
    if keyword_substitution.keyword_function_map_is_empty():
        keyword_substitution.add_keyword_function_map(get_keyword_function_map())
        # Once keyword function map is set, make update function do nothing
        keyword_substitution.add_keyword_function_map = lambda x: None
Beispiel #7
0
def run():
    """
    Executed during django startup
    """
    django_utils_translation.patch()

    autostartup()

    add_mimetypes()

    if settings.FEATURES.get('USE_CUSTOM_THEME', False):
        enable_theme()

    if settings.FEATURES.get('USE_MICROSITES', False):
        enable_microsites()

    if settings.FEATURES.get('ENABLE_THIRD_PARTY_AUTH', False):
        enable_third_party_auth()

    # Initialize Segment.io analytics module. Flushes first time a message is received and
    # every 50 messages thereafter, or if 10 seconds have passed since last flush
    if settings.FEATURES.get('SEGMENT_IO_LMS') and hasattr(
            settings, 'SEGMENT_IO_LMS_KEY'):
        analytics.init(settings.SEGMENT_IO_LMS_KEY, flush_at=50)

    # register any dependency injections that we need to support in edx_proctoring
    # right now edx_proctoring is dependent on the openedx.core.djangoapps.credit
    # as well as the instructor dashboard (for deleting student attempts)
    if settings.FEATURES.get('ENABLE_PROCTORED_EXAMS'):
        set_runtime_service('credit', CreditService())
        set_runtime_service('instructor', InstructorService())
Beispiel #8
0
def run():
    """
    Executed during django startup
    """

    # Patch the xml libs.
    from safe_lxml import defuse_xml_libs
    defuse_xml_libs()

    django_utils_translation.patch()

    autostartup()

    add_mimetypes()

    if settings.FEATURES.get('USE_CUSTOM_THEME', False):
        enable_theme()

    if settings.FEATURES.get('USE_MICROSITES', False):
        enable_microsites()

    if settings.FEATURES.get('ENABLE_THIRD_PARTY_AUTH', False):
        enable_third_party_auth()

    # Initialize Segment.io analytics module. Flushes first time a message is received and
    # every 50 messages thereafter, or if 10 seconds have passed since last flush
    if settings.FEATURES.get('SEGMENT_IO_LMS') and hasattr(
            settings, 'SEGMENT_IO_LMS_KEY'):
        analytics.init(settings.SEGMENT_IO_LMS_KEY, flush_at=50)
Beispiel #9
0
def init_analytics():
    import analytics
    analytics_key = getattr(settings, 'SEGMENT_IO_KEY', None)
    if analytics_key:
        analytics.init(analytics_key,
                       send=settings.IS_PROD,
                       log=not settings.IS_PROD,
                       log_level=logging.DEBUG)
Beispiel #10
0
def init_analytics():
    import analytics
    analytics_key = getattr(settings, 'SEGMENT_IO_KEY', None)
    if analytics_key:
        analytics.init(analytics_key, send=settings.IS_PROD, log=not settings.IS_PROD, log_level=logging.DEBUG)

    from temba.utils.analytics import init_librato
    librato_user = getattr(settings, 'LIBRATO_USER', None)
    librato_token = getattr(settings, 'LIBRATO_TOKEN', None)
    if librato_user and librato_token:
        init_librato(librato_user, librato_token)
Beispiel #11
0
def init_analytics():
    import analytics
    analytics_key = getattr(settings, 'SEGMENT_IO_KEY', None)
    if analytics_key:  # pragma: needs cover
        analytics.init(analytics_key, send=settings.IS_PROD, log=not settings.IS_PROD, log_level=logging.DEBUG)

    from temba.utils.analytics import init_librato
    librato_user = getattr(settings, 'LIBRATO_USER', None)
    librato_token = getattr(settings, 'LIBRATO_TOKEN', None)
    if librato_user and librato_token:  # pragma: needs cover
        init_librato(librato_user, librato_token)
Beispiel #12
0
def run():
    """
    Executed during django startup
    """
    autostartup()

    add_mimetypes()

    if settings.FEATURES.get('USE_CUSTOM_THEME', False):
        enable_theme()

    if settings.FEATURES.get('USE_MICROSITES', False):
        enable_microsites()

    if settings.FEATURES.get('ENABLE_THIRD_PARTY_AUTH', False):
        enable_third_party_auth()

    # Initialize Segment.io analytics module. Flushes first time a message is received and 
    # every 50 messages thereafter, or if 10 seconds have passed since last flush
    if settings.FEATURES.get('SEGMENT_IO_LMS') and settings.SEGMENT_IO_LMS_KEY:
        analytics.init(settings.SEGMENT_IO_LMS_KEY, flush_at=50)
Beispiel #13
0
def run():
    """
    Executed during django startup
    """
    autostartup()

    add_mimetypes()

    if settings.FEATURES.get('USE_CUSTOM_THEME', False):
        enable_theme()

    if settings.FEATURES.get('USE_MICROSITES', False):
        enable_microsites()

    if settings.FEATURES.get('ENABLE_THIRD_PARTY_AUTH', False):
        enable_third_party_auth()

    # Initialize Segment.io analytics module. Flushes first time a message is received and
    # every 50 messages thereafter, or if 10 seconds have passed since last flush
    if settings.FEATURES.get('SEGMENT_IO_LMS') and settings.SEGMENT_IO_LMS_KEY:
        analytics.init(settings.SEGMENT_IO_LMS_KEY, flush_at=50)
Beispiel #14
0
def initialize_analytics(settings):
    """ Provide useful configuration to a Pyramid ``Configurator`` instance.

    Currently, this hook will set up and register Segment.io's analytics.
    The following configurations are required in your configuration file:
        ``analytics.secret``
        ``analytics.flush_at``
        ``analytics.flush_after``
        ``analytics.async``
        ``analytics.send``
        ``analytics.max_queue_size``

    Other configuration data should be copied from your Segment.io panel.
    More at http://segment.io.
    """

    # Logging
    analytics_log = logging.getLogger('analytics')
    log_level = analytics_log.level

    # Flush configuration
    flush_at = int(settings.get('analytics.flush_at', '20').strip())
    flush_seconds = int(settings.get('analytics.flush_after', '10').strip())
    flush_after = timedelta(seconds=flush_seconds)

    # Other environment details
    secret = settings.get('analytics.secret').strip()
    async = asbool(settings.get('analytics.async', 'True').strip())
    send = asbool(settings.get('analytics.send', 'True').strip())
    max_queue_size = int(settings.get(
        'analytics.max_queue_size', '10').strip())

    analytics.init(
        secret,
        log_level=log_level,
        flush_at=flush_at,
        flush_after=flush_after,
        async=async,
        send=send,
        max_queue_size=max_queue_size)
Beispiel #15
0
def initialize_analytics(settings):
    """ Provide useful configuration to a Pyramid ``Configurator`` instance.

    Currently, this hook will set up and register Segment.io's analytics.
    The following configurations are required in your configuration file:
        ``analytics.secret``
        ``analytics.flush_at``
        ``analytics.flush_after``
        ``analytics.async``
        ``analytics.send``
        ``analytics.max_queue_size``

    Other configuration data should be copied from your Segment.io panel.
    More at http://segment.io.
    """

    # Logging
    analytics_log = logging.getLogger('analytics')
    log_level = analytics_log.level

    # Flush configuration
    flush_at = int(settings.get('analytics.flush_at', '20').strip())
    flush_seconds = int(settings.get('analytics.flush_after', '10').strip())
    flush_after = timedelta(seconds=flush_seconds)

    # Other environment details
    secret = settings.get('analytics.secret').strip()
    async = asbool(settings.get('analytics.async', 'True').strip())
    send = asbool(settings.get('analytics.send', 'True').strip())
    max_queue_size = int(
        settings.get('analytics.max_queue_size', '10').strip())

    analytics.init(secret,
                   log_level=log_level,
                   flush_at=flush_at,
                   flush_after=flush_after,
                   async=async,
                   send=send,
                   max_queue_size=max_queue_size)
Beispiel #16
0
from django.http import HttpResponse
from session_manager import SessionManager
from django.core.serializers.json import DjangoJSONEncoder
from .models import Event
import time
from mongo_helper import ProfilesDao
import pystmark
from shapers import settings
from django.core.exceptions import ObjectDoesNotExist
from django.views.decorators.csrf import csrf_exempt
import datetime
import analytics
import requests

global session_manager
analytics.init("9mh6pdkn3t")

session_manager = SessionManager()

def get_client_ip(request):
    x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR')
    if x_forwarded_for:
        ip = x_forwarded_for.split(',')[0]
    else:
        ip = request.META.get('REMOTE_ADDR')
    return ip

def getEventInfo(event):
    out = {}
    out['startIn'] = (event.start_utc - datetime.datetime.utcnow()).total_seconds()*1000
    out['eventLength'] = (event.end_utc - event.start_utc).total_seconds()*1000
Beispiel #17
0
    def setUp(self):
        analytics.init(secret, log_level=logging.DEBUG)

        analytics.on_success(on_success)
        analytics.on_failure(on_failure)
Beispiel #18
0
from totalimpactwebapp import emailer
from totalimpactwebapp import configs

from totalimpactwebapp.util import camel_to_snake_case
from totalimpactwebapp import views_helpers
from totalimpactwebapp import welcome_email
from totalimpactwebapp import event_monitoring
from totalimpactwebapp import notification_report

from totalimpactwebapp.reference_set import RefsetBuilder

import newrelic.agent
from sqlalchemy import orm

logger = logging.getLogger("tiwebapp.views")
analytics.init(os.getenv("SEGMENTIO_PYTHON_KEY"), log_level=logging.INFO)












###############################################################################
#
#   CONVENIENCE FUNCTIONS
Beispiel #19
0
from flask import Flask

app = Flask(__name__)
app.config.from_object('coinvibes.settings')

import coinvibes.views
import coinvibes.exchange_apis
import coinvibes.utils
import coinvibes.api_v1

import analytics

analytics.init('5asae1e0a2gpb8uu0sx0')

## use HerokuRequest class so we get real IPs
app.request_class = utils.ProxiedRequest
Beispiel #20
0
from django.conf.urls import patterns, include, url
from django.views.generic import TemplateView
from app.views import *
from steps.views import *
from talk.views import *

import analytics, logging

from app.api import CanvasBlockList, CanvasBlockDetail, CanvasBlockItemList, CanvasBlockItemDetail
# Uncomment the next two lines to enable the admin:
from django.contrib import admin
admin.autodiscover()

analytics.init('kt58pb0ynb', flush_at=1)

urlpatterns = patterns('',
    # Examples:
    url('', include('social.apps.django_app.urls', namespace='social')),
    url(r'^oauth2callback/$', auth_return, name='oauth2-callback'),
    url(r'^ga-config/$', GAConfigView.as_view(), name='ga-config-view'),
    url(r'^ga/config/account/$', GAWeboptsView.as_view(), name='ga-config-account'),
    url(r'^ga/config/webprops/$', GAProfileView.as_view(), name='ga-config-webprops'),
    url(r'^ga/config/profile/$', GAProfileCompletedView.as_view(), name='ga-config-profile'),
    url(r'^ga/config/funnel/$', GAFunnelConfigAjaxView.as_view(), name='ga-config-funnel'),
    url(r'^ga-funnel/$', GAFunnelView.as_view(), name='ga-funnel-view'),
    url(r'^redactor/', include('redactor.urls')),

    url(r'^$', DashboardView.as_view(), name='home'),
    url(r'^subscribe/$', SubscribeView.as_view(), name='subscribe'),

    url(r'^accounts/', include('registration.backends.default.urls')),
Beispiel #21
0

# config and debugging stuff

app.config["SECRET_KEY"] = os.getenv("SECRET_KEY")

# set up Flask-DebugToolbar
if (os.getenv("FLASK_DEBUG", False) == "True"):
    logger.info("Setting app.debug=True; Flask-DebugToolbar will display")
    app.debug = True
    app.config["DEBUG_TB_INTERCEPT_REDIRECTS"] = False
    toolbar = DebugToolbarExtension(app)


# segment.io logging
analytics.init(os.getenv("SEGMENTIO_PYTHON_KEY"))
analytics.identify("CORE", {
				       'internal': True,
				       'name': 'IMPACTSTORY CORE'})




# set up views and database, if necessary
try:
	from totalimpact import views
except exc.ProgrammingError:
	logger.info("SQLAlchemy database tables not found, so creating them")
	db.session.rollback()
	db.create_all()
	from totalimpact import views
Beispiel #22
0
    return Response(server_social_distance_detector.gen_social_distancing(2),mimetype='multipart/x-mixed-replace; boundary=frame')

@app.route('/video_mask1')
def video_mask1():
    """Video streaming route. Put this in the src attribute of an img tag."""
    return Response(server_detect_mask.gen_mask(0),mimetype='multipart/x-mixed-replace; boundary=frame')

@app.route('/video_mask2')
def video_mask2():
    """Video streaming route. Put this in the src attribute of an img tag."""
    return Response(server_detect_mask.gen_mask(1),mimetype='multipart/x-mixed-replace; boundary=frame')

@app.route('/video_mask3')
def video_mask3():
    """Video streaming route. Put this in the src attribute of an img tag."""
    return Response(server_detect_mask.gen_mask(2),mimetype='multipart/x-mixed-replace; boundary=frame')



@app.route("/savePhoneNumber", methods=['POST'])
def savePhoneNumber():
    phone_number = request.json['data']
    print(phone_number) # Save this phone number somewhere
    return jsonify({
        "data": "SUCCESS",
    })

if __name__ == "__main__":
    analytics.init()
    app.run(host='127.0.0.1', port=5000, debug=True)
logging.basicConfig(
    stream=sys.stdout,
    level=logging.DEBUG,
    format='[%(process)d] %(levelname)8s %(threadName)30s %(name)s - %(message)s'
)
logger = logging.getLogger("impactstoryanalytics")


# set up application
app = Flask(__name__)

# allow slashes and end of URLs even when they're not part of views:
# http://flask.pocoo.org/mailinglist/archive/2011/2/27/re-automatic-removal-of-trailing-slashes/#043b1a0b6e841ab8e7d38bd7374cbb58
app.url_map.strict_slashes = False


# setup segment.io
analytics.init(os.getenv("SEGMENTIO_KEY"), log_level=logging.DEBUG, flush_at=1)
analytics.identify(user_id='Heather', traits={
    "name": "Heather",
    "email": "*****@*****.**",
})
analytics.identify(user_id='Jason', traits={
    "name": "Jason",
    "email": "*****@*****.**",
})


# set up views
from impactstoryanalytics import views
Beispiel #24
0
# -*- coding: utf-8 -*-
"""
    This little bit of code powers my d3Sever!!!

"""
import os, analytics
from flask import Flask, jsonify, render_template, request, abort
from jinja2 import TemplateNotFound
from flask.ext.assets import Environment, Bundle

analytics.init('82cl6i9bo6h4cnptal9b')

#instatntiate the web app 
app = Flask(__name__)



#determines if I am using this on Titan and turns of analytics
@app.context_processor
def isItTitan():
  if 'COMPUTERNAME' in os.environ.keys():
    t = os.environ['COMPUTERNAME'] == 'TITAN'
  else:
    t = False
  return dict(Titan = t)

#sets the asset environment to allow for scss compiling :)
#app.debug = True 

assets = Environment(app)
assets.url = app.static_url_path
Beispiel #25
0
def init_analytics():
    import analytics
    analytics_key = getattr(settings, 'SEGMENT_IO_KEY', None)
    if analytics_key:
        analytics.init(analytics_key, send=settings.IS_PROD, log=not settings.IS_PROD, log_level=logging.DEBUG)
Beispiel #26
0
from django.conf.urls import patterns, include, url
from reg_form import UserRegistrationForm
from registration.views import register
import regbackend
from django.conf import settings


# Uncomment the next two lines to enable the admin:
from django.contrib import admin
admin.autodiscover()

#analytics.js
import analytics
analytics.init('8q7671bxndzv1yk81jbn', flush_at=1)

#api
from tastypie.api import Api
from lts.api import SupplyResource, UserResource, OrderResource

v1_api = Api(api_name='v1')
v1_api.register(SupplyResource())
v1_api.register(UserResource())
v1_api.register(OrderResource())



urlpatterns = patterns('',
    #static files
    url(r'^static/(?P<path>.*)$', 'django.views.static.serve', {'document_root': settings.STATIC_ROOT}),

    #registration app
    cursor.close()


# config and debugging stuff

app.config["SECRET_KEY"] = os.getenv("SECRET_KEY")

# set up Flask-DebugToolbar
if (os.getenv("FLASK_DEBUG", False) == "True"):
    logger.info("Setting app.debug=True; Flask-DebugToolbar will display")
    app.debug = True
    app.config["DEBUG_TB_INTERCEPT_REDIRECTS"] = False
    toolbar = DebugToolbarExtension(app)

# segment.io logging
analytics.init(os.getenv("SEGMENTIO_PYTHON_KEY"))
analytics.identify("CORE", {'internal': True, 'name': 'IMPACTSTORY CORE'})

# set up views and database, if necessary
try:
    from totalimpact import views
except exc.ProgrammingError:
    logger.info("SQLAlchemy database tables not found, so creating them")
    db.session.rollback()
    db.create_all()
    from totalimpact import views

try:
    from totalimpact import extra_schema
except exc.ProgrammingError:
    logger.info("SQLAlchemy database tables not found, so creating them")
def log_analytics(session, event, properties):
    if settings.DEBUG: return
    import analytics
    analytics.init('wdfkolf5dkr7gwh12jq7')
    analytics.track(user_id=session.session_key, event=event, properties=properties)
Beispiel #29
0
    def setUp(self):
        analytics.init(secret, log_level=logging.DEBUG)

        analytics.on_success(on_success)
        analytics.on_failure(on_failure)