Пример #1
0
 def test_handle_failure_for_short_coords(self):
     req = '{"coordinates": "4, 34, 32"}'
     with self.assertRaises(SystemExit) as cm:
         handle(req)
     the_exception = cm.exception
     print(the_exception.code)
     self.assertEqual(the_exception.code, 'need 4 numbers\n')
Пример #2
0
def handle():
	"""
	Handler for `/api_name` methods
	**api_name = configured in api_hander hooks 
	### Examples:

	`/api_name/version/{methodname}` will call a whitelisted method
	
	"""
	parts = frappe.request.path[1:].split("/",3)
	method_name = version = api_name = method = None

	if len(parts) <= 2:
		if parts[1] == 'login':
			frappe.local.form_dict.cmd = '.'.join(map(str,[parts[0],parts[1]]))
			frappe.local.form_dict.op = "login"
			return handler.handle()

	elif len(parts) == 3:
		api_name = parts[0]
		version = parts[1]
		method_name = parts[2]
		method = '.'.join(map(str,[api_name,"versions",version,method_name]))
		frappe.local.form_dict.cmd = method
		return handler.handle()
	else:
		#invalid url
		return report_error(417,"Invalid URL")	
Пример #3
0
def test(username="******"):
    #test
    #save redis
    # temp = redisController(gvar.REDIS_HOST,gvar.REDIS_PORT)
    # videoname = "yolotest.mp4"
    # with open(videoname,"r+b") as src:
    #     videoBytes = src.read()
    # temp.saveVideo(videoname,videoBytes)

    db = mongodbController(gvar.MONGO_HOST, gvar.MONGO_PORT)
    handle(username)
    userid = db.getUserID(username, "done")
    print("Userid: ", userid)
    if userid == False:
        return

    #retrive image from mongo
    outpath = "/home/y/Documents/comp4651/upload/uploadtext/out/"
    if db.getUserProcess(userid) == "done":
        allimg = db.getAllImage(username, userid)
        for x in allimg:
            #print("image{} id: {}".format(x["frameno"],x["_id"]))
            # with open("{}{}_w.txt".format(outpath,x["name"]),"w") as des:
            #     des.write(x["base64"])
            out = base64.b64decode(x["base64"])
            with open("{}{}".format(outpath, x["name"]), "w+b") as des:
                des.write(out)
Пример #4
0
def handle_data(data, socko, to_read, to_write, to_error):
    if data[0:len("<policy-file-request/>")] == "<policy-file-request/>":
        socko.send( '<?xml version=\"1.0\"?><cross-domain-policy><allow-access-from domain="*" to-ports= "*" /></cross-domain-policy>')
        print "sent policy file"
        closesocket(socko)
    elif data[0:55] == "GET / HTTP/1.1\r\nUpgrade: WebSocket\r\nConnection: Upgrade":
        websocket_response = u"HTTP/1.1 101 Web Socket Protocol Handshake\r\nUpgrade: WebSocket\r\nConnection: Upgrade\r\nWebSocket-Origin: http://"+ hnp +"\r\nWebSocket-Location: ws://"+ hnp + websocket_location + "\r\n\r\n"
        socko.send(websocket_response)
        print websocket_response
        print "web socky"
    elif data[0:14] == "GET / HTTP/1.1": #normal http
        file = open("index.html", "r")
        contents = file.read()
        contents =  contents.replace("ws://host_here:port_here/", "ws://" + hnp + websocket_location )
        print "normal http"
        socko.send("HTTP/1.1 200 OK\r\n" 
        "Connection: close\r\n" +
        "Content-Type: text/html\r\n" +
        "Content-Length: " + str(len(contents)) + "\r\n\r\n" +
        contents)
    elif data[0:25] == "GET /favicon.ico HTTP/1.1":
        print "favicon"
        contents = open("favicon.png", "rb").read()
        socko.send("HTTP/1.1 200 OK\r\n" 
        "Connection: close\r\n" +
        "Content-Type: image/png\r\n" +
        "Content-Length: " + str(len(contents)) + "\r\n\r\n" +
        contents)
    elif (data[0] == "\x00" and data[-1] == "\xff"): #websocket format
        handler.handle(data[1:-1], socko, to_read, to_write, to_error, scope)
    else:
        print "you said"
        print data
        for i in data:
            print ord(i)
Пример #5
0
 def test_handle_failure_for_bad_req_structure(self):
     req = '{"nums": "4, 4", "point2": "34, 32"}'
     with self.assertRaises(SystemExit) as cm2:
         handle(req)
     the_exception = cm2.exception
     print(the_exception.code)
     self.assertEqual(the_exception.code, "coordinates can't be blank\n")
Пример #6
0
def test_handle_card_payment():
    dataDescriptor = 'COMMON.ACCEPT.INAPP.PAYMENT'
    dataValue = '9471471570959063005001'
    amount = 151

    print handle({
        'dataDescriptor': dataDescriptor,
        'dataValue': dataValue,
        'amount': amount,
        'command': 'payWithCard'
    })
Пример #7
0
def test_handle_paypal():
    amount = 151
    successUrl = 'https://localhost:8443/paypal-success'
    cancelUrl = 'https://localhost:8443/paypal-cancel'

    print handle({
        'command': 'paypal',
        'amount': amount,
        'successUrl': successUrl,
        'cancelUrl': cancelUrl
    })
Пример #8
0
def handle():
    """
	Handler for `/api_name` methods
	**api_name = configured in api_hander hooks 
	### Examples:

	`/api_name/version/{methodname}` will call a whitelisted method
	
	"""
    parts = frappe.request.path[1:].split("/", 4)
    method_name = version = api_name = method = response = None
    req_method = frappe.local.request.method

    # log_id = log_request(frappe.local.request, frappe.local.form_dict)

    if len(parts) <= 2:
        # if parts[1] == 'login':
        frappe.local.form_dict.cmd = '.'.join(map(str, [parts[0], parts[1]]))
        frappe.local.form_dict.op = parts[1]
        response = handler.handle()

    else:
        api_name = parts[0]
        version = parts[2].replace(".", "_")
        # frappe.local.form_dict.req_log_id = log_id
        if parts[3] == "method":
            method_name = parts[4]
            method = '.'.join(
                map(str, [api_name, "api.versions", version, method_name]))
            frappe.local.form_dict.cmd = method
            response = handler.handle()
        elif parts[3] == "resource":
            resource = dict(zip(["doctype", "docname"],
                                parts[4].split("/")[:]))
            method = '.'.join(map(str, [api_name, "api.resources.handle"]))

            frappe.local.form_dict.cmd = method
            frappe.local.form_dict.version = version
            frappe.local.form_dict.resource = resource
            frappe.local.form_dict.req_method = req_method

            response = handler.handle()
        else:
            response = report_error(417, "Invalid URL")

    # # log response
    # data = json.loads(response.data)
    # data.update({ "log_id":log_id })
    # response.data = json.dumps(data)
    # log_response(log_id, response.data)

    return response
Пример #9
0
def handle(api_config):
	"""
	Handler for `/api_name` methods
	**api_name = configured in api_hander hooks 
	### Examples:

	`/api_name/version/{methodname}` will call a whitelisted method
	
	"""
	parts = frappe.request.path[1:].split("/",5)
	method_name = version = api_name = method = None
	# return report_error(1, len(parts) >= 5 and parts[2] == "resource")
	if len(parts) <= 2:
		if parts[1] == 'login':
			frappe.local.form_dict.cmd = '.'.join(map(str,[parts[0],parts[1]]))
			frappe.local.form_dict.op = "login"
			return handler.handle()

	elif len(parts) == 4 and parts[2] == "method":
		version = parts[1]
		if not is_valid_version(version): 
			return report_error(417, "Invalid API Version")

		method_name = parts[3]
		method = '.'.join(map(str,[api_config.app_name, "versions", version, method_name]))

		frappe.local.form_dict.cmd = method
		return handler.handle()

	elif (len(parts) <= 4 or len(parts) >= 5) and parts[2] == "resource":
		version = parts[1] or ""
		
		frappe.local.form_dict.doctype = parts[3] or ""
		frappe.local.form_dict.name = parts[4] if len(parts) == 5 else ""

		if not is_valid_version(version): 
			return report_error(417, "Invalid API Version")

		method = '.'.join(map(str,[api_config.app_name, "versions", version.replace(".", "_"), "rest_api"]))
		frappe.local.form_dict.cmd = method

		if not is_valid_min_max_filters():
			return report_error(417, "Invalid Min or Max filter")
		# return report_error(417, frappe.local.form_dict)
		return handler.handle()

	else:
		#invalid url
		return report_error(417,"Invalid URL")
