Ejemplo n.º 1
0
def main():
    """Construct and serve the tornado application."""
    api_root = '/api/v1'
    app = Application(
        handlers=[
            (r'/', HomeView),
            (r'/favicon.ico', HomeView),
            (r'/error_500', ErrorView),
            (api_root, InfoView),
            (api_root + r'/login', LoginView),
            (api_root + r'/accounts', RegistrationView),
            (api_root + r'/accounts/([\w]+)', ProfileView),
            (api_root + r'/accounts/([\w]+)/tasks', TaskListView),
            (api_root + r'/accounts/([\w]+)/tasks/([\d]+)', TaskView),
            (api_root + r'/accounts/([\w]+)/logout', LogoutView),
        ],
        db=SQLAlchemy(
            os.environ.get(
                'DATABASE_URL',
                'postgres://*****:*****@localhost:5432/task_manager')),
        cookie_secret="__TODO:_GENERATE_YOUR_OWN_RANDOM_VALUE_HERE__",
        **options.group_dict('application'),
        login_url="/api/v1/login",
        xsrf_cookies=True,
        debug=True,
        static_path=os.path.join(os.path.dirname(__file__), "static"),
        template_path=os.path.join(os.path.dirname(__file__), "templates"))
    http_server = HTTPServer(app)
    http_server.listen(options.port)
    print('Listening on http://localhost:%d' % options.port)
    logging.info('Listening on http://localhost:%d' % options.port)
    IOLoop.current().start()
def create_app():
    """

    :return:
    """
    app = Application(
        [
            *(main_blueprint.publish('/')), *(auth_blueprint.publish('/')),
            *(terminal_blueprint.publish('/')),
            *(queue_blueprint.publish('/queue')),
            *(device_blueprint.publish('/device'))
        ],
        login_url="/login",
        cookie_secret=os.environ.get(
            'TORNADO_SECRET_KEY',
            open(
                os.path.join(os.path.dirname(os.path.realpath(__file__)),
                             "../cookie.key"), 'r').read()),
        template_path="HardwareCheckout/templates/",
        static_path="HardwareCheckout/static/",
        db=SQLAlchemy(url=db_path),
        # xsrf_cookies=True,  #TODO
        websocket_ping_interval=10000,
        websocket_ping_timeout=30000,
    )

    return app  # skip all below for testing without removing it
def route():
    routes = [
        (r"/people", PeopleGetHandler),
        (r"/people/add", PeoplePostHandler),
        (r"/people/update/(?P<id>\w+)", PeopleUpdHandler),
        (r"/people/delete/(?P<id>\w+)", PeopleDelHandler)
    ]

    return Application(routes, db=SQLAlchemy(db_url), debug=True)
Ejemplo n.º 4
0
def db_object(options=None, url: str = None, binds: Optional[dict] = {}):
    """Return tornado_sqlalchemy session interface object.
    Used for SA Model class and ThreadPoolExecutor interfaces.
    """
    if url:
        url = url.strip()
    elif options:
        url = make_url(options)
    else:
        raise OptionsNotProvided(
            'Provide either options object or a valid DB URL')

    return SQLAlchemy(url=url, binds=binds)
Ejemplo n.º 5
0
 def __init__(self):
     handlers = [
         (r"/", ShowUrl),
         (r"/urls", UrlsApp),
         (r"/registration", RegistrationApp),
         (r"/login", AuthorizationApp)
     ]
     settings = {
         "cookie_secret": COOKIE_SECRET,
         "db": SQLAlchemy(DATABASE_URL),
         "login_url": '/login'
     }
     Application.__init__(self, handlers, **settings)
Ejemplo n.º 6
0
class BaseDBTestCase(AsyncHTTPTestCase):
    def setUp(self):
        super(BaseDBTestCase, self).setUp()
        alembic_config = AlembicConfig('alembic.ini')
        alembic_config.set_main_option('sqlalchemy.url',
                                       'sqlite:///testdb.sqlite')
        alembic_upgrade(alembic_config, 'head')

    def tearDown(self):
        os.remove('testdb.sqlite')

    def get_app(self):
        self.engine = SQLAlchemy('sqlite:///testdb.sqlite')
        self.session = self.engine.sessionmaker()
        return Application(routes, db=self.engine, debug=True)
