Esempio n. 1
0
    def load_application(self, application=None):

        if self.settings.TRANSLATIONS:
            try:
                from tornado import locale

                locale.load_translations(self.settings.TRANSLATIONS_CONF.translations_dir)
            except:
                warnings.warn('locale dir load failure,maybe your config file is not set correctly.')

        if not application:
            if not self.urls:
                raise BaseError("urls not found.")
            from torngas.application import Application

            self.application = Application(handlers=self.urls,
                                           default_host='',
                                           transforms=None, wsgi=False,
                                           **self.settings.TORNADO_CONF)
        else:
            self.application = application

        tmpl = self.settings.TEMPLATE_CONFIG.template_engine
        self.application.tmpl = import_object(tmpl) if tmpl else None

        return self
Esempio n. 2
0
    def _start_httpd(self):
        """Start the Tornado web application, creating the HTTPD server and
        passing in configuration as settings to the web Application

        """
        settings, config = self._application_settings()

        # Create the web application
        self._application = web.Application(self._get_routes(), **settings)

        # Start the HTTP Server
        self._application.listen(**self._httpd_config)

        # If translations are provided, load them
        if 'locale_path' in settings:
            locale.load_translations(settings['locale_path'])

        # Assign the config to an apiary attribute of the application
        self._application.apiary_config = config

        # Create the database session
        self._application.database = self._new_db_session()

        LOGGER.info('Apiary %s HTTP service started on port %s',
                    apiary.__version__, self._httpd_config['port'])
Esempio n. 3
0
def start_server():
    """ Main entry point for the application """
    locale.set_default_locale("en_US")
    locale.load_translations("locale")
    if options.autostart_game:
        app.settings["game_started"] = True
        app.settings["history_callback"].start()
        if options.use_bots:
            app.settings["score_bots_callback"].start()
    # Setup server object
    if options.ssl:
        server = HTTPServer(
            app,
            ssl_options={"certfile": options.certfile, "keyfile": options.keyfile},
            xheaders=options.x_headers,
        )
    else:
        server = HTTPServer(app, xheaders=options.x_headers)
    try:
        sockets = netutil.bind_sockets(options.listen_port, options.listen_interface)
    except (OSError, IOError) as err:
        logging.error("Problem binding socket to port %s", str(options.listen_port))
        if err.errno == 13:
            pypath = sys.executable
            if os_path.islink(pypath):
                pypath = os_path.realpath(pypath)
            logging.error(
                "Possible Fix: sudo setcap CAP_NET_BIND_SERVICE=+eip %s", pypath
            )
        elif err.errno == 98:
            logging.error(
                "The port may be in use by an existing service.  RTB already running?"
            )
        else:
            logging.error(err)
        sys.exit()
    server.add_sockets(sockets)
    if options.debug:
        logging.warn(
            "%sDebug mode is enabled; DO NOT USE THIS IN PRODUCTION%s" % (bold + R, W)
        )
    if options.autostart_game:
        logging.info("The game is about to begin, good hunting!")
    try:
        Scoreboard.update_gamestate(app)
    except OperationalError as err:
        if "Table definition has changed" in str(err):
            logging.info("Table definitions have changed -restarting RootTheBox.")
            return "restart"
        else:
            logging.error("There was a problem starting RootTheBox. Error: " + str(err))
    try:
        io_loop.start()
    except KeyboardInterrupt:
        sys.stdout.write("\r" + WARN + "Shutdown Everything!\n")
    except:
        logging.exception("Main i/o loop threw exception")
    finally:
        io_loop.stop()
        _exit(0)
Esempio n. 4
0
    def load_application(self, application=None):
        #加载app,进行初始化配置,如无ap参数,则使用内置app初始化
        #加载本地化配置
        if self.settings.TRANSLATIONS:
            try:
                from tornado import locale

                locale.load_translations(self.settings.TRANSLATIONS_CONF.translations_dir)
            except:
                warnings.warn('locale dir load failure,maybe your config file is not set correctly.')

        if not application:
            if not self.urls:
                raise TorngasError("urls not found.")

            self.application = application_module.Application(handlers=self.urls,
                                                              default_host='',
                                                              transforms=None, wsgi=False,
                                                              **self.settings.TORNADO_CONF)
        else:
            if isinstance(application, tornado.web.Application):
                self.application = application
            else:
                self.application = application(handlers=self.urls,
                                               default_host='',
                                               transforms=None, wsgi=False,
                                               **self.settings.TORNADO_CONF)

        self.application.project_path = self.proj_path \
            if self.proj_path.endswith('/') else self.proj_path + '/'

        tmpl = self.settings.TEMPLATE_CONFIG.template_engine
        self.application.tmpl = import_object(tmpl) if tmpl else None

        return self
