예제 #1
0
def update_carbon(signum):
    # connect to the carbon server
    carbon_fd = uwsgi.connect(CARBON_SERVER)
    # send data to the carbon server
    uwsgi.send(carbon_fd, "uwsgi.%s.requests %d %d\n" % (uwsgi.hostname, uwsgi.total_requests(), int(time.time())))
    # close the connection with the carbon server
    uwsgi.close(carbon_fd)
예제 #2
0
def application(e, sr):
    sr('200 OK', [('Content-Type','text/plain')])

    # call suspend 10 times and yield some value
    for i in range(0,10):
        print i
        uwsgi.suspend()
        yield str(i)

    # connect to a memcached server
    fd = uwsgi.async_connect('127.0.0.1:11211')
    try:
        # start waiting for socket availability (4 seconds max)
        uwsgi.wait_fd_write(fd, 4)
        # suspend execution 'til event
        uwsgi.suspend()
        uwsgi.send(fd, "get /foobar\r\n")
        # now wait for memcached response
        uwsgi.wait_fd_read(fd, 4)
        uwsgi.suspend()
        # read the response
        data = uwsgi.recv(fd, 4096)
        # return to the client
        yield data
    finally:
        uwsgi.close(fd)

    print "sleeping for 3 seconds..."
    uwsgi.async_sleep(3)
    uwsgi.suspend()
    yield "done"
예제 #3
0
def application(e, sr):
    sr('200 OK', [('Content-Type', 'text/plain')])

    # call suspend 10 times and yield some value
    for i in range(0, 10):
        print(i)
        uwsgi.suspend()
        yield str(i)

    # connect to a memcached server
    fd = uwsgi.async_connect('127.0.0.1:11211')
    try:
        # start waiting for socket availability (4 seconds max)
        uwsgi.wait_fd_write(fd, 4)
        # suspend execution 'til event
        uwsgi.suspend()
        uwsgi.send(fd, "get /foobar\r\n")
        # now wait for memcached response
        uwsgi.wait_fd_read(fd, 4)
        uwsgi.suspend()
        # read the response
        data = uwsgi.recv(fd, 4096)
        # return to the client
        yield data
    finally:
        uwsgi.close(fd)

    print("sleeping for 3 seconds...")
    uwsgi.async_sleep(3)
    uwsgi.suspend()
    yield "done"
예제 #4
0
def serve_logo(e, sr):
    # use raw facilities (status will not be set...)
    uwsgi.send(
        b"%s 200 OK\r\nContent-Type: image/png\r\n\r\n"
        % e["SERVER_PROTOCOL"].encode("latin1")
    )
    uwsgi.sendfile(logo_png)
    return []
예제 #5
0
def send_request(env, client):

    uwsgi.send(client, b"GET /intl/it_it/images/logo.gif HTTP/1.0\r\n")

    # test for suspend/resume
    uwsgi.suspend()

    uwsgi.send(client, b"Host: www.google.it\r\n\r\n")

    while 1:
        yield uwsgi.wait_fd_read(client, 2)
        if env['x-wsgiorg.fdevent.timeout']:
            return

        buf = uwsgi.recv(client, 4096)
        if buf:
            yield buf
        else:
            break
예제 #6
0
파일: iobound_async.py 프로젝트: Algy/uwsgi
def send_request(env, client):

    uwsgi.send(client, b"GET /intl/it_it/images/logo.gif HTTP/1.0\r\n")

    # test for suspend/resume
    uwsgi.suspend()

    uwsgi.send(client, b"Host: www.google.it\r\n\r\n")

    while 1:
        yield uwsgi.wait_fd_read(client, 2)
        if env['x-wsgiorg.fdevent.timeout']:
            return

        buf = uwsgi.recv(client, 4096)
        if buf:
            yield buf
        else:
            break
예제 #7
0
def application(e, sr):
    sr('200 OK', [('Content-Type', 'text/plain')])

    # suspend 10 times and yield a value
    for i in range(1, 10):
        print i
        uwsgi.suspend()
        yield str(i)

    # connect to a memcached server
    fd = uwsgi.async_connect('127.0.0.1:11211')
    try:
        command = "get /foobar\r\n"
        remains = len(command)
        while remains > 0:
            # start waiting for socket availability (4 seconds max)
            uwsgi.wait_fd_write(fd, 4)
            # suspend execution 'til event
            uwsgi.suspend()
            pos = len(command) - remains
            written = uwsgi.send(fd, command[pos:])
            remains -= written

        # now wait for memcached response
        uwsgi.wait_fd_read(fd, 4)
        uwsgi.suspend()
        # read a chunk of data
        data = uwsgi.recv(fd, 4096)
        # .. and yield it
        yield data
    finally:
        # always ensure sockets are closed
        uwsgi.close(fd)

    print "sleeping for 3 seconds..."
    uwsgi.async_sleep(3)
    uwsgi.suspend()
    yield "done"