Ejemplo n.º 7
0
def make_app():
    logging.info("Server start http://%s:%i", config.app_host, config.app_port)
    logging.info("DOC start http://%s:%i/swagger/spec.html", config.app_host,
                 config.app_port)
    settings = dict(
        cookie_secret=config.app_key,
        debug=True,
        description=config.app_title,
    )
    # 라우트 설정
    routes = swirl.api_routes() + [
        (r"/(.*)", RedirectHandler, {
            'url': '/api'
        }),
    ]
    return swirl.Application(
        routes,
        db=SQLAlchemy(
            f"{config.db_type}://{config.db_user}:{config.db_pass}@{config.db_host}/{config.db_name}"
        ),
        **settings)
Ejemplo n.º 8
0
from os import environ

from tornado.options import define
from tornado_sqlalchemy import SQLAlchemy

define("port",
       default=environ.get("DEFAULT_PORT", 9090),
       help="port to listen on")

SETTINGS = {
    "debug": environ.get("DEBUG", True),
}

DB = {
    "username": environ.get("DB_USER", "booksales"),
    "password": environ.get("DB_PWD", "booksales"),
    "host": environ.get("DB_HOST", "db"),
    "port": environ.get("DB_PORT", 5432),
    "name": environ.get("DB_NAME", "booksales"),
}
DB_URL = "postgresql://{user}:{pwd}@{host}:5432/{db_name}".format(
    user=DB["username"],
    pwd=DB["password"],
    host=DB["host"],
    db_name=DB["name"])

DATABASE = SQLAlchemy(url=DB_URL)
Ejemplo n.º 9
0
from sqlalchemy import Column, String, BigInteger, ForeignKey, DateTime, func
from tornado_sqlalchemy import SQLAlchemy

from settings import DATABASE_URL

db = SQLAlchemy(url=DATABASE_URL)


class User(db.Model):
    __tablename__ = 'user'
    id = Column(BigInteger, primary_key=True, autoincrement=True)
    username = Column(String(50), unique=True)
    password = Column(String(255))

    def __init__(self, username, password):
        self.username = username
        self.password = password


class Url(db.Model):
    __tablename__ = 'url'
    id = Column(BigInteger, primary_key=True, autoincrement=True)
    datetime = Column(DateTime(timezone=True), server_default=func.now())
    full_address = Column(String(255))
    abbreviated_address = Column(String(255), unique=True)
    access_level = Column(String(10), default='general')
    rating = Column(BigInteger, default=0)
    user_id = Column('user_id', BigInteger, ForeignKey('user.id'))

    def __init__(self, full_address, abbreviated_address, access_level,
                 user_id):
Ejemplo n.º 10
0
def route():
    route = [(r"/siswa", SiswaGetHandler),
             (r"/siswa/action/add", SiswaPostHandler),
             (r"/siswa/(?P<id>\w+)/action/update", SiswaUpdtHandler),
             (r"/siswa/(?P<id>\w+)/action/delete", SiswaDelHandler)]
    return Application(route, db=SQLAlchemy(db_url), debug=True)
Ejemplo n.º 11
0
def make_app():
    urls = [(r"/api/item/([^/]+)?", TodoItem), (r"/api/items", TodoItems)]
    db_url = 'postgresql://*****:*****@localhost:5400/postgres'
    return Application(urls, db=SQLAlchemy(db_url), debug=True)
Ejemplo n.º 12
0
from tornado_sqlalchemy import SQLAlchemy, SessionMixin
from sqlalchemy import Column, BigInteger, String, Integer # for use in defining our models
import os

# FOR MASTER BRANCH
db_url = os.environ['DATABASE_URL']

# FOR DEVELOPMENT / testing
# db_url = 'postgres://harry:@localhost/games'
# db_url = 'postgres://postgres:@localhost/games'

db = SQLAlchemy(url=db_url)

class Snake_Highscore(db.Model):
    __tablename__ = "snake_highscores"
    id = Column(Integer, primary_key = True, autoincrement = True)
    username = Column(String(100), nullable = False)
    highscore = Column(Integer)


