예제 #1
0
 def auth_api_call(self, method, resource, data=None, status=200, headers={}):
     method = method.lower()
     if method.lower() in ('put', 'post', 'patch'):
         if data and isinstance(data, dict):
             payload = json_stringify(data)
         else:
             payload = data
         data = None
         as_header = False
     else:
         payload = resource.split('?')[0]
         as_header = True
     now = int(mktime(datetime.utcnow().utctimetuple())) * 1000
     jws_headers = json_stringify({
         'alg': 'RS256',
         'kikUsr': self.USERNAME,
         'exp': now + 1000 * 60 * 60 * 2,
         'x5u': self.HOSTNAME,
         'nbf': now - 1000 * 60 * 60,
         'kikCrdDm': self.HOSTNAME,
         'kikDbg': True
     })
     jws = '.'.join(p.encode('base64').strip().replace('=', '') for p in [
         jws_headers, payload, 'signature'
     ])
     if as_header:
         headers[KIK_JWS] = jws
     else:
         headers['Content-Type'] = 'text/plain'
         data = jws
     return self.api_call(method, resource, data=data, status=status, headers=headers)
예제 #2
0
	def respond(self, data, content_type='application/json', cache_life=0, headers={}):
		self.security_headers()
		self.cors_headers()
		self.cache_header(cache_life)

		for header, value in headers.items():
			if header == 'Content-Type':
				content_type = value
			else:
				self.response.headers[header] = value

		if content_type == 'application/json':
			if isinstance(data, BaseModel):
				data = data.to_dict()
			elif isinstance(data, (list, tuple)) and len(data) > 0 and isinstance(data[0], BaseModel):
				data = [e.to_dict() for e in data]
			data = json_stringify(data, separators=(',',':'))

		# Let me begin with an apology. The Access-Control-Expose-Headers header is
		# not supported on most devices and prevents me from sending the session
		# token in a header. Instead of poluting the body of the response I have
		# decided to polute the Content-Type header with an extra parameter that
		# the client can read (because it is a "simple" header). I apologise for the
		# hackery that is below.
		if self.kik_session:
			content_type += '; kik-session=%s' % self.kik_session

		self.response.headers['Content-Type'] = content_type
		self.response.out.write(data)
		mixpanel.smart_flush()
예제 #3
0
 def call(body):
     cert = ('res/cert.pem', 'res/cert.key')
     headers = {'content-type': 'application/json'}
     response = requests.post(LAMBDA_URL, json_stringify(body), headers=headers, cert=cert)
     return {
         'body': response.text,
         'headers': dict(response.headers),
         'statusCode': response.status_code
     }
예제 #4
0
def step_impl(context, url_prefix):
    url = '%s/%s' % (url_prefix, context.userRecord.id)
    updatedUserData = __get_user_data()
    updateResponse = context.test.client.put(
        url, json_stringify(updatedUserData)).json()
    updatedUserRecord = UserRegistry.objects.get(id=context.userRecord.id)

    context.updatedUserData = updatedUserData
    context.updatedUserRecord = updatedUserRecord
    context.updateResponse = updateResponse
예제 #5
0
 def auth_api_call(self,
                   method,
                   resource,
                   data=None,
                   status=200,
                   headers={}):
     method = method.lower()
     if method.lower() in ('put', 'post', 'patch'):
         if data and isinstance(data, dict):
             payload = json_stringify(data)
         else:
             payload = data
         data = None
         as_header = False
     else:
         payload = resource.split('?')[0]
         as_header = True
     now = int(mktime(datetime.utcnow().utctimetuple())) * 1000
     jws_headers = json_stringify({
         'alg': 'RS256',
         'kikUsr': self.USERNAME,
         'exp': now + 1000 * 60 * 60 * 2,
         'x5u': self.HOSTNAME,
         'nbf': now - 1000 * 60 * 60,
         'kikCrdDm': self.HOSTNAME,
         'kikDbg': True
     })
     jws = '.'.join(
         p.encode('base64').strip().replace('=', '')
         for p in [jws_headers, payload, 'signature'])
     if as_header:
         headers[KIK_JWS] = jws
     else:
         headers['Content-Type'] = 'text/plain'
         data = jws
     return self.api_call(method,
                          resource,
                          data=data,
                          status=status,
                          headers=headers)
