Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
def test_hooks_with_validation(self):
run_hook = []
class RegistrationSchema(Schema):
first_name = validators.String(not_empty=True)
last_name = validators.String(not_empty=True)
email = validators.Email()
username = validators.PlainText()
password = validators.String()
password_confirm = validators.String()
age = validators.Int()
chained_validators = [
validators.FieldsMatch('password', 'password_confirm')
]
class SimpleHook(PecanHook):
def on_route(self, state):
run_hook.append('on_route')
def before(self, state):
run_hook.append('before')
def after(self, state):
run_hook.append('after')
def test_simple_validation(self):
class RegistrationSchema(Schema):
first_name = validators.String(not_empty=True)
last_name = validators.String(not_empty=True)
email = validators.Email()
username = validators.PlainText()
password = validators.String()
password_confirm = validators.String()
age = validators.Int()
chained_validators = [
validators.FieldsMatch('password', 'password_confirm')
]
class RootController(object):
@expose(schema=RegistrationSchema())
def index(self, first_name,
last_name,
email,
username,
password,
password_confirm,
"user_id,logo,uuid_,created,updated,updated_ss,status_,slug) "\
"VALUES (%s,%s,%s,%s,%s,%s,"\
"%s,%s,%s,UTC_TIMESTAMP(),UTC_TIMESTAMP(),UTC_TIMESTAMP(),%s,%s)"
args = (v["sitename"], v["website"], v["desc"], v["usecase"], usecase_md, v["source_url"], \
user_id, v["logo"], uuid.uuid4().hex, status, slug)
self._handler.db.execute(stmt, *args)
except Exception, e:
logging.error(str(e))
self.add_error("sitename", "Submit project error, please try it later.")
class SitePoweredForm(BaseForm):
site_id = validators.Int(not_empty=True)
projects = validators.Set(not_empty=True, use_set=True)
powered_projects = validators.PlainText()
def __after__(self):
try:
values = []
del_values = []
if self._values["powered_projects"] is not None:
powered_projects = self._values["powered_projects"].split("-")
else:
powered_projects = []
for project in self._values["projects"]:
if project not in powered_projects:
values.append((self._values["site_id"], project))
for project in powered_projects:
if project not in self._values["projects"]:
import logging
from formencode import validators
import markdown
from tornado import escape
from poweredsites.forms.base import BaseForm, URL
from poweredsites.libs import const
_domain_prefix_re = re.compile("(http://www\.|http://)")
class ProjectPreForm(BaseForm):
website = URL(not_empty=True, max=600, add_http=True)
class ProjectForm(BaseForm):
subdomain = validators.PlainText(not_empty=True, strip=True)
name = validators.String(not_empty=True, min=3, max=30, strip=True)
category = validators.Int(not_empty=True)
keywords = validators.String(not_empty=False, max=100)
desc = validators.String(not_empty=False, max=600)
website = URL(not_empty=False, max=600, add_http=True)
logo = URL(not_empty=False, max=600, add_http=True)
def __after__(self):
try:
v = self._values
status = const.Status.ACTIVE
length = len(v["subdomain"])
if length < 3 or length > 20:
self.add_error("subdomain", "Name should be more than three and less than twenty charaters.")
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
import re
import urlparse
import formencode
from formencode import htmlfill, validators
class BaseForm(formencode.Schema):
allow_extra_fields = True
filter_extra_fields = True
_xsrf = validators.PlainText(not_empty=True, max=32)
def __init__(self, handler):
self._parmas = {}
self._values = {}
self._form_errors = {}
arguments = {}
# re-parse qs, keep_blank_values for formencode to validate
# so formencode not_empty setting work.
request = handler.request
content_type = request.headers.get("Content-Type", "")
if request.method == "POST":
if content_type.startswith("application/x-www-form-urlencoded"):
arguments = urlparse.parse_qs(request.body, keep_blank_values=1)
Custom validator to check that a given user-name is unique.
"""
def _convert_to_python(self, value, state):
""" Fancy validate for Unique user-name """
if not UserService().is_username_valid(value):
raise formencode.Invalid('Please choose another user-name, this one is already in use!', value, state)
return value
class RegisterForm(formencode.Schema):
"""
Validate Register Form
"""
username = formencode.All(validators.UnicodeString(not_empty=True), validators.PlainText(), UniqueUsername())
password = validators.UnicodeString(not_empty=True)
password2 = validators.UnicodeString(not_empty=True)
email = validators.Email(not_empty=True)
comment = validators.UnicodeString()
role = validators.UnicodeString()
chained_validators = [validators.FieldsMatch('password', 'password2')]
class RecoveryForm(formencode.Schema):
"""
Validate Recover Password Form
"""
email = validators.Email(not_empty=True)
username = validators.String(not_empty=False)
return response
if post_data.get('form.vote_hit'):
idea.vote(voter, True)
elif post_data.get('form.vote_miss'):
idea.vote(voter, False)
session.flush()
return response
class RegistrationSchema(formencode.Schema):
allow_extra_fields = True
username = formencode.validators.PlainText(not_empty=True)
password = formencode.validators.PlainText(not_empty=True)
email = formencode.validators.Email(resolve_domain=False)
name = formencode.validators.String(not_empty=True)
password = formencode.validators.String(not_empty=True)
confirm_password = formencode.validators.String(not_empty=True)
chained_validators = [
formencode.validators.FieldsMatch('password', 'confirm_password')
]
@view_config(permission='view', route_name='register',
renderer='templates/user_add.pt')
def user_add(request):
form = Form(request, schema=RegistrationSchema)
if 'form.submitted' in request.POST and form.validate():
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)
import re
import logging
import urlparse
import formencode
from formencode import htmlfill, validators
class BaseForm(formencode.Schema):
"""
by Felinx Lee
https://bitbucket.org/felinx/poweredsites/src/8448db5ba387/poweredsites/forms/base.py
"""
allow_extra_fields = True
filter_extra_fields = True
_xsrf = validators.PlainText(not_empty=True, max=32)
def __init__(self, handler, form_id = None):
self._parmas = {}
self._values = {}
self._form_errors = {}
self.form_id = form_id
arguments = {}
# re-parse qs, keep_blankvalues for formencode to validate
# so formencode not_empty setting work.
request = handler.request
content_type = request.headers.get("Content-Type", "")
if request.method == "POST":
if content_type.startswith("application/x-www-form-urlencoded"):