class Firefly_Highscore(db.Model):
    __tablename__ = "firefly_highscores"
    id = Column(Integer, primary_key = True, autoincrement = True)
    username = Column(String(100), nullable = False)
    highscore = Column(Integer)


class User_Auth(db.Model):
    __tablename__ = "user_auth"
    id = Column(Integer, primary_key = True, autoincrement = True)
    username = Column(String(100), unique = True, nullable = False)
Ejemplo n.º 13
0
from functools import partial

from .config import db_path, ctfd_db_path

from sqlalchemy import Column, Integer, String, ForeignKey, DateTime
from sqlalchemy import or_
from sqlalchemy.orm import relationship
from tornado_sqlalchemy import SQLAlchemy, as_future

db = SQLAlchemy(
    url=db_path,
    engine_options={
        "max_overflow": 15,
        "pool_pre_ping": True,
        "pool_recycle": 60 * 60,
        "pool_size": 30,
    },
)

if ctfd_db_path:
    ctfd_db = SQLAlchemy(
        url=ctfd_db_path,
        engine_options={
            "max_overflow": 15,
            "pool_pre_ping": True,
            "pool_recycle": 60 * 60,
            "pool_size": 30,
        },
    )
else:
    ctfd_db = False
Ejemplo n.º 14
0
from sqlalchemy import BigInteger, Column, String
from tornado.gen import coroutine
from tornado.ioloop import IOLoop
from tornado.web import Application, RequestHandler

from tornado_sqlalchemy import (
    SessionMixin,
    as_future,
    set_max_workers,
    SQLAlchemy,
)

db = SQLAlchemy()

set_max_workers(10)


class User(db.Model):
    __tablename__ = 'users'

    id = Column(BigInteger, primary_key=True)
    username = Column(String(255))


class Foo(db.Model):
    __bind_key__ = 'foo'
    __tablename__ = 'foo'

    id = Column(BigInteger, primary_key=True)
    foo = Column(String(255))
Ejemplo n.º 15
0
from sqlalchemy import BigInteger, Column, String

from tornado_sqlalchemy import SQLAlchemy


postgres_url = 'postgresql://*****:*****@127.0.0.1:5432/t_sa'

mysql_url = 'mysql+mysqldb://t_sa:[email protected]:3306/t_sa'
mysql_url_1 = 'mysql+mysqldb://t_sa:[email protected]:3306/t_sa_1'
mysql_url_2 = 'mysql+mysqldb://t_sa:[email protected]:3306/t_sa_2'

sqlite_url = 'sqlite:///t_sa.sqlite3'


db = SQLAlchemy()


class User(db.Model):
    __tablename__ = 'users'

    id = Column(BigInteger, primary_key=True)
    username = Column(String(64), unique=True)

    def __init__(self, username):
        self.username = username


class BaseTestCase(TestCase):
    def setUp(self):
        self.db_url = mysql_url
Ejemplo n.º 16
0
 def get_app(self):
     self.engine = SQLAlchemy('sqlite:///testdb.sqlite')
     self.session = self.engine.sessionmaker()
     return Application(routes, db=self.engine, debug=True)
Ejemplo n.º 17
0
from sqlalchemy import BigInteger, Column, String
from tornado.gen import coroutine
from tornado.ioloop import IOLoop
from tornado.options import define, options, parse_command_line
from tornado.web import Application, RequestHandler

from tornado_sqlalchemy import SessionMixin, as_future, SQLAlchemy

db = SQLAlchemy()

define('database-url', type=str, help='Database URL')


class User(db.Model):
    __tablename__ = 'users'

    id = Column(BigInteger, primary_key=True)
    username = Column(String(255), unique=True)


class SynchronousRequestHandler(SessionMixin, RequestHandler):
    def get(self):
        with self.make_session() as session:
            count = session.query(User).count()

        # OR count = self.session.query(User).count()

        self.write('{} users so far!'.format(count))


class GenCoroutinesRequestHandler(SessionMixin, RequestHandler):
Ejemplo n.º 18
0
 def set_url(self, url):
     self.url = url
     self._db = SQLAlchemy(self.url)
Ejemplo n.º 19
0
    def instance(self):
        if not self._db:
            self._db = SQLAlchemy(self.url)

        return self._db
