Ejemplo n.º 1
0
 def __call__(self, environ, start_response):
     from controller.maintenance import MaintenanceController
     ui_lang = self.get_lang(environ)
     translation.activate(ui_lang)
     request = Request(environ)
     app = MaintenanceController(request=request, ui_lang=ui_lang)
     status, headers, sid_is_valid, body = app.run()
     response = Response(response=body, status=status, headers=headers)
     return response(environ, start_response)
Ejemplo n.º 2
0
 def __call__(self, environ, start_response):
     from controller.maintenance import MaintenanceController
     ui_lang = self.get_lang(environ)
     translation.activate(ui_lang)
     request = Request(environ)
     app = MaintenanceController(request=request, ui_lang=ui_lang)
     status, headers, sid_is_valid, body = app.run()
     response = Response(response=body, status=status, headers=headers)
     return response(environ, start_response)
Ejemplo n.º 3
0
    def __call__(self, environ, start_response):
        ui_lang = self.get_lang(environ)
        translation.activate(ui_lang)
        environ['REQUEST_URI'] = wsgiref.util.request_uri(
            environ)  # TODO remove?
        app_url_prefix = settings.get_str('global', 'action_path_prefix', '')
        if app_url_prefix and environ['PATH_INFO'].startswith(app_url_prefix):
            environ['PATH_INFO'] = environ['PATH_INFO'][len(app_url_prefix):]

        sessions = plugins.runtime.SESSIONS.instance
        request = JSONRequest(environ)
        sid = request.cookies.get(sessions.get_cookie_name())
        if sid is None:
            request.session = sessions.new()
        else:
            request.session = sessions.get(sid)

        sid_is_valid = True
        if environ['PATH_INFO'] in ('/', ''):
            url = environ['REQUEST_URI'].split('?')[0]
            if not url.endswith('/'):
                url += '/'
            status = '303 See Other'
            headers = [('Location', f'{self._root_url(environ)}query')]
            body = ''
        # old-style (CGI version) URLs are redirected to new ones
        elif '/run.cgi/' in environ['REQUEST_URI']:
            status = '301 Moved Permanently'
            headers = [('Location',
                        environ['REQUEST_URI'].replace('/run.cgi/', '/'))]
            body = ''
        else:
            app = self.create_controller(environ['PATH_INFO'],
                                         request=request,
                                         ui_lang=ui_lang)
            status, headers, sid_is_valid, body = app.run()
        response = Response(response=body, status=status, headers=headers)
        if not sid_is_valid:
            curr_data = dict(request.session)
            request.session = sessions.new()
            request.session.update(curr_data)
            request.session.modified = True
        if request.session.should_save:
            sessions.save(request.session)
            cookie_path = settings.get_str('global', 'cookie_path_prefix', '/')
            cookies_same_site = settings.get('global', 'cookies_same_site',
                                             None)
            response.set_cookie(sessions.get_cookie_name(),
                                request.session.sid,
                                path=cookie_path,
                                secure=cookies_same_site is not None,
                                samesite=cookies_same_site)

        return response(environ, start_response)
Ejemplo n.º 4
0
    def __call__(self, environ, start_response):
        """
        Works as specified by the WSGI
        """
        ui_lang = get_lang(environ)
        translation.activate(ui_lang)
        l10n.activate(ui_lang)
        environ['REQUEST_URI'] = wsgiref.util.request_uri(
            environ)  # TODO remove?

        sessions = plugins.get('sessions')
        request = Request(environ)
        sid = request.cookies.get(sessions.get_cookie_name())
        if sid is None:
            request.session = sessions.new()
        else:
            request.session = sessions.get(sid)

        sid_is_valid = True
        if environ['PATH_INFO'] in ('/', ''):
            url = environ['REQUEST_URI'].split('?')[0]
            if not url.endswith('/'):
                url += '/'
            status = '303 See Other'
            headers = [('Location', '%sfirst_form' % url)]
            body = ''
        elif '/run.cgi/' in environ[
                'REQUEST_URI']:  # old-style (CGI version) URLs are redirected to new ones
            status = '301 Moved Permanently'
            headers = [('Location',
                        environ['REQUEST_URI'].replace('/run.cgi/', '/'))]
            body = ''
        else:
            controller_class = load_controller_class(environ['PATH_INFO'])
            app = controller_class(request=request, ui_lang=ui_lang)
            status, headers, sid_is_valid, body = app.run()
        response = Response(response=body, status=status, headers=headers)
        if not sid_is_valid:
            curr_data = dict(request.session)
            request.session = sessions.new()
            request.session.update(curr_data)
            request.session.modified = True
        if request.session.should_save:
            sessions.save(request.session)
            response.set_cookie(sessions.get_cookie_name(),
                                request.session.sid)
        return response(environ, start_response)