Esempio n. 5
0
    def _start_httpd(self):
        """Start the Tornado web application, creating the HTTPD server and
        passing in configuration as settings to the web Application

        """
        settings, config = self._application_settings()

        # Create the web application
        self._application = web.Application(self._get_routes(), **settings)

        # Start the HTTP Server
        self._application.listen(**self._httpd_config)

        # If translations are provided, load them
        if 'locale_path' in settings:
            locale.load_translations(settings['locale_path'])

        # Assign the config to an apiary attribute of the application
        self._application.apiary_config = config

        # Create the database session
        self._application.database = self._new_db_session()

        LOGGER.info('Apiary %s HTTP service started on port %s',
                    apiary.__version__, self._httpd_config['port'])
Esempio n. 6
0
    def load_application(self, application=None):
        """

        :type application: torngas.application.Application subclass or instance
        :return:
        """
        self._patch_httpserver()
        if settings.TRANSLATIONS:
            try:
                from tornado import locale

                locale.load_translations(settings.TRANSLATIONS_CONF.translations_dir)
            except:
                warnings.warn('locale dir load failure,maybe your config file is not set correctly.')

        if not application:
            self._install_application(application)
        elif isinstance(application, Application):
            self.application = application
        elif issubclass(application, Application):
            self._install_application(application)
        else:
            raise ArgumentError('need torngas.application.Application instance object or subclass.')

        tmpl = settings.TEMPLATE_CONFIG.template_engine
        self.application.tmpl = import_object(tmpl) if tmpl else None

        return self.application
Esempio n. 7
0
    def load_application(self, application=None):

        if settings.TRANSLATIONS:
            try:
                from tornado import locale

                locale.load_translations(
                    settings.TRANSLATIONS_CONF.translations_dir)
            except:
                warnings.warn(
                    'locale dir load failure,maybe your config file is not set correctly.'
                )

        if not application:
            if not self.urls:
                raise BaseError("urls not found.")
            from torngas.application import Application

            tornado_conf = settings.TORNADO_CONF
            tornado_conf['debug'] = settings.DEBUG
            self.application = Application(
                handlers=self.urls,
                default_host='',
                transforms=None,
                wsgi=False,
                middlewares=settings.MIDDLEWARE_CLASSES,
                **tornado_conf)
        else:
            self.application = application

        tmpl = settings.TEMPLATE_CONFIG.template_engine
        self.application.tmpl = import_object(tmpl) if tmpl else None

        return self.application
Esempio n. 8
0
    def _load_translations(self, path):
        """Load the translations from the specified path.

        :param str path: The path to the translations

        """
        logger.info('Loading translations from %s', path)
        from tornado import locale
        locale.load_translations(path)
Esempio n. 9
0
    def _load_translations(self, path):
        """Load the translations from the specified path.

        :param str path: The path to the translations

        """
        logger.info('Loading translations from %s', path)
        from tornado import locale
        locale.load_translations(path)
Esempio n. 10
0
 def __init__(self, application, request, **kwargs):
     if BaseHandler._first_running:
         self._after_prefork()
         BaseHandler._first_running = False
     #国际化
     locale.load_translations("./protected/translations")
     locale.set_default_locale("zh_CN")
     self._locale = locale.get()
     super(BaseHandler, self).__init__(application, request, **kwargs)
     self.session = session.Session(self.application.session_manager, self)
Esempio n. 11
0
    def _prepare_translations(self):
        """Load in translations if they are set, and add the default locale as
        well.

        """
        if config.TRANSLATIONS in self.paths:
            LOGGER.info('Loading translations from %s',
                        self.paths[config.TRANSLATIONS])
            from tornado import locale
            locale.load_translations(self.paths[config.TRANSLATIONS])
            if config.DEFAULT_LOCALE in self._config:
                LOGGER.info('Setting default locale to %s',
                            self._config[config.DEFAULT_LOCALE])
                locale.set_default_locale(self._config[config.DEFAULT_LOCALE])
Esempio n. 12
0
def do_start():
    #  准备工作,系统准备工作放到这个方法里
    do_prepare()

    # 解析参数
    options.parse_command_line()
    locale.load_translations(
        os.path.join(os.path.dirname(__file__), "translations"))
    # 服务器配置
    app_opt = dict(session_secret=settings.SESSION_SECRET_KEY,
                   session_timeout=settings.SESSION_TIMEOUT,
                   cookie_secret=settings.COOKIE_SECRET_KEY,
                   xsrf_cookies=settings.XSRF_COOKIES,
                   xsrf_cookie_version=settings.XSRF_COOKIE_VERSION,
                   autoescape=settings.AUTO_ESCAPE,
                   compress_response=settings.COMPRESS_RESPONSE,
                   template_path=settings.TEMPLATE_PATH,
                   static_hash_cache=settings.STATIC_HASH_CACHE,
                   static_path=settings.STATIC_PATH,
                   static_url_prefix=settings.STATIC_URL_PREFIX,
                   autoreload=settings.AUTO_RELOAD)

    # 创建 & 启动服务
    application = IBApplication(handlers=[], **app_opt)
    http_server, task_id = None, ''
    if settings.OS.upper() == 'WINDOWS':
        logger = do_bind_logger_config()
        application.listen(options.options.port)
    else:
        # 绑定监听端口
        sockets = bind_sockets(options.options.port)
        # Fork服务,参数为服务数量,必须整型且不能为负数,0:依据CPU核心数量启动服务数量
        task_id = fork_processes(settings.NUM_PROCESSES)
        # 绑定日志配置
        logger = do_bind_logger_config(task_id)

        http_server = HTTPServer(application, xheaders=True)
        # 添加监听
        http_server.add_sockets(sockets)
    # 注册请求处理句柄
    application.register_handlers()

    logger.info('Started web server(%s) on %s://%s:%s' %
                (task_id, settings.SERVER_PROTOCOL, settings.SERVER_HOST,
                 options.options.port))

    IOLoop.current().start()
    if http_server:
        http_server.stop()
    IOLoop.current().stop()