Ejemplo n.º 20
0
from sqlalchemy import BigInteger, Column, String
from tornado.gen import coroutine
from tornado.ioloop import IOLoop
from tornado.web import Application, RequestHandler

from tornado_sqlalchemy import SessionMixin, as_future, SQLAlchemy

db = SQLAlchemy()


class User(db.Model):
    __tablename__ = 'users'

    id = Column(BigInteger, primary_key=True)
    username = Column(String(255), unique=True)


class SynchronousRequestHandler(SessionMixin, RequestHandler):
    def get(self):
        with self.make_session() as session:
            count = session.query(User).count()

        # OR count = self.session.query(User).count()

        self.write('{} users so far!'.format(count))


class GenCoroutinesRequestHandler(SessionMixin, RequestHandler):
    @coroutine
    def get(self):
        with self.make_session() as session:
from sqlalchemy import BigInteger, Column, String
from tornado.gen import coroutine
from tornado.ioloop import IOLoop
from tornado.web import Application, RequestHandler

from tornado_sqlalchemy import (
    SessionMixin,
    as_future,
    set_max_workers,
    SQLAlchemy,
)

db = SQLAlchemy()

set_max_workers(10)


class User(db.Model):
    __tablename__ = 'users'

    id = Column(BigInteger, primary_key=True)
    username = Column(String(255))


class Foo(db.Model):
    __bind_key__ = 'foo'
    __tablename__ = 'foo'

    id = Column(BigInteger, primary_key=True)
    foo = Column(String(255))
Ejemplo n.º 22
0
    from types import UnicodeType
except ImportError:
    UnicodeType = str
try:
    from json.decoder import JSONDecodeError
except ImportError:
    JSONDecodeError = ValueError
from tornado.concurrent import run_on_executor
from tornado_sqlalchemy import SQLAlchemy
from tornado_sqlalchemy import SessionMixin
from model import SSHConnection, UploadProgress
from tornadostreamform.multipart_streamer import MultiPartStreamer

TMP_DIR = os.path.join(os.path.dirname(os.path.abspath(__file__)), "tmp_dir")

db = SQLAlchemy("sqlite:///webssh.sqlite")

MB = 1024 * 1024
GB = 1024 * MB
MAX_STREAM_SIZE = 5 * GB


class BaseHandler(tornado.web.RequestHandler):
    def get_current_user(self):
        return self.get_secure_cookie("username")


class RegisterConnectionHandler(SessionMixin, BaseHandler):
    def get(self):
        self.render("connection_register.html", edit=False)
Ejemplo n.º 23
0
def db_settings(database_url: str = options.mysql_host) -> SQLAlchemy:
    return SQLAlchemy(url=database_url)
from sqlalchemy import Column, Integer, String, ForeignKey, DateTime
from sqlalchemy import func, or_
from sqlalchemy.orm import relationship
# from . import db
from .config import db_path
from tornado_sqlalchemy import SQLAlchemy, as_future
from functools import partial

db = SQLAlchemy(url=db_path)


class User(db.Model):
    """
    Suuuuper basic User model, this will almost certainly need to be updated.
    """
    __tablename__ = "user"
    id = Column(Integer, primary_key=True)
    password = Column(String(93), unique=True)
    name = Column(String(1000))

    #relationships
    roles = relationship('Role', secondary='user_roles')
    userQueueEntry = relationship("UserQueue")
    deviceQueueEntry = relationship("DeviceQueue",
                                    foreign_keys="DeviceQueue.owner")

    def get_owned_devices(self, session):
        return session.query(DeviceType.name, DeviceQueue.sshAddr,
                             DeviceQueue.webUrl).filter(
                                 or_(DeviceQueue.state == 'in-queue',
                                     DeviceQueue.state == 'in-use'),
Ejemplo n.º 25
0
from sqlalchemy import ARRAY, Column, DateTime, Integer
from tornado_sqlalchemy import SQLAlchemy

db = SQLAlchemy(url='localhost')


class TableItem(db.Model):
    __tablename__ = 'table'

    id = Column(Integer, primary_key=True)
    raw_array = Column(ARRAY(Integer))
    sorted_array = Column(ARRAY(Integer))
    created_at = Column(DateTime)

    class Meta:
        database = db