Ejemplo n.º 5
0
    def __call__(self, environ, start_response):
        ui_lang = self.get_lang(environ)
        translation.activate(ui_lang)
        l10n.activate(ui_lang)
        environ['REQUEST_URI'] = wsgiref.util.request_uri(environ)  # TODO remove?
        app_url_prefix = settings.get_str('global', 'action_path_prefix', '')
        if app_url_prefix and environ['PATH_INFO'].startswith(app_url_prefix):
            environ['PATH_INFO'] = environ['PATH_INFO'][len(app_url_prefix):]

        sessions = plugins.runtime.SESSIONS.instance
        request = Request(environ)
        sid = request.cookies.get(sessions.get_cookie_name())
        if sid is None:
            request.session = sessions.new()
        else:
            request.session = sessions.get(sid)

        sid_is_valid = True
        if environ['PATH_INFO'] in ('/', ''):
            url = environ['REQUEST_URI'].split('?')[0]
            if not url.endswith('/'):
                url += '/'
            status = '303 See Other'
            headers = [('Location', '%sfirst_form' % url)]
            body = ''
        # old-style (CGI version) URLs are redirected to new ones
        elif '/run.cgi/' in environ['REQUEST_URI']:
            status = '301 Moved Permanently'
            headers = [('Location', environ['REQUEST_URI'].replace('/run.cgi/', '/'))]
            body = ''
        else:
            controller_class = self.load_controller_class(environ['PATH_INFO'])
            app = controller_class(request=request, ui_lang=ui_lang)
            status, headers, sid_is_valid, body = app.run()
        response = Response(response=body, status=status, headers=headers)
        if not sid_is_valid:
            curr_data = dict(request.session)
            request.session = sessions.new()
            request.session.update(curr_data)
            request.session.modified = True
        if request.session.should_save:
            sessions.save(request.session)
            response.set_cookie(sessions.get_cookie_name(), request.session.sid)
        return response(environ, start_response)
Ejemplo n.º 6
0
    def __call__(self, environ, start_response):
        """
        Works as specified by the WSGI
        """
        ui_lang = get_lang(environ)
        translation.activate(ui_lang)
        l10n.activate(ui_lang)
        environ['REQUEST_URI'] = wsgiref.util.request_uri(environ)  # TODO remove?

        sessions = plugins.get('sessions')
        request = Request(environ)
        sid = request.cookies.get(sessions.get_cookie_name())
        if sid is None:
            request.session = sessions.new()
        else:
            request.session = sessions.get(sid)

        sid_is_valid = True
        if environ['PATH_INFO'] in ('/', ''):
            url = environ['REQUEST_URI']
            if not url.endswith('/'):
                url += '/'
            status = '303 See Other'
            headers = [('Location', '%sfirst_form' % url)]
            body = ''
        elif '/run.cgi/' in environ['REQUEST_URI']:  # old-style (CGI version) URLs are redirected to new ones
            status = '301 Moved Permanently'
            headers = [('Location', environ['REQUEST_URI'].replace('/run.cgi/', '/'))]
            body = ''
        else:
            controller_class = load_controller_class(environ['PATH_INFO'])
            app = controller_class(request=request, ui_lang=ui_lang)
            status, headers, sid_is_valid, body = app.run(request)
        response = Response(response=body, status=status, headers=headers)
        if not sid_is_valid:
            curr_data = dict(request.session)
            request.session = sessions.new()
            request.session.update(curr_data)
            request.session.modified = True
        if request.session.should_save:
            sessions.save(request.session)
            response.set_cookie(sessions.get_cookie_name(), request.session.sid)
        start_response(status, headers)
        return response(environ, start_response)
Ejemplo n.º 7
0
 def setUp(self):
     self.mock_redis_plugin.clear()
     # these are needed to return anonymous user w/o errors:
     load_translations('en_US')
     activate('en_US')
Ejemplo n.º 8
0
import unittest

sys.path.insert(
    0,
    os.path.realpath(
        '%s/../lib' %
        os.path.dirname(os.path.realpath(__file__))))  # application libraries

PLUGIN_PATH = os.path.join(os.path.dirname(os.path.realpath(__file__)), '..',
                           'lib', 'plugins')
PLUGINS_TESTS_PATH = os.path.join(os.path.dirname(os.path.realpath(__file__)),
                                  'plugins_tests')
CORE_TEST_PATH = os.path.join(os.path.dirname(os.path.realpath(__file__)),
                              'lib')
VERBOSITY = 2

if __name__ == '__main__':
    import translation
    translation.activate('en_US')
    root_suite = unittest.TestSuite()
    root_suite.addTest(unittest.TestLoader().discover(
        start_dir=CORE_TEST_PATH, ))
    root_suite.addTest(unittest.TestLoader().discover(start_dir=PLUGIN_PATH, ))
    root_suite.addTest(unittest.TestLoader().discover(
        start_dir=PLUGINS_TESTS_PATH, ))
    ans = unittest.TextTestRunner(verbosity=VERBOSITY).run(root_suite)
    if len(ans.failures) + len(ans.errors) > 0:
        sys.exit(1)
    else:
        sys.exit(0)
Ejemplo n.º 9
0
def post_syncdb_append_permissions(sender, **kwargs):
    u"""
    1、升级数据库结构, 设置字段默认值
    2、导入初始数据
    3、创建操作权限
    """
    #创建一个超级用户
    print 'johan-------------------------------------: syncdb 命令信号扩展处理'
    if not User.objects.filter(username="******"):
        User.objects.create_superuser("admin", "*****@*****.**", "admin")

    from django.utils import translation
    from sync_contenttype import update_all_contenttypes
    language = settings.LANGUAGE_CODE

    app = sender
    if app.__name__=="base.models":
        call_command('loaddata', 'initial_data_'+language, verbosity=1, database="default") #  将固化数据插入数据库
    created_models = list(kwargs['created_models'])
    verbosity = kwargs["verbosity"]
    interactive = kwargs["interactive"]

    translation.activate(language)  #设置语言
    translation.activate("en-us")   #?????
    
    update_all_contenttypes()   # 同步 models 和 contenttype

    all_models = []
    for i in dir(app):
        try:
            model = app.__getattribute__(i)
        except:
            continue
        if callable(model) and type(model) not in [type(issubclass), type(post_syncdb_append_permissions)]:
            try:
                if issubclass(model, models.Model) and not model._meta.abstract:
                    check_and_create_model_new_fields(model)    #添加新字段
                    check_and_create_model_default(model)         #设置表字段默认值
                    translation.activate("zh-cn")
                    check_and_create_model_permissions(model)   # 添加 model 权限
                    translation.activate(language)
                    check_and_create_model_initial_data(model)  # 执行 model 初始化数据
                    translation.activate("en-us")
                elif issubclass(model, AppOperation) and hasattr(model, 'view'):
                    translation.activate("zh-cn")
                    check_and_create_app_permission(app, model) # 添加 app 权限
                    translation.activate("en-us")
            except:
                print_exc()
    try:
        check_and_create_app_options(app)
    except:
        print_exc()
Ejemplo n.º 10
0
os.environ['MANATEE_REGISTRY'] = settings.get('corpora', 'manatee_registry')
initializer.init_plugin('db')
initializer.init_plugin('sessions')
initializer.init_plugin('auth')
initializer.init_plugin('conc_cache')
initializer.init_plugin('query_storage')
initializer.init_plugin('conc_persistence')
initializer.init_plugin('sessions')
initializer.init_plugin('user_items')
initializer.init_plugin('corparch')
initializer.init_plugin('token_connect', optional=True)
initializer.init_plugin('live_attributes', optional=True)
initializer.init_plugin('dispatch_hook', optional=True)

translation.load_translations(settings.get('global', 'translations'))
translation.activate('en_US')  # background jobs do not need localization

import conclib.calc
import conclib.calc.base
from bgcalc import (freq_calc, subc_calc, coll_calc)


def load_script_module(name, path):
    return imp.load_source(name, path)


class WorkerTaskException(Exception):
    pass


def is_compiled(corp, attr, method):
Ejemplo n.º 11
0
import manatee

