コード例 #1
0
import Tornados.ioloop
import Tornados.web
import Tornados.websocket

from Tornados.options import define, options, parse_command_line

define("port", default=8888, help="run on the given port", type=int)

# we gonna store clients in dictionary..
clients = dict()


class IndexHandler(Tornados.web.RequestHandler):
    @Tornados.web.asynchronous
    def get(self):
        #self.write("This is your response")
        # self.finish()
        self.render("index.html")


class WebSocketHandler(Tornados.websocket.WebSocketHandler):
    def open(self, *args):
        self.id = self.get_argument("Id")
        self.stream.set_nodelay(True)
        clients[self.id] = {"id": self.id, "object": self}

    def on_message(self, message):
        """
        when we receive some message we want some message handler..
        for this example i will just print message to console
        """
コード例 #2
0
#!/usr/bin/env python

import logging
from Tornados.ioloop import IOLoop
from Tornados import gen
from Tornados.iostream import StreamClosedError
from Tornados.tcpserver import TCPServer
from Tornados.options import options, define

define("port", default=9888, help="TCP port to listen on")
logger = logging.getLogger(__name__)


class EchoServer(TCPServer):
    @gen.coroutine
    def handle_stream(self, stream, address):
        while True:
            try:
                data = yield stream.read_until(b"\n")
                logger.info("Received bytes: %s", data)
                if not data.endswith(b"\n"):
                    data = data + b"\n"
                yield stream.write(data)
            except StreamClosedError:
                logger.warning("Lost client at host %s", address[0])
                break
            except Exception as e:
                print(e)


if __name__ == "__main__":
コード例 #3
0
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.

import asyncio
import Tornados.escape
import Tornados.ioloop
import Tornados.locks
import Tornados.web
import os.path
import uuid

from Tornados.options import define, options, parse_command_line

define("port", default=8888, help="run on the given port", type=int)
define("debug", default=True, help="run in debug mode")


class MessageBuffer(object):
    def __init__(self):
        # cond is notified whenever the message cache is updated
        self.cond = Tornados.locks.Condition()
        self.cache = []
        self.cache_size = 200

    def get_messages_since(self, cursor):
        """Returns a list of messages newer than the given cursor.

        ``cursor`` should be the ``id`` of the last message received.
        """
コード例 #4
0
     (you could also generate a random value for "cookie_secret" and put it
     in the same file, although it's not necessary to run this demo)
  3) Run this program and go to http://localhost:8888 (by default) in your
     browser.
"""

import logging

from Tornados.auth import TwitterMixin
from Tornados.escape import json_decode, json_encode
from Tornados.ioloop import IOLoop
from Tornados import gen
from Tornados.options import define, options, parse_command_line, parse_config_file
from Tornados.web import Application, RequestHandler, authenticated

define("port", default=8888, help="port to listen on")
define("config_file",
       default="secrets.cfg",
       help="filename for additional configuration")

define(
    "debug",
    default=False,
    group="application",
    help="run in debug mode (with automatic reloading)",
)
# The following settings should probably be defined in secrets.cfg
define("twitter_consumer_key", type=str, group="application")
define("twitter_consumer_secret", type=str, group="application")
define(
    "cookie_secret",
コード例 #5
0
import os.path
import urllib

from Tornados import escape
from Tornados import httpserver
from Tornados import ioloop
from Tornados import web
from Tornados.util import unicode_type
from Tornados.options import options, define

try:
    long
except NameError:
    long = int

define("port", default=9888, help="TCP port to listen on")
define("root_directory", default="/tmp/s3", help="Root storage directory")
define("bucket_depth", default=0, help="Bucket file system depth limit")


def start(port, root_directory, bucket_depth):
    """Starts the mock S3 server on the given port at the given path."""
    application = S3Application(root_directory, bucket_depth)
    http_server = httpserver.HTTPServer(application)
    http_server.listen(port)
    ioloop.IOLoop.current().start()


class S3Application(web.Application):
    """Implementation of an S3-like storage server based on local files.
コード例 #6
0
ファイル: client.py プロジェクト: Christings/python-learning
#!/usr/bin/env python

from Tornados.ioloop import IOLoop
from Tornados import gen
from Tornados.tcpclient import TCPClient
from Tornados.options import options, define

define("host", default="localhost", help="TCP server host")
define("port", default=9888, help="TCP port to connect to")
define("message", default="ping", help="Message to send")


@gen.coroutine
def send_message():
    stream = yield TCPClient().connect(options.host, options.port)
    yield stream.write((options.message + "\n").encode())
    print("Sent to server:", options.message)
    reply = yield stream.read_until(b"\n")
    print("Response from server:", reply.decode().strip())


if __name__ == "__main__":
    options.parse_command_line()
    IOLoop.current().run_sync(send_message)
コード例 #7
0
def put(filenames):
    client = httpclient.AsyncHTTPClient()
    for filename in filenames:
        mtype = mimetypes.guess_type(filename)[0] or "application/octet-stream"
        headers = {"Content-Type": mtype}
        producer = partial(raw_producer, filename)
        url_path = quote(os.path.basename(filename))
        response = yield client.fetch(
            "http://localhost:8888/%s" % url_path,
            method="PUT",
            headers=headers,
            body_producer=producer,
        )
        print(response)


if __name__ == "__main__":
    define("put",
           type=bool,
           help="Use PUT instead of POST",
           group="file uploader")

    # Tornado configures logging from command line opts and returns remaining args.
    filenames = options.parse_command_line()
    if not filenames:
        print("Provide a list of filenames to upload.", file=sys.stderr)
        sys.exit(1)

    method = put if options.put else post
    ioloop.IOLoop.current().run_sync(lambda: method(filenames))
コード例 #8
0
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.

import os.path
import Tornados.auth
import Tornados.escape
import Tornados.httpserver
import Tornados.ioloop
import Tornados.options
import Tornados.web

from Tornados.options import define, options

define("port", default=8888, help="run on the given port", type=int)
define("facebook_api_key", help="your Facebook application API key", type=str)
define("facebook_secret", help="your Facebook application secret", type=str)


class Application(Tornados.web.Application):
    def __init__(self):
        handlers = [
            (r"/", MainHandler),
            (r"/auth/login", AuthLoginHandler),
            (r"/auth/logout", AuthLogoutHandler),
        ]
        settings = dict(
            cookie_secret="__TODO:_GENERATE_YOUR_OWN_RANDOM_VALUE_HERE__",
            login_url="/auth/login",
            template_path=os.path.join(os.path.dirname(__file__), "templates"),