Пример #10
0
def test_vegas_cart_under_40():
    event = dict(subtotal=30, city='Las Vegas', state='NV')

    result = handle(event, None)

    assert result['freeShipping'] == False
    assert result['shippingCost'] == 5
Пример #11
0
def test_boulder_city_cart_at_40():
    event = dict(subtotal=40, city='Boulder City', state='NV')

    result = handle(event, None)

    assert result['freeShipping'] == False
    assert result['shippingCost'] == 10
Пример #12
0
def handles(response, to_handle):
	t_h = copy(to_handle)
	if t_h is not None:
		handler = t_h.pop('@handler','XPATH')
		response = handle(handler, response, t_h)
		return response
	else:
		return response
Пример #13
0
 def __call__(self, environ, start_response):
     request = werkzeug.Request(environ)
     m = self.mapper.match(environ=environ)
     if m is not None:
         handler = m["handler"](app=self, request=request, settings=self.settings)
         try:
             return handler.handle(**m)(environ, start_response)
         except werkzeug.exceptions.HTTPException, e:
             return e(environ, start_response)
Пример #14
0
def test_vegas_cart_at_40():
    event = dict(
        subtotal = 40,
        city = 'Las Vegas',
        state = 'NV'
    )

    result = handle(event, None)

    assert result['freeShipping'] == True
Пример #15
0
def main_route():
    warm_req = request.headers.get("X-Warm-Request", None) == 'true'
    if not warm_req:
        print('T4: %d' % get_monotonic_clock())

    ret = handler.handle(request)

    if not warm_req:
        print('T6: %d' % get_monotonic_clock())

    return ret.__close__()
Пример #16
0
def test_henderson_cart_at_40():
    event = dict(
        subtotal = 40,
        city = 'Henderson',
        state = 'NV'
    )

    result = handle(event, None)

    assert result['freeShipping'] == True
    assert result['shippingCost'] == 0
Пример #17
0
def main_route(path):
    raw_body = os.getenv("RAW_BODY", "false")

    as_text = True

    if is_true(raw_body):
        as_text = False

    # with proc_lock:
    g.start = time.time()
    ret = handler.handle(request.get_data(as_text=as_text))
    return ret
Пример #18
0
 def __call__(self, environ, start_response):
     with self.loghandler.threadbound():
         request = werkzeug.Request(environ)
         m = self.mapper.match(environ = environ)
         if m is not None:
             handler = m['handler'](app=self, request=request, settings=self.settings)
             try:
                 return handler.handle(**m)(environ, start_response)
             except werkzeug.exceptions.HTTPException, e:
                 return e(environ, start_response)
         # no view found => 404
         return werkzeug.exceptions.NotFound()(environ, start_response)
Пример #19
0
async def on_message(message):
    if message.content.startswith('$board'):
        comd = message.content[1:]
        try:
            op = handler.handle(comd)
            if op:
                await message.channel.send(
                    content="```Open attached with your browser.```", file=op)
        except Exception as e:
            print(e)
            await message.channel.send("```\nerrrrrrr\n```")
        return

    elif message.content.startswith('$'):
        comd = message.content[1:]
        try:
            op = handler.handle(comd)
            if op:
                await message.channel.send("```\n" + op + "\n```")
        except Exception as e:
            print(e)
            await message.channel.send("`errrrrrr`")
Пример #20
0
def transform():
    if request.method == 'POST':
        j = loads(request.get_data())
        url = j['fileUrl']
        data = handler.handle(url)
        return Response(dumps({
            'fileUrl': url,
            'data': data
        }),
                        mimetype='application/json')
    else:
        return Response(dumps({'message': 'healthy'}),
                        mimetype='application/json')