os.environ['MANATEE_REGISTRY'] = settings.get('corpora', 'manatee_registry')
initializer.init_plugin('db')
initializer.init_plugin('sessions')
initializer.init_plugin('auth')
initializer.init_plugin('conc_cache')
initializer.init_plugin('query_storage')
initializer.init_plugin('conc_persistence')
initializer.init_plugin('sessions')
initializer.init_plugin('user_items')
initializer.init_plugin('corparch')
initializer.init_plugin('live_attributes', optional=True)

translation.load_translations(settings.get('global', 'translations'))
translation.activate('en_US')  # background jobs do not need localization

import concworker
import task
from bgcalc import freq_calc
from bgcalc import subc_calc
from bgcalc import coll_calc


_, conf = settings.get_full('global', 'calc_backend')
app = task.get_celery_app(conf['conf'])


def load_script_module(name, path):
    return imp.load_source(name, path)
Ejemplo n.º 12
0
def post_syncdb_append_permissions(sender, **kwargs):
    u"""
    1、升级数据库结构, 设置字段默认值
    2、导入初始数据
    3、创建操作权限
    """
    #创建一个超级用户
    print 'johan-------------------------------------: syncdb 命令信号扩展处理'
    if not User.objects.filter(username="******"):
        User.objects.create_superuser("admin", "*****@*****.**", "admin")

    from django.utils import translation
    from sync_contenttype import update_all_contenttypes
    language = settings.LANGUAGE_CODE

    app = sender
    if app.__name__ == "base.models":
        call_command('loaddata',
                     'initial_data_' + language,
                     verbosity=1,
                     database="default")  #  将固化数据插入数据库
    created_models = list(kwargs['created_models'])
    verbosity = kwargs["verbosity"]
    interactive = kwargs["interactive"]

    translation.activate(language)  #设置语言
    translation.activate("en-us")  #?????

    update_all_contenttypes()  # 同步 models 和 contenttype

    all_models = []
    for i in dir(app):
        try:
            model = app.__getattribute__(i)
        except:
            continue
        if callable(model) and type(model) not in [
                type(issubclass),
                type(post_syncdb_append_permissions)
        ]:
            try:
                if issubclass(model,
                              models.Model) and not model._meta.abstract:
                    check_and_create_model_new_fields(model)  #添加新字段
                    check_and_create_model_default(model)  #设置表字段默认值
                    translation.activate("zh-cn")
                    check_and_create_model_permissions(model)  # 添加 model 权限
                    translation.activate(language)
                    check_and_create_model_initial_data(
                        model)  # 执行 model 初始化数据
                    translation.activate("en-us")
                elif issubclass(model, AppOperation) and hasattr(
                        model, 'view'):
                    translation.activate("zh-cn")
                    check_and_create_app_permission(app, model)  # 添加 app 权限
                    translation.activate("en-us")
            except:
                print_exc()
    try:
        check_and_create_app_options(app)
    except:
        print_exc()
Ejemplo n.º 13
0
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
from __future__ import absolute_import
import sys
import os
import unittest

sys.path.insert(0, os.path.realpath('%s/../lib' % os.path.dirname(os.path.realpath(__file__))))  # application libraries

PLUGIN_PATH = os.path.join(os.path.dirname(os.path.realpath(__file__)), '..', 'lib', 'plugins')
PLUGINS_TESTS_PATH = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'plugins_tests')
CORE_TEST_PATH = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'lib')
VERBOSITY = 2

if __name__ == '__main__':
    import translation
    translation.activate('en_US')
    root_suite = unittest.TestSuite()
    root_suite.addTest(unittest.TestLoader().discover(start_dir=CORE_TEST_PATH, ))
    root_suite.addTest(unittest.TestLoader().discover(start_dir=PLUGIN_PATH, ))
    root_suite.addTest(unittest.TestLoader().discover(start_dir=PLUGINS_TESTS_PATH, ))
    ans = unittest.TextTestRunner(verbosity=VERBOSITY).run(root_suite)
    if len(ans.failures) + len(ans.errors) > 0:
        sys.exit(1)
    else:
        sys.exit(0)


Ejemplo n.º 14
0
 def setUp(self):
     self.mock_redis_plugin.clear()
     # these are needed to return anonymous user w/o errors:
     load_translations('en_US')
     activate('en_US')