예제 #8
0
파일: welcome.py 프로젝트: wu-h/uwsgi
def serve_logo(e, sr):
    # use raw facilities (status will not be set...)
    uwsgi.send("%s 200 OK\r\nContent-Type: image/png\r\n\r\n" %
               e['SERVER_PROTOCOL'])
    uwsgi.sendfile('logo_uWSGI.png')
    return ''
예제 #9
0
def serve_logo(e, sr):
    # use raw facilities
    uwsgi.send("%s 200 OK\r\nContent-Type: image/png\r\n\r\n" % e['SERVER_PROTOCOL'])
    uwsgi.sendfile('logo_uWSGI.png')
    return ''
예제 #10
0
파일: ws.py 프로젝트: artizirk/dotchat
def application(env, sr):

    ws_scheme = 'ws'
    if 'HTTPS' in env or env['wsgi.url_scheme'] == 'https':
        ws_scheme = 'wss'

    if env['PATH_INFO'] == '/':
        sr('200 OK', [('Content-Type','text/html')])
        output = """
    <!doctype html>
    <html>
      <head>
          <meta charset="utf-8">
          <script language="Javascript">
            var s = new WebSocket("%s://%s/foobar/");
            s.onopen = function() {
              console.log("connected !!!");
              s.send("hello");
            };
            s.onmessage = function(e) {
        var bb = document.getElementById('blackboard')
        var html = bb.innerHTML;
        bb.innerHTML = html + '<br/>' + e.data;
            };

        s.onerror = function(e) {
            console.log(e);
        }

    s.onclose = function(e) {
        console.log("connection closed");
    }

            function invia() {
              var value = document.getElementById('testo').value;
              s.send(value);
            }
          </script>
     </head>
    <body>
        <h1>WebSocket</h1>
        <input type="text" id="testo"/>
        <input type="button" value="invia" onClick="invia();"/>
    <div id="blackboard" style="width:640px;height:480px;background-color:black;color:white;border: solid 2px red;overflow:auto">
    </div>
    </body>
    </html>
        """ % (ws_scheme, env['HTTP_HOST'])
        return output.encode()
    elif env['PATH_INFO'] == '/favicon.ico':
        return ""
    elif env['PATH_INFO'] == '/foobar/':
        uwsgi.websocket_handshake(env['HTTP_SEC_WEBSOCKET_KEY'], env.get('HTTP_ORIGIN', ''))
        print("websockets...")
        msg_srv_fd = uwsgi.async_connect("127.0.0.1:8888")
        websocket_fd = uwsgi.connection_fd()
        while True:
            uwsgi.wait_fd_read(websocket_fd, 3)
            uwsgi.wait_fd_read(msg_srv_fd)
            uwsgi.suspend()
            fd = uwsgi.ready_fd()
            if fd > -1:
                if fd == websocket_fd:
                    msg = uwsgi.websocket_recv_nb()
                    print("got message over ws: {}".format(msg))
                    if msg:
                        uwsgi.send(msg_srv_fd, msg)
                elif fd == msg_srv_fd:
                    msg = uwsgi.recv(msg_srv_fd)
                    print("got message over msg_srv: {}".format(msg))
                    uwsgi.websocket_send("[%s] %s" % (time.time(), msg.decode()))
            else:
                # on timeout call websocket_recv_nb again to manage ping/pong
                msg = uwsgi.websocket_recv_nb()
                print("ws ping/pong")
                if msg:
                    print("got message over ws: {}".format(msg))
                    uwsgi.send(msg_srv_fd, msg)
예제 #11
0
def uwsgi_pypy_wait_fd_write(fd, timeout=0):
    wsgi_req = uwsgi_pypy_current_wsgi_req();
    if lib.async_add_fd_write(wsgi_req, fd, timeout) < 0:
        raise Exception("unable to add fd %d to the event queue" % fd)
uwsgi.wait_fd_write = uwsgi_pypy_wait_fd_write

"""
uwsgi.ready_fd()
"""
def uwsgi_pypy_ready_fd():
    wsgi_req = uwsgi_pypy_current_wsgi_req();
    return lib.uwsgi_ready_fd(wsgi_req)
uwsgi.ready_fd = uwsgi_pypy_ready_fd
    

