Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
def _schema(d=None, **kw):
dd = {}
if d:
dd.update(d)
dd.update(**kw)
return formencode.Schema.__metaclass__('schema', (formencode.Schema,), dd)
# -*- coding: utf-8 -*-
import logging
from formencode import Schema, validators
from pyramid.i18n import TranslationStringFactory
_ = TranslationStringFactory('pylonshq')
log = logging.getLogger(__name__)
class LoginForm(Schema):
allow_extra_fields = True
filter_extra_fields = True
username = validators.UnicodeString(
not_empty=True,
messages={
'empty':_('Please enter your username.')
}
)
password = validators.UnicodeString(
not_empty=True,
messages={
'empty':_('Please enter your password.')
}
def _sav_create_fe_schema(cls, fev_metas, for_event, for_conversion):
schema = formencode.Schema(allow_extra_fields=True)
field_validators = defaultdict(list)
for fevm in fev_metas:
if fevm.event == for_event and fevm.is_converter == for_conversion:
field_validators[fevm.field_name].append(fevm.fev)
for fieldname, validators in six.iteritems(field_validators):
schema.add_field(fieldname, formencode.compound.All(*validators))
return schema
from flask import Flask, session, redirect, url_for, request, render_template, jsonify
import core
import couch
import formencode
import gearman
class TemplateForm(formencode.Schema):
"""
Formencode Form validators for Email Template add/edit
"""
allow_extra_fields = True
filter_exter_fields = True
pre_validators = [formencode.variabledecode.NestedVariables()]
_id = formencode.validators.String(not_empty=True, if_missing=None)
name = formencode.validators.String(not_empty=True)
class contents(formencode.Schema):
lang = formencode.validators.String(not_empty=False)
subject = formencode.validators.String(not_empty=False)
body = formencode.validators.String(not_empty=False)
contents = formencode.ForEach(contents)
app = Flask(__name__)
allow_extra_fields = True
class AuthMethodsValidator(Schema):
"""Auth methods validator"""
method = validators.String()
set = validators.Bool(if_empty=None)
active = validators.Bool(if_empty=None)
allowed = validators.Bool(if_empty=None)
supported = validators.Bool(if_empty=None)
user_required = validators.Bool(if_empty=None)
passed = validators.Bool(if_empty=None)
error = validators.Bool(if_empty=None)
class GeoFenceValidator(Schema):
""" GeoFence Validator, can represent both GeoFence and GeoCircleFence """
name = validators.String(if_missing=None)
latitude = validators.Number()
longitude = validators.Number()
radius = validators.Number()
class GeoCircleFenceValidator(GeoFenceValidator):
""" GeoFence Validator, can represent ONLY GeoCircleFence """
type = validators.OneOf(["GEO_CIRCLE"])
class TerritoryFenceValidator(Schema):
""" TerritoryFence Validator"""
name = validators.String(if_missing=None)
type = validators.OneOf(["TERRITORY"], if_missing=None)
self.as_string = as_string
def _to_python(self, value, state):
value = super(self.__class__, self)._to_python(value, state)
try:
for k, v in value.iteritems():
if not(isinstance(k, basestring) and isinstance(v, basestring)):
raise
return json.dumps(value) if self.as_string else value
except:
raise fe.Invalid(
'User map file must contain mapping of {str:str, ...}',
value, state)
class CreateTaskSchema(fe.Schema):
task = TaskValidator(not_empty=True, strip=True)
task_args = JsonConverter(if_missing=dict(args=[], kwargs={}))
user = UserValidator(strip=True, if_missing=None)
path = PathValidator(strip=True, if_missing={}, if_empty={})
class CreateSiteNotificationSchema(fe.Schema):
active = fev.StringBool(if_missing=False)
impressions = fev.Int(not_empty=True)
content = fev.UnicodeString(not_empty=True)
user_role = fev.FancyValidator(not_empty=False, if_empty=None)
page_regex = fev.FancyValidator(not_empty=False, if_empty=None)
page_tool_type = fev.FancyValidator(not_empty=False, if_empty=None)
class DateValidator(fev.FancyValidator):
try:
new_params[field] = validator.to_python(params.get(field),
self.state)
# catch individual validation errors into the errors dictionary
except formencode.api.Invalid, inv:
errors[field] = inv
# If there are errors, create a compound validation error based on
# the errors dictionary, and raise it as an exception
if errors:
raise formencode.api.Invalid(
formencode.schema.format_compound_error(errors),
params, None, error_dict=errors)
return new_params
elif isinstance(self.validators, formencode.Schema):
# A FormEncode Schema object - to_python converts the incoming
# parameters to sanitized Python values
return self.validators.to_python(params, self.state)
elif isinstance(self.validators, tw.forms.InputWidget) \
or hasattr(self.validators, 'validate'):
# A tw.forms.InputWidget object. validate converts the incoming
# parameters to sanitized Python values
# - OR -
# An object with a "validate" method - call it with the parameters
# This is a generic case for classes mimicking tw.forms.InputWidget
return self.validators.validate(params, self.state)
# No validation was done. Just return the original params.
return params
from databin.core import db
from databin.util import make_key
from databin.parsers import get_parsers
class ValidFormat(FancyValidator):
def _to_python(self, value, state):
for key, name in get_parsers():
if value == key:
return value
raise Invalid('Not a valid format', value, None)
class PasteSchema(Schema):
description = validators.String(min=0, max=255)
format = ValidFormat()
force_header = validators.StringBool(empty=False)
data = validators.String(min=10, max=255000)
class Paste(db.Model):
__tablename__ = 'paste'
id = db.Column(db.Integer, primary_key=True)
key = db.Column(db.Unicode())
source_ip = db.Column(db.Unicode())
description = db.Column(db.Unicode())
format = db.Column(db.Unicode())
data = db.Column(db.Unicode())
force_header = db.Column(db.Boolean())
nodes.append(node)
return nodes
def fill_default_attributes(self, template_dictionary, subsection='project'):
"""
Overwrite base controller to add required parameters for adapter templates.
"""
template_dictionary[common.KEY_SECTION] = 'project'
template_dictionary[common.KEY_SUB_SECTION] = subsection
template_dictionary[common.KEY_INCLUDE_RESOURCES] = 'project/included_resources'
BaseController.fill_default_attributes(self, template_dictionary)
return template_dictionary
class EditForm(formencode.Schema):
"""
Validate creation of a Project entity.
"""
invalis_name_msg = "Please enter a name composed only of letters, numbers and underscores."
name = formencode.All(validators.UnicodeString(not_empty=True),
validators.PlainText(messages={'invalid': invalis_name_msg}))
description = validators.UnicodeString()
users = formencode.foreach.ForEach(formencode.validators.Int())
administrator = validators.UnicodeString(not_empty=False)
project_id = validators.UnicodeString(not_empty=False)
visited_pages = validators.UnicodeString(not_empty=False)
from formencode import Schema, validators, ForEach
from ..utils.validation import ValidateISODate
class PublicKeyValidator(Schema):
"""Public Key entity Validator"""
id = validators.String()
active = validators.Bool()
date_created = ValidateISODate()
date_expires = ValidateISODate()
public_key = validators.String()
allow_extra_fields = True
class DirectoryUserDeviceLinkResponseValidator(Schema):
"""Directory User Device link response validator"""
qrcode = validators.String() # URL
code = validators.String(min=7)
device_id = validators.String()
allow_extra_fields = True
class DirectoryGetDeviceResponseValidator(Schema):
"""Directory get Device response validator"""
id = validators.String()
name = validators.String()
status = validators.Int()
type = validators.String()
allow_extra_fields = True