Esempio n. 13
0
    def _prepare_translations(self):
        """Load in translations if they are set, and add the default locale as
        well.

        """
        if config.TRANSLATIONS in self.paths:
            LOGGER.info('Loading translations from %s',
                        self.paths[config.TRANSLATIONS])
            from tornado import locale
            locale.load_translations(self.paths[config.TRANSLATIONS])
            if config.DEFAULT_LOCALE in self._config:
                LOGGER.info('Setting default locale to %s',
                            self._config[config.DEFAULT_LOCALE])
                locale.set_default_locale(self._config[config.DEFAULT_LOCALE])
Esempio n. 14
0
 def __init__(self):
     self.support_locales = [
         "en_US",
         "zh_CN",
         "zh_TW",
     ]
     load_translations(get_current_path("i18n"))
     settings = {}
     settings["debug"] = True
     settings["static_path"] = get_current_path("static")
     settings["template_path"] = get_current_path("html")
     settings[
         "cookie_secret"] = "24oETzKXQAGaYdkL5gEmGeJJFuYh7EQnp2XdTP1o/Vo="
     handlers = [(r"/", MainHandler), (r"/([\w]+\.html$)", HtmlHandler),
                 (r"/([a-z]+_[A-Za-z]+)/([\w]+\.html$)", HtmlLangHandler)]
     Application.__init__(self, handlers, **settings)
Esempio n. 15
0
    def run(self):
        self.application.logger = LoggerConnector.get_logger('app')

        self.application.logger.info("FM Component Web Application Bootstrap run() - started")
        self.application.options = self.options
        self.application.logger.info("Tornado server File Manager app started with options %s",
                                     self.application.options.as_dict())

        # resources
        self.application.redis = RedisPool()
        self.application.logger.info("FM Component Redis - started")

        # RPC
        rpc.servers["default"]["host"] = self.options.rpc_host
        rpc.servers["default"]["port"] = self.options.rpc_port

        # Localization
        locale.load_translations(TRANSLATIONS_PATH)
Esempio n. 16
0
 def __init__(self):
     self.support_locales = [
         "en_US",
         "zh_CN",
         "zh_TW",
     ]
     load_translations(get_current_path("i18n"))
     settings = {}
     settings["debug"] = True
     settings["static_path"] = get_current_path("static")
     settings["template_path"] = get_current_path("html")
     settings["cookie_secret"] = "24oETzKXQAGaYdkL5gEmGeJJFuYh7EQnp2XdTP1o/Vo="
     handlers = [
         (r"/", MainHandler),
         (r"/([\w]+\.html$)", HtmlHandler),
         (r"/([a-z]+_[A-Za-z]+)/([\w]+\.html$)", HtmlLangHandler)
     ]
     Application.__init__(self, handlers, **settings)
Esempio n. 17
0
    def run(self):
        self.application.logger = LoggerConnector.get_logger('app')

        self.application.logger.info("FM Component Web Application Bootstrap run() - started")
        self.application.options = self.options
        self.application.logger.info("Tornado server File Manager app started with options %s",
                                     self.application.options.as_dict())

        # resources
        self.application.redis = RedisPool()
        self.application.logger.info("FM Component Redis - started")

        # RPC
        rpc.servers["default"]["host"] = self.options.rpc_host
        rpc.servers["default"]["port"] = self.options.rpc_port

        # Localization
        locale.load_translations(TRANSLATIONS_PATH)
Esempio n. 18
0
    def __init__(self, routes=None, **settings):

        # Define our logger
        self._logger = logging.getLogger(__name__)

        # Assign the settings
        self._settings = settings

        # If we have a base path, add it to our sys path
        if settings.get('base_path'):
            sys.path.insert(0, settings['base_path'])

        # Create a TinmanAttributes for assignments to application scope
        self.tinman = TinmanAttributes()

        # A handle for a HTTP Port we may want to use when logging
        self.port = None

        # Prepare the routes
        prepared_routes = self._prepare_routes(routes)

        # Prepare the paths
        self._prepare_paths()

        # If a translation path is specified, load the translations
        if 'translation_path' in self._settings:
            self._logger.info('Loading translations from %s',
                              self._settings['translation_path'])
            from tornado import locale
            locale.load_translations(self._settings['translation_path'])

        # Set the app version from the version setting in this file
        self._prepare_version()

        # Setup the UI modules
        self._prepare_transforms()

        # Setup the UI modules
        self._prepare_uimodules()

        # Create our Application for this process
        super(TinmanApplication, self).__init__(prepared_routes,
                                                **self._settings)
Esempio n. 19
0
    def _load_application(self):
        """
        """
        if settings.translation:
            try:
                from tornado import locale
                locale.load_translations(settings.translations_dir)
            except:
                warnings.warn(
                    'locale dir load failure,maybe your config file is not set correctly.'
                )

        apps = settings.INSTALLED_APPS
        if not apps:
            raise ConfigError('settings.INSTALLED_APPS is empty')
        handlers = []
        for app_name in apps:
            handlers += get_handlers(app_name)
        app = self._install_application(handlers)
        self.router = RuleRouter([Rule(PathMatches('/.*'), app)])
Esempio n. 20
0
    def load_application(self, application=None):
        #加载app,进行初始化配置,如无ap参数,则使用内置app初始化
        #加载本地化配置
        if self.settings.TRANSLATIONS:
            try:
                from tornado import locale

                locale.load_translations(
                    self.settings.TRANSLATIONS_CONF.translations_dir)
            except:
                warnings.warn(
                    'locale dir load failure,maybe your config file is not set correctly.'
                )

        if not application:
            if not self.urls:
                raise TorngasError("urls not found.")

            self.application = application_module.Application(
                handlers=self.urls,
                default_host='',
                transforms=None,
                wsgi=False,
                **self.settings.TORNADO_CONF)
        else:
            if isinstance(application, tornado.web.Application):
                self.application = application
            else:
                self.application = application(handlers=self.urls,
                                               default_host='',
                                               transforms=None,
                                               wsgi=False,
                                               **self.settings.TORNADO_CONF)

        self.application.project_path = self.proj_path \
            if self.proj_path.endswith('/') else self.proj_path + '/'

        tmpl = self.settings.TEMPLATE_CONFIG.template_engine
        self.application.tmpl = import_object(tmpl) if tmpl else None

        return self
Esempio n. 21
0
def init_locale(config):
    """
    Load per-module ``lang`` folder CSV translations
    """
    chain = defaultdict(lambda: defaultdict(ChainMap))

    for m in config.modules_loaded:
        lang_path = os.path.join(config.root_path, m, 'lang')
        if not os.path.exists(lang_path):
            continue
        locale.load_translations(lang_path)

        # old translations is overrided by a `load` call,
        # so this is a hack to chain all mobule's translations into bigger one
        for lang, plurals in locale._translations.items():
            for plural, translation in plurals.items():
                chain[lang][plural].maps.append(translation)

    locale._translations = chain
    locale._supported_locales = frozenset(
        list(chain.keys()) + [locale._default_locale])
Esempio n. 22
0
    def load_application(self, default_host='', transforms=None, wsgi=False, urls=None):
        #加载app,进行初始化配置,如无ap参数,则使用内置app初始化
        if not urls: urls = []
        #加载本地化配置
        if self.settings.TRANSLATIONS:
            try:
                from tornado import locale

                locale.load_translations(self.settings.TRANSLATIONS_CONF.translations_dir)
            except:
                warnings.warn('locale dir load failure,maybe your config file is not set correctly.')

        #初始化app
        if not self.application:
            self.application = application_module.AppApplication(handlers=urls, default_host=default_host,
                                                                 transforms=transforms, wsgi=wsgi,
                                                                 **self.settings.TORNADO_CONF)

        self.application.project_path = self.proj_path if self.proj_path.endswith('/') else self.proj_path + '/'
        self.application.tmpl = import_object(self.settings.TEMPLATE_ENGINE) if self.settings.TEMPLATE_ENGINE else None
        return self.application
Esempio n. 23
0
    def main(self,path):
        #import tornado stuff
        import tornado.web, tornado.httpserver, tornado.ioloop, tornado.options
        from tornado.options import options
        from config import options_setup
        from whirlwind.db.mongo import Mongo
        
        #parse the app config
        tornado.options.parse_config_file(os.path.join(path,'config/settings.py'))
        #parse the command line args
        tornado.options.parse_command_line()
        
        #connect to our db using our options set in settings.py
        Mongo.create(host=options.db_host, port=options.db_port)
        
        #init our url routes
        url_routes = self.init_routes()
        
        #init a logger
        self.init_logging(options.log)
        
        #add in any app settings 
        settings = {
            "static_path": options.static_path,
            "cookie_secret": options.cookie_secret,
            "login_url": options.login_url,
        }
        
        #setup the controller action routes
        self.application = tornado.web.Application(url_routes,**settings)

        #instantiate a server instance
        http_server = tornado.httpserver.HTTPServer(self.application)
        
        #bind server to port
        http_server.listen(options.port)

        #gets locales at server start
	    locale.load_translations(options.locales)
Esempio n. 24
0
from bson.objectid import ObjectId
from bson.errors import InvalidId
from datetime import datetime, timedelta
from tornado import locale

import os
import requests
import logging

from .fb_api import *
from .csv import getCsvStrFrom2DArray

SERVER_DOMAIN = os.environ.get('SERVER_DOMAIN', '')

locale.load_translations(os.path.join(os.path.dirname(__file__), 'locale'))


class _Translate():
    def __init__(self, loc_str, timezone):
        self._lo = locale.get(loc_str)
        self._tznum = timezone
        self._tz = timedelta(hours=timezone)

    def __call__(self, trans_str):
        return self._lo.translate(trans_str)

    def toDatetime(self, time_str, format_str):
        time_obj = datetime.strptime(time_str, format_str)
        return time_obj - self._tz
Esempio n. 25
0
# -*- coding: utf-8 -*-
from tornado import locale
#国际化
locale.load_translations("./protected/translations")
locale.set_default_locale("zh_CN")
_locale = locale.get()


class AdminErrorMessage(object):
    error_message = {
        '001': _locale.translate('admin_userinfo_incomplete').encode(
            "utf-8"),  #填写信息不完整
        '002':
        _locale.translate('admin_user_not_exist').encode("utf-8"),  #'该用户不存在'
        '003': _locale.translate('admin_password_no_correct').encode(
            "utf-8"),  #'密码错误'
        '004': _locale.translate('admin_session_had_expired').encode(
            "utf-8"),  #'您的会话已经过期'
        '005':
        _locale.translate('admin_delete_error').encode("utf-8"),  #'删除失败'
        '006': _locale.translate('admin_add_error').encode("utf-8"),  #'添加失败'
        '007':
        _locale.translate('admin_update_error').encode("utf-8"),  #'修改失败'
        '008':
        _locale.translate('admin_same_error').encode("utf-8"),  #'存在相同记录'
    }


class ErrorMessage(object):
    error_message = {
        '001': _locale.translate('login_fail').encode("utf-8"),  #登录失败
Esempio n. 26
0
 def setUp(self):
     super(TornadoApplicationTest, self).setUp()
     locale.load_translations('tests/translations')
Esempio n. 27
0
 def setUp(self):
     super(TornadoApplicationTest, self).setUp()
     locale.load_translations('tests/translations')
Esempio n. 28
0
    (r"/sales", SalesHandler),
    (r"/register_sale", RegisterSaleHandler),
    (r"/sale", ViewSaleHandler),
    (r"/remove_sale", RemoveSaleHandler),
    (r"/reports", ReportsHandler),
    (r"/reports/best_client", BestClientHandler),
    (r"/jquery_ui/(.*)", StaticFileHandler, {"path": "./external_modules/jquery_ui"}),
    (r"/font-awesome-4.3.0/(.*)", StaticFileHandler, {"path": "./external_modules/font-awesome-4.3.0"}),
    (r"/(.*\.css)", StaticFileHandler, {"path": "./www/styles"}),
    (r"/(.*\.js)", StaticFileHandler, {"path": "./www/scripts"}),
    (r"/(.*\.png)", StaticFileHandler, {"path": "./www/images"}),
], **settings)
redirect_protocol = Application([
    (r"/.*", RedirectProtocolHandler),
])
database = Redis()
databases = dict(map(lambda line: line.strip("\n").split(":"), open("databases.dat").readlines()))

if __name__ == "__main__":
    locale.load_translations("./locales")
    redirect_protocol.listen(8000)
    https_server = HTTPServer(application, ssl_options={
        "certfile": "./certificate/carbono.crt",
        "keyfile": "./certificate/carbono.pem",
    })
    
    https_server.listen(8443)
    IOLoop.instance().start()
    

Esempio n. 29
0
from tornado import autoreload, locale
from tornado.web import StaticFileHandler
import abeja.server.web.handlers

settings = {
    "debug": True,
    "template_path": "./web/static/template",
    "cookie_secret": "DOVIETHOA",
    
    "ui_modules": {"UserToolbar": abeja.server.web.handlers.UserToolbar}
}

application = tornado.web.Application([
    (r"/res/style/(.*)", StaticFileHandler, {"path": "./web/static/style"}),
    
    (r"/", abeja.server.web.handlers.HomeHandler),
    (r"/index.html", abeja.server.web.handlers.HomeHandler),
    (r"/login.html", abeja.server.web.handlers.UserLoginHandler),
    (r"/logout.html", abeja.server.web.handlers.UserLogoutHandler),
    (r"/register.html", abeja.server.web.handlers.UserRegisterHandler),
], **settings)

locale.set_default_locale("vi_VN")
locale.load_translations("./web/static/lang")

if __name__ == "__main__":
    application.listen(3692)
    ioloop = tornado.ioloop.IOLoop.instance()
    autoreload.start(ioloop)
    ioloop.start()
Esempio n. 30
0
File: app.py Progetto: 52lemon/djinn
    """Base Application for djinn framework"""

    def reverse_api(self, request):
        """Returns a URL name for a request"""
        rule_name = None
        
        if hasattr(self, "_get_host_handlers"):
            # legacy
            handlers = self._get_host_handlers(request)
            for spec in handlers:
                match = spec.regex.match(request.path)
                if match:
                    rule_name = spec.name
                    break
        else:
            for rule in self.wildcard_router.rules:
                if rule.matcher.match(request) is not None:
                    rule_name = rule.name
                    break

        return rule_name


translation_folder = "translations"
here = os.path.dirname(os.path.realpath(__file__))
load_translations(os.path.join(here, translation_folder))

app_translation = os.path.join(os.getcwd(), translation_folder)
if os.path.isdir(app_translation):
    load_translations(app_translation)
Esempio n. 31
0
"""Base Application"""

import os

from tornado.locale import load_translations
from tornado.web import Application


class DjinnApplication(Application):

    """Base Application for djinn framework"""

    def reverse_api(self, request):
        """Returns a URL name for a request"""
        handlers = self._get_host_handlers(request)

        for spec in handlers:
            match = spec.regex.match(request.path)
            if match:
                return spec.name

        return None

translation_folder = "translations"
here = os.path.dirname(os.path.realpath(__file__))
load_translations(os.path.join(here, translation_folder))

app_translation = os.path.join(os.getcwd(), translation_folder)
if os.path.isdir(app_translation):
    load_translations(app_translation)
Esempio n. 32
0
        }
        if not autoescape:
            config['autoescape'] = None

        # create jinja evironment here to make its own cache works
        template_path = os.path.join(template_path, 'jinja')
        self.env = Environment(loader=FileSystemLoader(template_path),
                               auto_reload=config['debug'],
                               autoescape=autoescape,
                               extensions=['jinja2.ext.autoescape'])
        self.env.filters['chunks'] = chunks
        self.env.filters['datetimeformat'] = datetimeformat

        super(Application, self).__init__(app_handlers, **config)


if __name__ == "__main__":
    define("debug", default=0, help="run debug mode", type=int)
    define("autoescape", default=0, help="enable autoescape", type=int)
    define("port", default=8888, help="run on the given port", type=int)

    tornado.options.parse_command_line()
    translations = os.path.join(PROJECT_DIR, "../translations")
    load_translations(translations)
    set_default_locale("ru_RU")

    logging.info("start server on port %s" % options.port)
    application = tornado.httpserver.HTTPServer(Application())
    application.listen(options.port)
    tornado.ioloop.IOLoop.instance().start()
