Python pyramid.settings.asbool() Examples

The following are 30 code examples of pyramid.settings.asbool(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module pyramid.settings , or try the search function .
Example #1
Source File: ificlaims.py    From patzilla with GNU Affero General Public License v3.0 6 votes vote down vote up
def ificlaims_download_handler(request):
    """Download resources from IFI CLAIMS Direct"""

    resource = request.matchdict['resource']
    format   = request.matchdict['format'].lower()
    pretty   = asbool(request.params.get('pretty'))
    seq      = int(request.params.get('seq', 1))
    options = {'pretty': pretty, 'seq': seq}

    try:
        response = ificlaims_download(resource, format, options)

    except IFIClaimsException, ex:
        if type(ex) is IFIClaimsFormatException:
            raise HTTPNotFound(ex)
        else:
            raise HTTPBadRequest(ex) 
Example #2
Source File: __init__.py    From pyramid-jsonapi with GNU Affero General Public License v3.0 6 votes vote down vote up
def error(exc, request):
        """Error method to return jsonapi compliant errors."""
        request.response.content_type = 'application/vnd.api+json'
        request.response.status_code = exc.code
        errors = {
            'errors': [
                {
                    'code': str(exc.code),
                    'detail': exc.detail,
                    'title': exc.title,
                }
            ]
        }
        if asbool(request.registry.settings.get('pyramid_jsonapi.debug_traceback', False)):
            errors['traceback'] = traceback.format_exc()
        return errors 
Example #3
Source File: tween.py    From pyramid_swagger with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def load_settings(registry):
    return Settings(
        swagger12_handler=build_swagger12_handler(
            registry.settings.get('pyramid_swagger.schema12')),
        swagger20_handler=build_swagger20_handler(),
        validate_request=asbool(registry.settings.get(
            'pyramid_swagger.enable_request_validation',
            True,
        )),
        validate_response=asbool(registry.settings.get(
            'pyramid_swagger.enable_response_validation',
            True,
        )),
        validate_path=asbool(registry.settings.get(
            'pyramid_swagger.enable_path_validation',
            True,
        )),
        exclude_paths=get_exclude_paths(registry),
        exclude_routes=set(aslist(registry.settings.get(
            'pyramid_swagger.exclude_routes',
        ) or [])),
        prefer_20_routes=set(aslist(registry.settings.get(
            'pyramid_swagger.prefer_20_routes') or [])),
    ) 
Example #4
Source File: views.py    From kinto-attachment with Apache License 2.0 5 votes vote down vote up
def attachments_ping(request):
    """Heartbeat view for the attachments backend.
    :returns: ``True`` if succeeds to write and delete, ``False`` otherwise.
    """
    # Do nothing if server is readonly.
    if asbool(request.registry.settings.get('readonly', False)):
        return True

    # We will fake a file upload, so pick a file extension that is allowed.
    extensions = request.attachment.extensions or {'json'}
    allowed_extension = "." + list(extensions)[-1]

    status = False
    try:
        content = cgi.FieldStorage()
        content.filename = HEARTBEAT_FILENAME + allowed_extension
        content.file = BytesIO(HEARTBEAT_CONTENT.encode('utf-8'))
        content.type = 'application/octet-stream'

        stored = utils.save_file(request, content, keep_link=False, replace=True)

        relative_location = stored['location'].replace(request.attachment.base_url, '')
        request.attachment.delete(relative_location)

        status = True
    except Exception as e:
        logger.exception(e)
    return status 
Example #5
Source File: views.py    From kinto-attachment with Apache License 2.0 5 votes vote down vote up
def delete_attachment_view(request, file_field):
    keep_old_files = asbool(utils.setting_value(request, 'keep_old_files', default=False))

    utils.delete_attachment(request, keep_old_files=keep_old_files)

    # Remove metadata.
    record = {"data": {}}
    record["data"][file_field] = None
    utils.patch_record(record, request)

    request.response.status = 204 
Example #6
Source File: account.py    From pyvac with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def render(self):

        settings = self.request.registry.settings
        use_ldap = False
        if 'pyvac.use_ldap' in settings:
            use_ldap = asbool(settings.get('pyvac.use_ldap'))

        user_attr = {}
        users_teams = {}
        active_users = []
        if use_ldap:
            # synchronise user groups/roles
            User.sync_ldap_info(self.session)
            ldap = LdapCache()

            user_attr = ldap.get_users_units()
            users_teams = {}
            for team, members in list(ldap.list_teams().items()):
                for member in members:
                    users_teams.setdefault(member, []).append(team)

            active_users = ldap.list_active_users()

        return {'user_count': User.find(self.session, count=True),
                'users': User.find(self.session, order_by=[User.dn]),
                'use_ldap': use_ldap,
                'ldap_info': user_attr,
                'users_teams': users_teams,
                'active_users': active_users,
                } 
Example #7
Source File: common_utils.py    From travelcrm with GNU General Public License v3.0 5 votes vote down vote up
def get_tarifs_timeout():
    settings = get_settings()
    return asbool(settings.get('tarifs.timeout')) 
Example #8
Source File: common_utils.py    From travelcrm with GNU General Public License v3.0 5 votes vote down vote up
def get_tarifs():
    settings = get_settings()
    return asbool(settings.get('tarifs.enabled')) 
Example #9
Source File: common_utils.py    From travelcrm with GNU General Public License v3.0 5 votes vote down vote up
def get_multicompanies():
    settings = get_settings()
    return asbool(settings.get('multicompanies')) 
Example #10
Source File: base.py    From pyvac with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def render(self):
        settings = self.request.registry.settings
        ldap = False
        if 'pyvac.use_ldap' in settings:
            ldap = asbool(settings.get('pyvac.use_ldap'))

        if 'form.cancelled' in self.request.params:
            return self.redirect()

        log.debug('rendering %s' % self.__class__.__name__)
        errors = []
        model = self.get_model()

        if self.user and not self.user.is_admin:
            if model.id != self.user.id:
                return self.redirect('home')

        if 'form.submitted' in self.request.params:

            self.validate(model, errors)

            if not errors:
                try:
                    self.update_model(model)
                    model.validate(self.session, ldap=ldap)
                except ModelError as err:
                    errors.extend(err.errors)

            if not errors:
                self.save_model(model)
                return self.redirect()

        rv = {'errors': errors,
              self.model.__tablename__: model,
              'use_ldap': ldap,
              'csrf_token': self.request.session.get_csrf_token()}

        self.update_view(model, rv)
        log.debug(repr(rv))
        return rv 
Example #11
Source File: util.py    From patzilla with GNU Affero General Public License v3.0 5 votes vote down vote up
def request_to_options(request, options):

    # TODO: transfer all modifiers 1:1

    if asbool(request.params.get('query_data[modifiers][family-remove]')):
        options.update({'feature_family_remove': True})
    elif asbool(request.params.get('query_data[modifiers][family-replace]')):
        options.update({'feature_family_replace': True})

    # this is awful, switch to JSON POST
    for key, value in request.params.iteritems():
        if key.startswith(u'query_data[sorting]'):
            key = key.replace('query_data[sorting]', '').replace('[', '').replace(']', '')
            options.setdefault('sorting', {})
            options['sorting'][key] = value 
Example #12
Source File: util.py    From patzilla with GNU Affero General Public License v3.0 5 votes vote down vote up
def numberlist_util_handler(request):
    response = {}
    numberlist = None

    if request.content_type == 'text/plain':
        numberlist = parse_numberlist(request.text)
        response['numbers-sent'] = numberlist

    if numberlist:
        if asbool(request.params.get('normalize')):
            response['numbers-normalized'] = normalize_numbers(numberlist)

    return response 
Example #13
Source File: views.py    From patzilla with GNU Affero General Public License v3.0 5 votes vote down vote up
def login_page(request):
    tplvars = {
        'username': request.params.get('username', ''),
        'came_from': request.params.get('came_from', ''),
        'error': asbool(request.params.get('error')),
        'reason': request.params.get('reason', ''),
    }
    return tplvars 
Example #14
Source File: account.py    From pyvac with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def append_groups(self, account):
        settings = self.request.registry.settings
        use_ldap = False
        if 'pyvac.use_ldap' in settings:
            use_ldap = asbool(settings.get('pyvac.use_ldap'))
        if use_ldap:
            # update groups only for non LDAP users
            return

        exists = []
        group_ids = [int(id) for id in self.request.params.get('groups')]

        if not group_ids:
            # ensure that account has at least user group otherwise
            # he cannot access anything
            group_ids = [Group.by_name(self.session, 'user').id]

        # only update if there is at least one group provided
        if group_ids:
            # cast as list because of iterator for will only loop on first one
            account_groups = list(account.groups)
            for group in account_groups:
                exists.append(group.id)
                if group.id not in group_ids:
                    if group.name != 'sudoer':
                        account.groups.remove(group)

            for group_id in group_ids:
                if group_id not in exists:
                    account.groups.append(Group.by_id(self.session, group_id)) 
Example #15
Source File: dashboard.py    From kotori with GNU Affero General Public License v3.0 5 votes vote down vote up
def build_panel(self, panel, measurement):

        self.panel_id += 1

        try:
            legend_right_side = asbool(self.channel.settings.graphing_legend_right_side)
        except AttributeError:
            legend_right_side = False

        data_panel = {
            'id': self.panel_id,
            'datasource': self.datasource,
            'panel_title': panel.get('title', 'default'),
            'left_log_base': panel.get('scale', 1),
            'label_y': panel.get('label', ''),
            'format_y': panel.get('format', 'none'),
            'legend_right_side': json.dumps(legend_right_side),
        }

        # Build targets list from fieldnames
        targets_list = []
        for fieldname in panel['fieldnames']:
            data_target = self.get_target(panel, measurement, fieldname)
            target_json = self.build_target(data_target)
            targets_list.append(target_json)

        targets_json = ',\n'.join(targets_list)
        panel_json = self.tpl_panel.render(data_panel, targets=targets_json)
        #print 'panel_json:', panel_json
        try:
            return json.loads(panel_json)
        except Exception:
            log.failure(u'Failed building valid JSON for Grafana panel. data={data}, json={json}',
                data=data_panel, json=panel_json) 
Example #16
Source File: harvesting.py    From thinkhazard with GNU General Public License v3.0 5 votes vote down vote up
def do_execute(self, resources="regions,layers,documents", hazard_type=None, use_cache=False):
        self.use_cache = use_cache or asbool(os.environ.get("USE_CACHE", False))

        resources = resources.split(",")

        if "regions" in resources:
            try:
                self.harvest_regions()
                self.create_region_admindiv_associations()
            except Exception:
                logger.error(traceback.format_exc())
                logger.info("Continue with layers")

        if "layers" in resources:
            try:
                self.harvest_layers(hazard_type)
            except Exception:
                logger.error(traceback.format_exc())
                logger.info("Continue with documents")

        if "documents" in resources:
            try:
                self.harvest_documents()
            except Exception:
                logger.error(traceback.format_exc())

        Harvesting.new(self.dbsession, complete=(self.force is True and hazard_type is None)) 
Example #17
Source File: listeners.py    From kinto-attachment with Apache License 2.0 5 votes vote down vote up
def on_delete_record(event):
    """When a resource record is deleted, delete all related attachments.
    When a bucket or collection is deleted, it removes the attachments of
    every underlying records.
    """
    keep_old_files = asbool(utils.setting_value(event.request, 'keep_old_files', default=False))

    # Retrieve attachments for these records using links.
    resource_name = event.payload['resource_name']
    filter_field = '%s_uri' % resource_name
    uri = event.payload['uri']
    utils.delete_attachment(event.request, link_field=filter_field, uri=uri,
                            keep_old_files=keep_old_files) 
Example #18
Source File: utils.py    From channelstream with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def set_config_types(config):
    """
    convert raw config values to proper types
    :param config:
    :return:
    """
    config = copy.deepcopy(config)
    config["debug"] = asbool(config["debug"])
    config["port"] = int(config["port"])
    config["validate_requests"] = asbool(config["validate_requests"])
    config["enforce_https"] = asbool(config["enforce_https"])
    if not config["cookie_secret"]:
        config["cookie_secret"] = str(uuid.uuid4())

    if config["http_scheme"] not in ["http", "https"]:
        config["http_scheme"] = ""

    for key in ["allow_posting_from", "allow_cors"]:
        if not config[key]:
            continue
        # if those keys are strings from ini convert to lists of individual values
        if isinstance(config[key], str):
            try:
                listed = [ip.strip() for ip in config[key].split(",") if ip.strip()]
                config[key] = listed
            except ValueError:
                pass
    return config 
Example #19
Source File: request.py    From pyvac with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def render(self):
        from datetime import datetime
        today = datetime.now()
        end_date = datetime(today.year, 10, 31)

        previsions = Request.get_previsions(self.session, end_date)

        users_per_id = dict([(user.id, user)
                             for user in User.find(self.session)])

        settings = self.request.registry.settings
        use_ldap = False
        if 'pyvac.use_ldap' in settings:
            use_ldap = asbool(settings.get('pyvac.use_ldap'))

        user_attr = {}
        users_teams = {}
        if use_ldap:
            # synchronise user groups/roles
            User.sync_ldap_info(self.session)
            ldap = LdapCache()
            user_attr = ldap.get_users_units()
            users_teams = {}
            for team, members in list(ldap.list_teams().items()):
                for member in members:
                    users_teams.setdefault(member, []).append(team)

        return {'users_per_id': users_per_id,
                'use_ldap': use_ldap,
                'ldap_info': user_attr,
                'users_teams': users_teams,
                'previsions': previsions,
                'today': today,
                'end_date': end_date,
                } 
Example #20
Source File: dictset.py    From nefertari with Apache License 2.0 5 votes vote down vote up
def pop_bool_param(self, name, default=False):
        if name in self:
            return asbool(self.pop(name))
        else:
            return default 
Example #21
Source File: core.py    From kotori with GNU Affero General Public License v3.0 5 votes vote down vote up
def get_vendors(self):
        for name, config_object in self.settings.iteritems():
            if 'type' in config_object and config_object.type == 'vendor':
                if 'enable' not in config_object or asbool(config_object['enable']):
                    yield name 
Example #22
Source File: core.py    From kotori with GNU Affero General Public License v3.0 5 votes vote down vote up
def get_applications(self):
        for name, config_object in self.settings.iteritems():
            if 'type' in config_object and config_object.type == 'application':
                if 'enable' not in config_object or asbool(config_object['enable']):
                    yield name 
Example #23
Source File: util.py    From kotori with GNU Affero General Public License v3.0 5 votes vote down vote up
def get_data_uri(bucket, sibling=None, more_params=None):
    """
    Compute uri to data source as sibling to the current path.
    Add "from" and "to" query parameters from bucket.
    """

    more_params = more_params or {}

    forward_parameters = [u'from', u'to', u'exclude', u'include', u'pad', u'backfill', u'interpolate']

    request = bucket.request

    # Honor X-Forwarded-Proto request header if behind SSL-terminating HTTP proxy
    twisted_honor_reverse_proxy(request)

    url = URL()
    for param in forward_parameters:
        if param in bucket.tdata:
            url = url.add(unicode(param), unicode(bucket.tdata[param]))

    for param, value in more_params.iteritems():

        # Special rule: Don't add any of "pad" or "backfill", if "interpolate" is true
        do_interpolate = 'interpolate' in bucket.tdata and asbool(bucket.tdata.interpolate)
        if do_interpolate and param in ['pad', 'backfill']:
            continue

        url = url.add(unicode(param), unicode(value))

    data_uri = str(request.URLPath().sibling(sibling).click(url.asText()))
    return data_uri 
Example #24
Source File: __init__.py    From gamification-engine with MIT License 5 votes vote down vote up
def get_jsmain():
    debug = asbool(get_settings().get("load_from_webpack_dev_server", False))
    if debug:
        return "http://localhost:3000/static/js/bundle.js"
    else:
        modpath = os.path.dirname(sys.modules[__name__].__file__)

        buildpath = os.path.join(modpath, "build")
        with open(os.path.join(buildpath, "asset-manifest.json"), "r") as f:
            manifest = json.load(f)
            return "/admin/jsstatic/"+lstrip_word(manifest["main.js"], "static/")

        return None 
Example #25
Source File: __init__.py    From gamification-engine with MIT License 5 votes vote down vote up
def get_cssmain():
    debug = asbool(get_settings().get("load_from_webpack_dev_server", False))
    if debug:
        return "http://localhost:3000/static/css/bundle.css"
    else:
        modpath = os.path.dirname(sys.modules[__name__].__file__)

        buildpath = os.path.join(modpath, "build")
        with open(os.path.join(buildpath, "asset-manifest.json"), "r") as f:
            manifest = json.load(f)
            return "/admin/jsstatic/"+lstrip_word(manifest["main.css"],"static/")

        return None 
Example #26
Source File: views.py    From gamification-engine with MIT License 5 votes vote down vote up
def delete_subject(request):
    """delete a subject completely"""
    subject_id = int(request.matchdict["subject_id"])

    if asbool(get_settings().get("enable_user_authentication", False)):
        # ensure that the subject exists and we have the permission to update it
        may_delete = request.has_perm(perm_global_delete_subject) or request.has_perm(perm_own_delete_subject) and request.subject.id == subject_id
        if not may_delete:
            raise APIError(403, "forbidden", "You may not delete this subject.")

    Subject.delete_subject(subject_id)
    return {"status": "OK"} 
Example #27
Source File: views.py    From gamification-engine with MIT License 5 votes vote down vote up
def register_device(request):
    try:
        doc = request.json_body
    except:
        raise APIError(400, "invalid_json", "no valid json body")

    subject_id = int(request.matchdict["subject_id"])

    device_id = doc.get("device_id")
    push_id = doc.get("push_id")
    device_os = doc.get("device_os")
    app_version = doc.get("app_version")

    if not device_id \
            or not push_id \
            or not subject_id \
            or not device_os \
            or not app_version:
        raise APIError(400, "register_device.required_fields",
                       "Required fields: device_id, push_id, device_os, app_version")

    if asbool(get_settings().get("enable_user_authentication", False)):
        may_register = request.has_perm(perm_global_register_device) or request.has_perm(
            perm_own_register_device) and str(request.subject.id) == str(subject_id)
        if not may_register:
            raise APIError(403, "forbidden", "You may not register devices for this subject.")

    if not exists_by_expr(t_subjects, t_subjects.c.id==subject_id):
        raise APIError(404, "register_device.subject_not_found",
                       "There is no subject with this id.")

    SubjectDevice.add_or_update_device(subject_id = subject_id, device_id = device_id, push_id = push_id, device_os = device_os, app_version = app_version)

    return {
        "status" : "ok"
    } 
Example #28
Source File: views.py    From gamification-engine with MIT License 5 votes vote down vote up
def get_messages(request):
    try:
        subject_id = int(request.matchdict["subject_id"])
    except:
        subject_id = None

    try:
        offset = int(request.GET.get("offset",0))
    except:
        offset = 0

    limit = 100

    if asbool(get_settings().get("enable_user_authentication", False)):
        may_read_messages = request.has_perm(perm_global_read_messages) or request.has_perm(
            perm_own_read_messages) and str(request.subject.id) == str(subject_id)
        if not may_read_messages:
            raise APIError(403, "forbidden", "You may not read the messages of this subject.")

    if not exists_by_expr(t_subjects, t_subjects.c.id == subject_id):
        raise APIError(404, "get_messages.subject_not_found",
                       "There is no subject with this id.")

    q = t_subject_messages.select().where(t_subject_messages.c.subject_id==subject_id).order_by(t_subject_messages.c.created_at.desc()).limit(limit).offset(offset)
    rows = DBSession.execute(q).fetchall()

    return {
        "messages" : [{
            "id" : message["id"],
            "text" : SubjectMessage.get_text(message),
            "is_read" : message["is_read"],
            "created_at" : message["created_at"]
        } for message in rows]
    } 
Example #29
Source File: views.py    From gamification-engine with MIT License 5 votes vote down vote up
def set_messages_read(request):
    try:
        doc = request.json_body
    except:
        raise APIError(400, "invalid_json", "no valid json body")

    subject_id = int(request.matchdict["subject_id"])

    if asbool(get_settings().get("enable_user_authentication", False)):
        may_read_messages = request.has_perm(perm_global_read_messages) or request.has_perm(
            perm_own_read_messages) and str(request.subject.id) == str(subject_id)
        if not may_read_messages:
            raise APIError(403, "forbidden", "You may not read the messages of this subject.")

    if not exists_by_expr(t_subjects, t_subjects.c.id == subject_id):
        raise APIError(404, "set_messages_read.subject_not_found", "There is no subject with this id.")

    message_id = doc.get("message_id")
    q = select([t_subject_messages.c.id,
        t_subject_messages.c.created_at], from_obj=t_subject_messages).where(and_(t_subject_messages.c.id==message_id,
                                                                       t_subject_messages.c.subject_id==subject_id))
    msg = DBSession.execute(q).fetchone()
    if not msg:
        raise APIError(404, "set_messages_read.message_not_found", "There is no message with this id.")

    uS = update_connection()
    uS.execute(t_subject_messages.update().values({
        "is_read" : True
    }).where(and_(
        t_subject_messages.c.subject_id == subject_id,
        t_subject_messages.c.created_at <= msg["created_at"]
    )))

    return {
        "status" : "ok"
    } 
Example #30
Source File: model.py    From gamification-engine with MIT License 5 votes vote down vote up
def may_increase(cls, variable_row, request, subject_id):
        if not asbool(get_settings().get("enable_user_authentication", False)):
            #Authentication deactivated
            return True
        if request.has_perm(perm_global_increase_value):
            # I'm the global admin
            return True
        if variable_row["increase_permission"] == "own" and request.subject and str(request.subject.id) == str(subject_id):
            #The variable may be updated for myself
            return True
        return False