Пример #21
0
def handle_data(data, socko, to_read, to_write, to_error):
    if data[0:len("<policy-file-request/>")] == "<policy-file-request/>":
        socko.send(
            '<?xml version=\"1.0\"?><cross-domain-policy><allow-access-from domain="*" to-ports= "*" /></cross-domain-policy>'
        )
        print "sent policy file"
        closesocket(socko)
    elif data[
            0:
            55] == "GET / HTTP/1.1\r\nUpgrade: WebSocket\r\nConnection: Upgrade":
        websocket_response = u"HTTP/1.1 101 Web Socket Protocol Handshake\r\nUpgrade: WebSocket\r\nConnection: Upgrade\r\nWebSocket-Origin: http://" + hnp + "\r\nWebSocket-Location: ws://" + hnp + websocket_location + "\r\n\r\n"
        socko.send(websocket_response)
        print websocket_response
        print "web socky"
    elif data[0:14] == "GET / HTTP/1.1":  #normal http
        file = open("index.html", "r")
        contents = file.read()
        contents = contents.replace("ws://host_here:port_here/",
                                    "ws://" + hnp + websocket_location)
        print "normal http"
        socko.send("HTTP/1.1 200 OK\r\n"
                   "Connection: close\r\n" + "Content-Type: text/html\r\n" +
                   "Content-Length: " + str(len(contents)) + "\r\n\r\n" +
                   contents)
    elif data[0:25] == "GET /favicon.ico HTTP/1.1":
        print "favicon"
        contents = open("favicon.png", "rb").read()
        socko.send("HTTP/1.1 200 OK\r\n"
                   "Connection: close\r\n" + "Content-Type: image/png\r\n" +
                   "Content-Length: " + str(len(contents)) + "\r\n\r\n" +
                   contents)
    elif (data[0] == "\x00" and data[-1] == "\xff"):  #websocket format
        handler.handle(data[1:-1], socko, to_read, to_write, to_error, scope)
    else:
        print "you said"
        print data
        for i in data:
            print ord(i)
Пример #22
0
    def run(self):
        con = db.get_con()
        trans = con.transaction()
        while 1:
            Base.vlock.acquire()
            self.chunks = Base.chunks
            Base.chunks = []
            Base.vlock.release()
            print "Hanlding harvested data(%d)" % len(self.chunks)
            for chunk in self.chunks:
                try:
                    handler.handle(chunk, trans)
                except Exception:
                    print "ERROR IN %s" % chunk

            if self.chunks:
                trans.commit()
                print "COMMITED (%d)" % len(self.chunks)
            else:
                print "NOTHING"

            self.chunks = []
            time.sleep(HANDLER_DELAY)
Пример #23
0
	def run(self):
		con = db.get_con()		
		trans = con.transaction()
		while 1:
			Base.vlock.acquire()
			self.chunks = Base.chunks
			Base.chunks = []
			Base.vlock.release()
			print "Hanlding harvested data(%d)" % len(self.chunks)
			for chunk in self.chunks:
				try:
					handler.handle(chunk,trans)
				except Exception:
					print "ERROR IN %s" % chunk

			if self.chunks: 
				trans.commit()
				print "COMMITED (%d)" % len(self.chunks)
			else:
				print "NOTHING"

			self.chunks=[]
			time.sleep(HANDLER_DELAY)			
Пример #24
0
 def __call__(self, environ, start_response):
     with self.loghandler.threadbound():
         request = werkzeug.Request(environ)
         m = self.mapper.match(environ=environ)
         if m is not None:
             handler = m['handler'](app=self,
                                    request=request,
                                    settings=self.settings)
             try:
                 return handler.handle(**m)(environ, start_response)
             except werkzeug.exceptions.HTTPException, e:
                 return e(environ, start_response)
         # no view found => 404
         return werkzeug.exceptions.NotFound()(environ, start_response)
Пример #25
0
def check_buf(chunk,
              *,
              remote,
              persisted=[b'', b'',
                         os.path.getmtime(handler.__file__)]):
    buf = persisted[remote] + chunk

    # all packets are prefixed with their length
    while len(buf) >= 2 and len(buf) >= struct.unpack('<H', buf[:2])[0]:
        length = struct.unpack('<H', buf[:2])[0]
        packet, buf = buf[:length], buf[length:]

        try:
            mod = os.path.getmtime(handler.__file__)
            if mod != persisted[-1]:
                persisted[-1] = mod
                importlib.reload(handler)
                print('reloaded handler')

            handler.handle(remote, packet)
        except Exception:
            traceback.print_exc()

    persisted[remote] = buf
Пример #26
0
def handle():
	"""
	Handler for `/helpdesk` methods

	### Examples:

	`/helpdesk/method/{methodname}` will call a whitelisted method
	"""
	try:
		validate_request()
		return handler.handle()
	except Exception, e:
		import traceback
		print traceback.format_exc()
		return get_response(0, str(e))
Пример #27
0
def handle():
	"""
	Handler for `/helpdesk` methods

	### Examples:

	`/helpdesk/method/{methodname}` will call a whitelisted method
	"""
	try:
		validate_request()
		return handler.handle()
	except Exception, e:
		import traceback
		print traceback.format_exc()
		return get_response(message=str(e))