Esempio n. 33
0
File: app.py Progetto: mqshen/MyTask
    def __init__(self, settings):
        from controller.attachment import AttachmentHandler, AvatarHandler
        from controller.search import AutoCompleteHandler
        from controller.mycalendar import  CalendarHandler, CalendarEventHandler, CalendarEventModifyHandler
        from controller.operation import OperationHandler, TodoItemLogHandler
        from controller.project import ProjectHandler, ProjectFilesHandler, ProjectColorHandler, ProjectDetailHandler, \
                ProjectAccessHandler, NewProjectHandler
        from controller.todo import TodoListHandler, TodoListDetailHandler, TodoItemHandler, TodoItemDetailHandler, \
                TodoItemModifyHandler, TodoItemCommentHandler, TodoListModifyHandler, TodoListCommentHandler
        from controller.topic import MessageHandler, MessageDetailHandler, NewMessageHandler, CommentHandler, CommentDetailHandler
        from controller.user import RegisterHandler, LoginHandler, SignOutHandler, TeamNewHandler, TeamHandler, SettingHandler, \
                PeopleHandler, NewPeopleHandler, PeopleDetailHandler, JoinHandler
        from controller.calendarfeed import CalendarFeedHandler, CalendarFeedPortalHandler, CalendarItemFeedHandler
        from controller.mygraphs import ProjectGraphsHandler, ProjectDataHandler, ProjectTodoGraphsHandler

        handlers = [
            ('/([0-9]+)', ProjectHandler),
            ('/([0-9]+)/attachment/([0-9A-Za-z]+)', AttachmentHandler),
            ('/([0-9]+)/calendar', CalendarHandler),
            ('/([0-9]+)/event', CalendarEventHandler),
            ('/([0-9]+)/event/([0-9]+)/trash', CalendarEventModifyHandler),
            ('/([0-9]+)/operation', OperationHandler),
            ('/([0-9]+)/project', ProjectHandler),
            ('/([0-9]+)/project/([0-9]+)/files', ProjectFilesHandler),
            ('/([0-9]+)/project/([0-9]+)/color', ProjectColorHandler),
            ('/([0-9]+)/project/([0-9]+)', ProjectDetailHandler),
            ('/([0-9]+)/project/([0-9]+)/access', ProjectAccessHandler),
            ('/([0-9]+)/project/([0-9]+)/graphs', ProjectGraphsHandler),
            ('/([0-9]+)/project/([0-9]+)/todographs', ProjectTodoGraphsHandler),
            ('/([0-9]+)/project/([0-9]+)/(messagedata|messageuserdata|tododata|todouserdata)', ProjectDataHandler),
            ('/([0-9]+)/project/new', NewProjectHandler),
            ('/([0-9]+)/project/([0-9]+)/todolist', TodoListHandler),
            ('/([0-9]+)/project/([0-9]+)/todolist/([0-9]+)', TodoListDetailHandler),
            ('/([0-9]+)/project/([0-9]+)/todolist/([0-9]+)/trash', TodoListModifyHandler),
            ('/([0-9]+)/project/([0-9]+)/todolist/([0-9]+)/comment', TodoListCommentHandler),
            ('/([0-9]+)/project/([0-9]+)/todolist/([0-9]+)/todoitem', TodoItemHandler),
            ('/([0-9]+)/project/([0-9]+)/todolist/([0-9]+)/todoitem/([0-9]+)', TodoItemDetailHandler),
            ('/([0-9]+)/project/([0-9]+)/todolist/([0-9]+)/todoitem/([0-9]+)/log', TodoItemLogHandler),
            ('/([0-9]+)/project/([0-9]+)/todolist/([0-9]+)/todoitem/([0-9]+)/(done|undone|trash)', TodoItemModifyHandler),
            ('/([0-9]+)/project/([0-9]+)/todolist/([0-9]+)/todoitem/([0-9]+)/comment', TodoItemCommentHandler),
            ('/([0-9]+)/project/([0-9]+)/message', MessageHandler),
            ('/([0-9]+)/project/([0-9]+)/message/([0-9]+)', MessageDetailHandler),
            ('/([0-9]+)/project/([0-9]+)/message/new', NewMessageHandler),
            ('/([0-9]+)/project/([0-9]+)/message/([0-9]+)/comment', CommentHandler),
            ('/([0-9]+)/project/([0-9]+)/message/([0-9]+)/comment/([0-9]+)', CommentDetailHandler),
            ('/([0-9]+)/people', PeopleHandler),
            ('/([0-9]+)/people/([0-9]+)', PeopleDetailHandler),
            ('/([0-9]+)/people/new', NewPeopleHandler),
            ('/([0-9]+)/calendar_feeds', CalendarFeedPortalHandler),
            ('/([0-9]+)/calendar_feeds.ics', CalendarFeedHandler),
            ('/([0-9]+)/calendar_feeds/([cp][0-9]+).ics', CalendarItemFeedHandler),
            ('/avatar', AvatarHandler),
            ('/avatar/([0-9A-Za-z]+)', AvatarHandler),
            ('/attachment', AttachmentHandler),
            ('/register', RegisterHandler),
            ('/login', LoginHandler),
            ('/signOut', SignOutHandler),
            ('/team', TeamNewHandler),
            ('/', TeamNewHandler),
            ('/team/([0-9]+)', TeamHandler),
            ('/settings', SettingHandler),
            ('/join/([0-9a-z]+)', JoinHandler),
            ('/autocomplete', AutoCompleteHandler),
        ]
        pool = redis.ConnectionPool(host=options.redis.get("host"), port=options.redis.get("port"), db=0)
        r = redis.Redis(connection_pool=pool)
        self.session_store = RedisSessionStore(r)
        tornado.web.Application.__init__(self, handlers, **settings)
        
        qm = QueMail.get_instance()
        qm.init(options.smtp.get("host"), options.smtp.get("user"), options.smtp.get("password"))
        qm.start()

        from tornado import locale
        language_path = os.path.join(os.path.dirname(__file__), "i18n")
        locale.load_translations(language_path)
        locale.set_default_locale(options.locale)