"""
uwsgi.send(fd=None,data)
"""
def uwsgi_pypy_send(*args):
    if len(args) == 0:
        raise ValueError("uwsgi.send() takes at least 1 argument")
    elif len(args) == 1:
        wsgi_req = uwsgi_pypy_current_wsgi_req();
        fd = wsgi_req.fd
        data = args[0]
    else:
        fd = args[0]
        data = args[1]
    rlen = libc.write(fd, data, len(data))
    if rlen <= 0:
        raise IOError("unable to send data")
예제 #12
0
	def send(self, body):
		if not self.closed:
			uwsgi.send(self.fileno(), body)
		return len(body)
예제 #13
0
파일: factory.py 프로젝트: 5432935/kbengine
 def send(self, body):
     if not self.closed:
         uwsgi.send(self.fileno(), body)
     return len(body)
예제 #14
0
 def raw_send(self, data):
     import uwsgi
     uwsgi.send(self.fd, str(data))
 def raw_send(self, data):
     import uwsgi
     uwsgi.send(self.fd, str(data))
예제 #16
0
파일: uwsgirouter.py 프로젝트: wu-h/uwsgi
def application(env, start_response):

    # open the socket
    fd = uwsgi.async_connect("192.168.173.100:3032")

    # wait for connection ready (3s timeout)
    yield uwsgi.wait_fd_write(fd, 3)

    # has timed out ?
    if env['x-wsgiorg.fdevent.timeout']:
        print "connection timed out !!!"
        uwsgi.close(fd)
        raise StopIteration

    # connection refused ?
    if not uwsgi.is_connected(fd):
        print "unable to connect"
        uwsgi.close(fd)
        raise StopIteration

    # send request
    # env can contains python objects, but send_message will discard them.
    # In this way we will automagically have a congruent and valid uwsgi packet
    uwsgi.async_send_message(fd, 0, 0, env)

    # send the http body
    # ready body in async mode and resend to fd
    # uwsgi.recv will use always an internal buffer of 4096, but can be limited in the number of bytes to read

    # does this request has a body ?
    cl = uwsgi.cl()

    if cl > 0:
        # get the input fd
        input = env['wsgi.input'].fileno()

        # read (in async mode) upto 'cl' data and send to uwsgi peer
        while cl > 0:
            bufsize = min(cl, 4096)
            yield uwsgi.wait_fd_read(input, 30)
            if env['x-wsgiorg.fdevent.timeout']:
                print "connection timed out !!!"
                uwsgi.close(fd)
                raise StopIteration
            body = uwsgi.recv(input, bufsize)
            if body:
                uwsgi.send(fd, body)
                cl = cl - len(body)
            else:
                break

    # wait for response (30s timeout)
    yield uwsgi.wait_fd_read(fd, 30)

    # has timed out ?
    if env['x-wsgiorg.fdevent.timeout']:
        print "connection timed out !!!"
        uwsgi.close(fd)
        raise StopIteration

    data = uwsgi.recv(fd)
    # recv the data, if it returns None the callable will end
    while data:
        yield data
        # wait for response
        yield uwsgi.wait_fd_read(fd, 30)
        if env['x-wsgiorg.fdevent.timeout']:
            print "connection timed out !!!"
            uwsgi.close(fd)
            raise StopIteration
        data = uwsgi.recv(fd)

    uwsgi.close(fd)
예제 #17
0
def uwsgi_pypy_wait_fd_write(fd, timeout=0):
    wsgi_req = uwsgi_pypy_current_wsgi_req();
    if lib.async_add_fd_write(wsgi_req, fd, timeout) < 0:
        raise Exception("unable to add fd %d to the event queue" % fd)
uwsgi.wait_fd_write = uwsgi_pypy_wait_fd_write

"""
uwsgi.ready_fd()
"""
def uwsgi_pypy_ready_fd():
    wsgi_req = uwsgi_pypy_current_wsgi_req();
    return lib.uwsgi_ready_fd(wsgi_req)
uwsgi.ready_fd = uwsgi_pypy_ready_fd
    

"""
uwsgi.send(fd=None,data)
"""
def uwsgi_pypy_send(*args):
    if len(args) == 0:
        raise ValueError("uwsgi.send() takes at least 1 argument")
    elif len(args) == 1:
        wsgi_req = uwsgi_pypy_current_wsgi_req();
        fd = wsgi_req.fd
        data = args[0]
    else:
        fd = args[0]
        data = args[1]
    rlen = libc.write(fd, data, len(data))
    if rlen <= 0:
        raise IOError("unable to send data")