Пример #28
0
    def test_load(self):
        failures = 0
        for x in range(20):
            print('Request #: ', x)

            response = handle()
            print('Response Code: ', response.status_code)
            if response.status_code != 200:
                print('FAILED')
                failures += 1
            else:
                print('PASS')

            time.sleep(5.0)

        self.assertEqual(failures, 0)
Пример #29
0
    def simulate(self, t=[]):
        # makes a copy of pcp1.pcp
        # and modifies the original
        self.make_a_copy()
        self.modify_pcp1_pcp(t)

        # runs the SWAT model
        run_swat = swat.project(self.project)
        run_swat.run()
        run_swat.clear()

        # calculates the nash values
        h = handler.handle(self.output_rch, self.observed_rch)
        r = [float(i[1]) for i in h.nash]
        self.nashes.append((t, sum(r) / len(r)))
        print "Nashes until now:", self.nashes
Пример #30
0
def diTH():
    global current_data
    connected = False
    while not connected:
        try:
            client_id = '932430232049832423324'  # Fake ID, put your real one here
            RPC = Presence(client_id)  # Initialize the client class
            RPC.connect()  # Start the handshake loop
            connected = True
        except Exception as e:
            print(126)
            print(e)
            connected = False
        time.sleep(20)
    while True:  # The presence will stay on as long as the program is running
        try:
            print("---cdata---")
            print(current_data)
            print("---Ecdata---")
            d = handler.handle(current_data)
            print(d)
            RPC.update(state=d["state"],
                       details=d["details"],
                       large_image=d["large_image"],
                       small_image=d["small_image"],
                       large_text=d["large_text"],
                       small_text=d["small_text"],
                       start=d["start"],
                       end=d["end"])
            time.sleep(15)  # Can only update rich presence every 15 seconds
        except Exception as e:
            print(144)
            print(e)
            while not connected:
                try:
                    client_id = '778926641333796885'  # Fake ID, put your real one here
                    RPC = Presence(client_id)  # Initialize the client class
                    RPC.connect()  # Start the handshake loop
                    connected = True
                except Exception as e:
                    print(149)
                    print(e)
                    connected = False
                time.sleep(20)
Пример #31
0
def handle():
    """
	Handler for `/api_name` methods
	**api_name = configured in api_hander hooks
	### Examples:

	`/api_name/{methodname}` will call a whitelisted method

	"""
    try:
        validate_and_get_json_request()
        return handler.handle()
    except Exception, e:
        import traceback

        print traceback.format_exc()
        frappe.response["X_ERROR_CODE"] = "03" if "XML Request" in cstr(e) else "01"
        frappe.response["X_ERROR_DESC"] = cstr(e)
        return build_response("xml")
Пример #32
0
def handle():
    json = request.get_json()
    response = handler.handle(json['data'], json['nick'])
    return create_response(response)
Пример #33
0
def test_handler(data, client):
    result = handle(data, client)
    result == 2.0 * data["value"]
Пример #34
0
import sys
import handler
import json

def get_stdin():
    buf = ""
    for line in sys.stdin:
        buf = buf + line
    return buf

def read_head():
    buf = ""
    while(True):
        line = sys.stdin.readline()
        buf += line

        if line == "\r\n":
            break
    return buf

if(__name__ == "__main__"):
    st = get_stdin()
    print(json.dumps(handler.handle(st)))
Пример #35
0
def run(daemon=False):
    if daemon:
        try:
            if os.fork() > 0:
                # parent
                sys.exit(0)
        except OSError, e:
            sys.stderr.write("fork #1 failed: (%d) %sn" % (e.errno, e.strerror))
            sys.exit(1)

        # children process
        # setup a safe environment and start a new process in that
        os.chdir("/")
        os.umask(0)
        os.setsid()

        try:
            if os.fork() > 0:
                sys.exit(0)
        except OSError, e:
            sys.stderr.write("fork #2 failed: (%d) %sn" % (e.errno, e.strerror))
            sys.exit(1)

        # now we're daemonized
        for f in sys.stdout, sys.stderr: f.flush()

    handle()

if __name__ == '__main__':
    sys.exit(main())
Пример #36
0
#-*- coding:utf-8 -*-
import requests
import os
import shutil
from bs4 import BeautifulSoup
import handler

url = 'http://123.xidian.edu.cn/'
r = requests.get(url)
soup = BeautifulSoup(r.text)