Esempio n. 34
0
File: app.py Progetto: mqshen/MyTask
    def __init__(self, settings):
        from controller.attachment import AttachmentHandler, AvatarHandler
        from controller.search import AutoCompleteHandler
        from controller.mycalendar import CalendarHandler, CalendarEventHandler, CalendarEventModifyHandler
        from controller.operation import OperationHandler, TodoItemLogHandler
        from controller.project import ProjectHandler, ProjectFilesHandler, ProjectColorHandler, ProjectDetailHandler, \
                ProjectAccessHandler, NewProjectHandler
        from controller.todo import TodoListHandler, TodoListDetailHandler, TodoItemHandler, TodoItemDetailHandler, \
                TodoItemModifyHandler, TodoItemCommentHandler, TodoListModifyHandler, TodoListCommentHandler
        from controller.topic import MessageHandler, MessageDetailHandler, NewMessageHandler, CommentHandler, CommentDetailHandler
        from controller.user import RegisterHandler, LoginHandler, SignOutHandler, TeamNewHandler, TeamHandler, SettingHandler, \
                PeopleHandler, NewPeopleHandler, PeopleDetailHandler, JoinHandler
        from controller.calendarfeed import CalendarFeedHandler, CalendarFeedPortalHandler, CalendarItemFeedHandler
        from controller.mygraphs import ProjectGraphsHandler, ProjectDataHandler, ProjectTodoGraphsHandler

        handlers = [
            ('/([0-9]+)', ProjectHandler),
            ('/([0-9]+)/attachment/([0-9A-Za-z]+)', AttachmentHandler),
            ('/([0-9]+)/calendar', CalendarHandler),
            ('/([0-9]+)/event', CalendarEventHandler),
            ('/([0-9]+)/event/([0-9]+)/trash', CalendarEventModifyHandler),
            ('/([0-9]+)/operation', OperationHandler),
            ('/([0-9]+)/project', ProjectHandler),
            ('/([0-9]+)/project/([0-9]+)/files', ProjectFilesHandler),
            ('/([0-9]+)/project/([0-9]+)/color', ProjectColorHandler),
            ('/([0-9]+)/project/([0-9]+)', ProjectDetailHandler),
            ('/([0-9]+)/project/([0-9]+)/access', ProjectAccessHandler),
            ('/([0-9]+)/project/([0-9]+)/graphs', ProjectGraphsHandler),
            ('/([0-9]+)/project/([0-9]+)/todographs',
             ProjectTodoGraphsHandler),
            ('/([0-9]+)/project/([0-9]+)/(messagedata|messageuserdata|tododata|todouserdata)',
             ProjectDataHandler),
            ('/([0-9]+)/project/new', NewProjectHandler),
            ('/([0-9]+)/project/([0-9]+)/todolist', TodoListHandler),
            ('/([0-9]+)/project/([0-9]+)/todolist/([0-9]+)',
             TodoListDetailHandler),
            ('/([0-9]+)/project/([0-9]+)/todolist/([0-9]+)/trash',
             TodoListModifyHandler),
            ('/([0-9]+)/project/([0-9]+)/todolist/([0-9]+)/comment',
             TodoListCommentHandler),
            ('/([0-9]+)/project/([0-9]+)/todolist/([0-9]+)/todoitem',
             TodoItemHandler),
            ('/([0-9]+)/project/([0-9]+)/todolist/([0-9]+)/todoitem/([0-9]+)',
             TodoItemDetailHandler),
            ('/([0-9]+)/project/([0-9]+)/todolist/([0-9]+)/todoitem/([0-9]+)/log',
             TodoItemLogHandler),
            ('/([0-9]+)/project/([0-9]+)/todolist/([0-9]+)/todoitem/([0-9]+)/(done|undone|trash)',
             TodoItemModifyHandler),
            ('/([0-9]+)/project/([0-9]+)/todolist/([0-9]+)/todoitem/([0-9]+)/comment',
             TodoItemCommentHandler),
            ('/([0-9]+)/project/([0-9]+)/message', MessageHandler),
            ('/([0-9]+)/project/([0-9]+)/message/([0-9]+)',
             MessageDetailHandler),
            ('/([0-9]+)/project/([0-9]+)/message/new', NewMessageHandler),
            ('/([0-9]+)/project/([0-9]+)/message/([0-9]+)/comment',
             CommentHandler),
            ('/([0-9]+)/project/([0-9]+)/message/([0-9]+)/comment/([0-9]+)',
             CommentDetailHandler),
            ('/([0-9]+)/people', PeopleHandler),
            ('/([0-9]+)/people/([0-9]+)', PeopleDetailHandler),
            ('/([0-9]+)/people/new', NewPeopleHandler),
            ('/([0-9]+)/calendar_feeds', CalendarFeedPortalHandler),
            ('/([0-9]+)/calendar_feeds.ics', CalendarFeedHandler),
            ('/([0-9]+)/calendar_feeds/([cp][0-9]+).ics',
             CalendarItemFeedHandler),
            ('/avatar', AvatarHandler),
            ('/avatar/([0-9A-Za-z]+)', AvatarHandler),
            ('/attachment', AttachmentHandler),
            ('/register', RegisterHandler),
            ('/login', LoginHandler),
            ('/signOut', SignOutHandler),
            ('/team', TeamNewHandler),
            ('/', TeamNewHandler),
            ('/team/([0-9]+)', TeamHandler),
            ('/settings', SettingHandler),
            ('/join/([0-9a-z]+)', JoinHandler),
            ('/autocomplete', AutoCompleteHandler),
        ]
        pool = redis.ConnectionPool(host=options.redis.get("host"),
                                    port=options.redis.get("port"),
                                    db=0)
        r = redis.Redis(connection_pool=pool)
        self.session_store = RedisSessionStore(r)
        tornado.web.Application.__init__(self, handlers, **settings)

        qm = QueMail.get_instance()
        qm.init(options.smtp.get("host"), options.smtp.get("user"),
                options.smtp.get("password"))
        qm.start()

        from tornado import locale
        language_path = os.path.join(os.path.dirname(__file__), "i18n")
        locale.load_translations(language_path)
        locale.set_default_locale(options.locale)
Esempio n. 35
0
 def start(self, args):
     port = args.port if args.port else 8080
     app = webapp()
     app.listen(port)
     locale.load_translations(settings.LOCALE_DIR)
     IOLoop.current().start()