예제 #6
0
def flush(max_batches=10):
    global last_flush
    last_flush = time()

    if DONT_FLUSH_QUEUE:
        return

    size = min(queue.qsize(), max_batches * MAX_BATCH_SIZE)
    if not size:
        return

    events = []
    for index in range(size):
        try:
            events.append(queue.get_nowait())
            queue.task_done()
        except EmptyQueueException:
            break
    if not events:
        return

    # Do not send metrics events in debug mode
    from lib.utils import DEBUG
    if DEBUG:
        return

    rpcs = []
    for index in range(0, len(events), MAX_BATCH_SIZE):
        batch = events[index:index + MAX_BATCH_SIZE]
        data = 'data=' + b64encode(json_stringify(batch))
        rpc = urlfetch.create_rpc()
        try:
            urlfetch.make_fetch_call(
                rpc,
                API_URL,
                method='POST',
                headers={'Content-Type': 'application/x-www-form-urlencoded'},
                payload=data,
            )
            rpcs.append(rpc)
        except Exception as e:
            logging.error('failed to trigger urlfetch')
            logging.exception(e)

    for rpc in rpcs:
        try:
            rpc.wait()
        except Exception as e:
            logging.error('failed to resolve urlfetch')
            logging.exception(e)
예제 #7
0
def flush(max_batches=10):
	last_flush = time()

	if DONT_FLUSH_QUEUE:
		return

	size = min(queue.qsize(), max_batches*MAX_BATCH_SIZE)
	if not size:
		return

	events = []
	for index in range(size):
		try:
			events.append( queue.get_nowait() )
			queue.task_done()
		except EmptyQueueException:
			break
	if not events:
		return

	# Do not send metrics events in debug mode
	from lib.utils import DEBUG
	if DEBUG:
		return

	rpcs = []
	for index in range(0, len(events), MAX_BATCH_SIZE):
		batch = events[index:index+MAX_BATCH_SIZE]
		data  = 'data=' + b64encode(json_stringify(batch))
		rpc   = urlfetch.create_rpc()
		try:
			urlfetch.make_fetch_call(
				rpc,
				API_URL,
				method  = 'POST',
				headers = { 'Content-Type' : 'application/x-www-form-urlencoded' },
				payload = data,
			)
			rpcs.append(rpc)
		except Exception as e:
			logging.error('failed to trigger urlfetch')
			logging.exception(e)

	for rpc in rpcs:
		try:
			rpc.wait()
		except Exception as e:
			logging.error('failed to resolve urlfetch')
			logging.exception(e)
예제 #8
0
def track(distinct_id, event_name, properties=None):
	if properties is None:
		properties = {}
	properties['token'      ] = MiXPANEL_TOKEN
	properties['distinct_id'] = distinct_id
	event = {
		'event'      : event_name,
		'properties' : properties,
	}
	if not last_flush:
		last_flush = time()
	try:
		queue.put_nowait(event)
	except FullQueueException:
		logging.error('mixpanel queue is full, failed to log event=%s' % json_stringify(event))
예제 #9
0
    def respond(self,
                data,
                content_type='application/json',
                cache_life=0,
                headers={}):
        self.security_headers()
        self.cors_headers()
        self.cache_header(cache_life)

        for header, value in headers.items():
            if header == 'Content-Type':
                content_type = value
            else:
                self.response.headers[header] = value

        if content_type == 'application/json':
            if isinstance(data, BaseModel):
                data = data.to_dict()
            elif isinstance(data,
                            (list, tuple)) and len(data) > 0 and isinstance(
                                data[0], BaseModel):
                data = [e.to_dict() for e in data]
            data = json_stringify(data, separators=(',', ':'))

        # Let me begin with an apology. The Access-Control-Expose-Headers header is
        # not supported on most devices and prevents me from sending the session
        # token in a header. Instead of poluting the body of the response I have
        # decided to polute the Content-Type header with an extra parameter that
        # the client can read (because it is a "simple" header). I apologise for the
        # hackery that is below.
        if self.kik_session:
            content_type += '; kik-session=%s' % self.kik_session

        self.response.headers['Content-Type'] = content_type
        self.response.out.write(data)
        mixpanel.smart_flush()
예제 #10
0
 def call(body):
     return process_event({'body': json_stringify(body)}, {})