handler = handler.handler(['www.xidian.edu.cn'])
handler.handle()
Пример #37
0
import loader, parser, handler

print()

print('DATABASE')
print(loader.database)
print()

print('INSERT')
print(handler.handle(parser.parse('α{t1}[τ[a1,a2](1,2)]'), loader.database))
print(handler.handle(parser.parse('α{t2}[t1]'), loader.database))
print(handler.handle(parser.parse('α{t1}[μ{t1}{τ[a1,a2](1,3)}]'), loader.database))
print()

print('DATABASE')
print(loader.database)
print()

print('PROJECT')
print(handler.handle(parser.parse('Π[a1](t1)'), loader.database))
print(handler.handle(parser.parse('Π[a1](Π[a1,a2](t1))'), loader.database))
print()

print('SELECT')
print(handler.handle(parser.parse('σ[a1=1](t1)'), loader.database))
print(handler.handle(parser.parse('σ[a2=3](t1)'), loader.database))
print(handler.handle(parser.parse('σ[a1=1|a2=3](t1)'), loader.database))
print(handler.handle(parser.parse('σ[a2=3&a2=3](t1)'), loader.database))
print()

print('NESTED')
Пример #38
0
	def run(self):
		handler.handle(self.data)
Пример #39
0
s.send("PASS {}\r\n".format(cfg.PASS).encode("utf-8"))
s.send("NICK {}\r\n".format(cfg.NICK).encode("utf-8"))
for chan in cfg.CHAN:
    s.send("JOIN {}\r\n".format(chan).encode("utf-8"))
handler.load()
last_chatted = time()
last_checked = time()
chat(s, "HeyGuys", "#toddle_bot")


while True:
    response = s.recv(4096).decode("utf-8").split("\n")
    if time() - last_checked > 60:
        last_checked = time()
        handler.handle("DISTRIBUTE")
    for line in response:
        with open('log.txt', 'a') as f:
            try: 
                f.write("IN = " + line + '\r\n')
            except UnicodeEncodeError:
                break
        neatline = converter.convert(line)
        done = handler.handle(neatline)
        if done == "PING":
            s.send("PONG :tmi.twitch.tv \r\n".encode())
        elif done == "Success" or done == "?":
            pass
        elif "MSG" in done[0]:
            chat(s, done[0][4:], done[1])
            last_chatted = time()
Пример #40
0
def test_handle():
    res = handle("Test")
    assert res == "Hello! You said: Test", "Should be equals"
Пример #41
0
requestSchema  = avro.schema.Parse(open('/root/chariot/avro-schema/basicRequest.avsc').read())
responseSchema = avro.schema.Parse(open('/root/chariot/avro-schema/basicResponse.avsc').read())

def buildResponseBody(response, request):
  responseBody = {
    'request_id'    : request['request_id'],
    'status'        : 'SUCCESS',
    'function_name' : request['function_name'],
    'response'      : response
  }
  return responseBody

if len(sys.argv) < 2:
  print('Request ID not present. Aborting')
else:
  requestID    = sys.argv[1]
  rawBytes     = open('/tmp/'+requestID+'.req', 'rb').read()
  bytesReader  = io.BytesIO(rawBytes)
  decoder      = avro.io.BinaryDecoder(bytesReader)
  reader       = avro.io.DatumReader(requestSchema)
  request      = reader.read(decoder)
  response     = handler.handle(request)
  writer       = avro.io.DatumWriter(responseSchema)
  bytesWriter  = io.BytesIO()
  encoder      = avro.io.BinaryEncoder(bytesWriter)
  responseBody = buildResponseBody(response, request)
  writer.write(responseBody, encoder)
  responseFile = open('/tmp/'+requestID+'.res', 'wb')
  responseFile.write(bytesWriter.getvalue())
  print('Response saved in /tmp/'+requestID+'.res')
Пример #42
0
# Copyright (c) Alex Ellis 2017. All rights reserved.
# Copyright (c) OpenFaaS Author(s) 2018. All rights reserved.
# Licensed under the MIT license. See LICENSE file in the project root for full license information.

import sys
import handler

def get_stdin():
    buf = ""
    while(True):
        line = sys.stdin.readline()
        buf += line
        if line == "":
            break
    return buf

if __name__ == "__main__":
    st = get_stdin()
    ret = handler.handle(st)
    if ret != None:
        print(ret)
Пример #43
0
def test_handler():
    event = create_s3_event(BUCKET, KEY)

    handler.handle(event, None)