Skip to content

Instantly share code, notes, and snippets.

@richmondwang
Created February 21, 2017 08:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save richmondwang/b765ce3b79c0b33ba9d14f54fe685782 to your computer and use it in GitHub Desktop.
Save richmondwang/b765ce3b79c0b33ba9d14f54fe685782 to your computer and use it in GitHub Desktop.
A way to validate keys that start with a given prefix.
# -*- coding: utf-8 -*-
from voluptuous import Marker, Schema
class StartsWith(Marker):
"""
A way to validate keys that start with a given prefix.
Example:
>>> from voluptuous.util import DefaultTo
>>> from voluptuous import REMOVE_EXTRA, Any
>>> test_dict = {
... 'MOD_WSGI_HOST': '0.0.0.0',
... 'MOD_WSGI_PORT': 80,
... 'META': 'Hello World!',
... 'LIMIT_REQUEST_BODY': 50
... }
>>> schema = Schema({
... StartsWith(starts_with='MOD_WSGI_'): Any(str, int)
... }, extra=REMOVE_EXTRA)
>>> schema(test_dict)
{'MOD_WSGI_HOST': '0.0.0.0', 'MOD_WSGI_PORT': 80}
>>> schema = Schema({
... StartsWith(starts_with='MOD_WSGI_'): Any(str, int),
... 'META': str
... }, extra=REMOVE_EXTRA)
>>> schema(test_dict)
{'MOD_WSGI_HOST': '0.0.0.0', 'MOD_WSGI_PORT': 80, 'META': 'Hello World!'}
"""
def __init__(self, starts_with, msg=None):
super().__init__(None, msg=msg)
def starts(v):
if v.startswith(starts_with):
return v
raise ValueError()
self._schema = Schema(starts)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment