How to use the gramex.config.variables function in gramex

To help you get started, we’ve selected a few gramex examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github gramener / gramex / testlib / test_cache_module.py View on Github external
def setUpClass(cls):
        cls.url = dbutils.mysql_create_db(variables.MYSQL_SERVER, 'test_cache',
                                          t1=cls.data, t2=cls.data)
        cls.engine = sa.create_engine(cls.url, encoding=str_utf8)
github gramener / gramex / testlib / test_cache_module.py View on Github external
def setUpClass(cls):
        cls.url = dbutils.postgres_create_db(variables.POSTGRES_SERVER, 'test_cache',
                                             **{'t1': cls.data, 't2': cls.data, 'sc.t3': cls.data})
        cls.engine = sa.create_engine(cls.url, encoding=str_utf8)
github gramener / gramex / tests / test_formhandler.py View on Github external
def test_mysql(self):
        dbutils.mysql_create_db(variables.MYSQL_SERVER, 'test_formhandler', sales=self.sales)
        try:
            self.check_filter('/formhandler/mysql', na_position='first')
        finally:
            dbutils.mysql_drop_db(variables.MYSQL_SERVER, 'test_formhandler')
github gramener / gramex / tests / test_queryhandler.py View on Github external
def setUpClass(cls):
        dbutils.mysql_create_db(variables.MYSQL_SERVER, 'test_queryhandler', actors=cls.data)
github gramener / gramex / tests / test_translater.py View on Github external
def setUpClass(cls):
        cls.stores = ['db', 'xlsx']
        cls.caches = [
            variables['TRANSLATE_' + store.upper()]
            for store in cls.stores
        ]
        cls.tearDownClass()
        gramex.ml.translate_api['mock'] = translate_mock
github gramener / gramex / gramex / ml.py View on Github external
args = handler.argparse(
        q={'nargs': '*', 'default': []},
        source={'default': source},
        target={'default': target}
    )
    import gramex
    result = yield gramex.service.threadpool.submit(
        translate, *args.q, source=args.source, target=args.target, key=key, cache=cache, api=api)

    # TODO: support gramex.data.download features
    handler.set_header('Content-Type', 'application/json; encoding="UTF-8"')
    raise Return(result.to_json(orient='records'))


_languagetool = {
    'defaults': {k: v for k, v in variables.items() if k.startswith('LT_')},
    'installed': os.path.isdir(variables['LT_CWD'])
}


@coroutine
def languagetool(handler, *args, **kwargs):
    import gramex
    merge(kwargs, _languagetool['defaults'], mode='setdefault')
    yield gramex.service.threadpool.submit(languagetool_download)
    if not handler:
        lang = kwargs.get('lang', 'en-us')
        q = kwargs.get('q', '')
    else:
        lang = handler.get_argument('lang', 'en-us')
        q = handler.get_argument('q', '')
    result = yield languagetoolrequest(q, lang, **kwargs)
github gramener / gramex / gramex / apps / guide / uicomponents / guide_ui_app.py View on Github external
from __future__ import unicode_literals

import os
from gramex.config import variables
from tornado.escape import xhtml_escape

folder = os.path.dirname(os.path.abspath(__file__))
config_file = os.path.join(folder, 'config.yaml')
ui_config_file = os.path.join(variables['GRAMEXPATH'], 'apps', 'ui', 'config.yaml')


def view_source(html):
    '''Return the HTML with an escaped view source block appended to it'''
    s = html.decode('utf-8')
    return ('<div class="viewsource-wrapper">' + s +
            '<pre class="viewsource"><code class="language-html">' + xhtml_escape(s.strip()) +
            '</code></pre></div>')


def only_source(html):
    '''Return only the escaped view source block'''
    s = html.decode('utf-8')
    return ('<pre class="viewsource"><code class="language-html">' + xhtml_escape(s.strip()) +
            '</code></pre>')
github gramener / gramex / gramex / __init__.py View on Github external
import time
    import requests
    import platform
    from . import services

    if not services.info.eventlog:
        return app_log.error('eventlog: service is not running. So Gramex update is disabled')

    query = services.info.eventlog.query
    update = query('SELECT * FROM events WHERE event="update" ORDER BY time DESC LIMIT 1')
    delay = 24 * 60 * 60            # Wait for one day before updates
    if update and time.time() &lt; update[0]['time'] + delay:
        return app_log.debug('Gramex update ran recently. Deferring check.')

    meta = {
        'dir': variables.get('GRAMEXDATA'),
        'uname': platform.uname(),
    }
    if update:
        events = query('SELECT * FROM events WHERE time &gt; ? ORDER BY time',
                       (update[0]['time'], ))
    else:
        events = query('SELECT * FROM events')
    logs = [dict(log, **meta) for log in events]

    r = requests.post(url, data=json.dumps(logs))
    r.raise_for_status()
    update = r.json()
    version = update['version']
    if version &gt; __version__:
        app_log.error('Gramex %s is available. See https://learn.gramener.com/guide/', version)
    elif version &lt; __version__:
github gramener / gramex / gramex / apps / ui / uiapp.py View on Github external
def bootstraptheme(handler):
    '''
    Return a bootstrap theme based on the custom SASS variables provided.
    '''
    args = dict(variables.get('ui-bootstrap', {}))
    args.update({key: handler.get_arg(key) for key in handler.args})
    args = {key: val for key, val in args.items() if val}

    cache_key = json.dumps(args, sort_keys=True, ensure_ascii=True).encode('utf-8')
    cache_key = md5(cache_key).hexdigest()[:5]

    # Replace fonts from config file, if available
    config = gramex.cache.open(config_file)
    google_fonts = set()
    for key in ('font-family-base', 'headings-font-family'):
        if key in args and args[key] in config['fonts']:
            fontinfo = config['fonts'][args[key]]
            args[key] = fontinfo['stack']
            if 'google' in fontinfo:
                google_fonts.add(fontinfo['google'])
github gramener / gramex / gramex / install.py View on Github external
- A relative path to the Gramex apps/ folder

    Returns the absolute path of the final target path.

    This supports:

    - ``make`` (if Makefile exists)
    - ``powershell -File setup.ps1``
    - ``bash setup.sh``
    - ``pip install -r requirements.txt``
    - ``python setup.py``
    - ``yarn install`` else ``npm install``
    - ``bower --allow-root install``
    '''
    if not os.path.exists(target):
        app_target = os.path.join(variables['GRAMEXPATH'], 'apps', target)
        if not os.path.exists(app_target):
            raise OSError('No directory %s' % target)
        target = app_target
    target = os.path.abspath(target)
    app_log.info('Setting up %s', target)
    for file, runners in setup_paths.items():
        setup_file = os.path.join(target, file)
        if not os.path.exists(setup_file):
            continue
        for exe, cmd in runners.items():
            exe_path = which(exe)
            if exe_path is not None:
                cmd = cmd.format(FILE=setup_file, EXE=exe_path)
                app_log.info('Running %s', cmd)
                _run_console(cmd, cwd=target)
                break