本文整理汇总了Python中colanderalchemy.SQLAlchemySchemaNode类的典型用法代码示例。如果您正苦于以下问题:Python SQLAlchemySchemaNode类的具体用法?Python SQLAlchemySchemaNode怎么用?Python SQLAlchemySchemaNode使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了SQLAlchemySchemaNode类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: _prep_schema
def _prep_schema(self):
overrides = {
'person': {
'includes': ['name', 'surname', 'gender', 'addresses'],
'overrides': {
'addresses': {
'includes': ['street', 'city'],
'overrides': {
'city': {
'exclude': False
}
}
}
}
},
}
includes = ['email', 'enabled', 'created', 'timeout', 'person']
schema = SQLAlchemySchemaNode(Account, includes=includes,
overrides=overrides)
# Add a non-SQLAlchemy field
schema.add(colander.SchemaNode(
colander.String(),
name='non_sql',
missing=colander.drop
))
return schema
示例2: statistic_sheet_add_edit_view
def statistic_sheet_add_edit_view(context, request):
"""
View for adding editing statistics sheets
"""
logger.info("Here we are")
logger.info(request.POST)
if 'title' in request.POST:
schema = SQLAlchemySchemaNode(StatisticSheet, includes=('title',))
try:
appstruct = schema.deserialize(request.POST)
except colander.Invalid:
logger.exception(u"Erreur à la création de la feuille de \
statistiques")
else:
if context.__name__ == 'statistic_sheet':
sheet = schema.objectify(appstruct, context)
sheet = request.dbsession.merge(sheet)
else:
sheet = schema.objectify(appstruct)
request.dbsession.add(sheet)
request.dbsession.flush()
url = request.route_path('statistic', id=sheet.id)
return HTTPFound(url)
logger.debug(u"Invalid datas have been passed")
raise HTTPClientError()
logger.debug(u"Missing datas in the request")
raise HTTPClientError()
示例3: test_dictify_with_null
def test_dictify_with_null(self):
""" Test SQLAlchemySchemaNode.dictify(obj) with null values
and show that result is a valid appstruct for the given schema
"""
Base = declarative_base()
class Sensor(Base):
__tablename__ = 'sensor'
sensor_id = Column(Integer, primary_key=True)
institution_id = Column(Integer, nullable=True)
sensor_label = Column(String, nullable=True)
sensor = Sensor(
sensor_id=3,
institution_id=None,
sensor_label=None,
)
schema = SQLAlchemySchemaNode(Sensor)
appstruct = schema.dictify(sensor)
cstruct = schema.serialize(appstruct=appstruct)
newappstruct = schema.deserialize(cstruct)
newobj = schema.objectify(appstruct)
self.assertEqual(appstruct, newappstruct)
self.assertEqual(sensor.sensor_id, newobj.sensor_id)
self.assertEqual(sensor.institution_id, newobj.institution_id)
self.assertEqual(sensor.sensor_label, newobj.sensor_label)
示例4: get_project_schema
def get_project_schema():
"""
Return the project Edition/add form schema
"""
schema = SQLAlchemySchemaNode(Project, excludes=('_acl',))
schema['name'].missing = colander.required
# Add a custom node to be able to associate existing customers
customer_id_node = colander.SchemaNode(
colander.Integer(),
widget=deferred_customer_select,
validator=deferred_customer_validator,
default=deferred_default_customer,
name='un client'
)
customer_id_node.objectify = customer_objectify
customer_id_node.dictify = customer_dictify
schema.insert(3,
colander.SchemaNode(
colander.Sequence(),
customer_id_node,
widget=deform.widget.SequenceWidget(min_len=1),
title=u"Clients",
name='customers')
)
return schema
示例5: test_null_issues
def test_null_issues(self):
""" Make sure nullable values are set properly when null
#42 introduced an issue where values may not have been properly
set if the value is supposed to be set to null
"""
Base = declarative_base()
class Person(Base):
__tablename__ = 'person'
id = Column(Integer, primary_key=True)
fullname = Column(String, nullable=True)
age = Column(Integer, nullable=True)
schema = SQLAlchemySchemaNode(Person)
person = Person(
id=7,
fullname="Joe Smith",
age=35,
)
# dict coming from a form submission
update_cstruct = {
'id': '7',
'fullname': '',
'age': '',
}
update_appstruct = schema.deserialize(update_cstruct)
schema.objectify(update_appstruct, context=person)
self.assertEqual(person.id, 7)
self.assertEqual(person.fullname, None)
self.assertEqual(person.age, None)
示例6: get_add_edit_schema
def get_add_edit_schema(edit=False):
"""
Return a user add schema
"""
schema = SQLAlchemySchemaNode(
User,
includes=(
'civilite',
'firstname',
'lastname',
'email',
),
)
if not edit:
schema.add(
colander.SchemaNode(
colander.Boolean(),
name='add_login',
title=u"Créer des identifiants pour ce compte ?",
description=u"Les identifiants permettront au titulaire de ce "
u"compte de se connecter",
)
)
set_widgets(schema)
return schema
示例7: get_password_schema
def get_password_schema():
"""
Return the schema for user password change
:returns: a colander Schema
"""
schema = SQLAlchemySchemaNode(
Login,
includes=('pwd_hash',),
title=u'',
)
set_widgets(schema)
schema.insert(
0,
colander.SchemaNode(
colander.String(),
widget=deform.widget.PasswordWidget(),
name='password',
title=u'Mot de passe actuel',
default=u'',
)
)
schema['pwd_hash'].title = u"Nouveau mot de passe"
schema.validator = deferred_password_validator
schema.after_bind = remove_actual_password_my_account
return schema
示例8: get_doctypes_schema
def get_doctypes_schema(userdatas_model):
"""
Build a form schema for doctypes registration
:param obj userdatas_model: An instance of userdatas we're building
the form for
"""
registered = userdatas_model.doctypes_registrations
node_schema = SQLAlchemySchemaNode(UserDatasSocialDocTypes)
node_schema.widget = deform.widget.MappingWidget(
template="clean_mapping.pt"
)
node_schema['status'].widget = deform.widget.CheckboxWidget()
form_schema = colander.Schema()
for index, entry in enumerate(registered):
node = node_schema.clone()
name = 'node_%s' % index
node.name = name
node.title = u''
node['status'].title = u''
node['status'].label = entry.doctype.label
form_schema.add(node)
return form_schema
示例9: test_default_clause
def test_default_clause(self):
"""Test proper handling of default and server_default values
"""
Base = declarative_base()
def give_me_three():
return 3
class Patient(Base):
__tablename__ = 'patient'
# default= is equivalent to ColumnDefault()
# server_default= is equivalent to DefaultClause()
id = Column(BigInteger(unsigned=True), default=text("uuid_short()"), primary_key=True, autoincrement=False)
received_timestamp = Column(TIMESTAMP, server_default=func.now(), nullable=False)
some_number = Column(Integer, DefaultClause('3'), nullable=False)
scalar_number = Column(Integer, default=3, nullable=False)
pyfunc_test = Column(Integer, default=give_me_three, nullable=False)
schema = SQLAlchemySchemaNode(Patient)
'''
Conceivably you should be able to test DefaultClause for a
scalar type value and use it as a default/missing in Colander.
However, the value is interpreted by the backend engine and
could be a interpreted by it in an unexpected way. For this
reason we drop the value and let the backend handle it.
'''
# from <FORM> result into SQLA; tests missing
self.assertEqual(schema['id'].missing, colander.drop)
self.assertEqual(schema['received_timestamp'].missing, colander.drop)
self.assertEqual(schema['some_number'].missing, colander.drop)
self.assertEqual(schema['scalar_number'].missing, 3)
self.assertEqual(schema['pyfunc_test'].missing, 3)
deserialized = schema.deserialize({})
self.assertIn('scalar_number', deserialized)
self.assertEqual(deserialized['scalar_number'], 3)
self.assertIn('pyfunc_test', deserialized)
self.assertEqual(deserialized['pyfunc_test'], 3)
# from SQLA result into <FORM>; tests default
self.assertEqual(schema['id'].default, colander.null)
self.assertEqual(schema['received_timestamp'].default, colander.null)
self.assertEqual(schema['some_number'].default, colander.null)
self.assertEqual(schema['scalar_number'].default, 3)
self.assertEqual(schema['pyfunc_test'].default, 3)
serialized = schema.serialize({})
self.assertIn('id', serialized)
self.assertEqual(serialized['id'], colander.null)
self.assertIn('received_timestamp', serialized)
self.assertEqual(serialized['received_timestamp'], colander.null)
self.assertIn('some_number', serialized)
self.assertEqual(serialized['some_number'], colander.null)
self.assertIn('scalar_number', serialized)
self.assertEqual(serialized['scalar_number'], str(3))
self.assertIn('pyfunc_test', serialized)
self.assertEqual(serialized['pyfunc_test'], str(3))
示例10: test_clone
def test_clone(self):
schema = SQLAlchemySchemaNode(Account, dummy='dummy', dummy2='dummy2')
cloned = schema.clone()
for attr in ['class_', 'includes', 'excludes', 'overrides']:
self.assertEqual(getattr(schema, attr), getattr(cloned, attr))
self.assertEqual(cloned.kwargs, schema.kwargs)
self.assertEqual([node.name for node in schema.children],
[node.name for node in cloned.children])
示例11: get_company_customer_schema
def get_company_customer_schema():
"""
return the schema for user add/edit regarding the current user's role
"""
schema = SQLAlchemySchemaNode(Customer)
schema = _customize_schema(schema)
schema['name'].missing = colander.required
schema.after_bind = _customer_after_bind
return schema
示例12: test_missing_mapping_configuration
def test_missing_mapping_configuration(self):
""" Test to check ``missing`` is set to an SQLAlchemy-suitable value.
"""
schema = SQLAlchemySchemaNode(Account)
self.assertEqual(schema['person_id'].missing, colander.null)
self.assertEqual(schema['person'].missing, [])
deserialized = schema.deserialize({'email': '[email protected]',
'timeout': '09:44:33'})
self.assertEqual(deserialized['person_id'], colander.null)
self.assertEqual(deserialized['person'], [])
示例13: __init__
def __init__(self, class_, includes=None,
excludes=None, overrides=None, unknown='raise'):
self.comparators = {}
self.order_by_values = []
SQLAlchemySchemaNode.__init__(self,
class_,
includes,
excludes,
overrides,
unknown)
示例14: get_individual_customer_schema
def get_individual_customer_schema():
"""
return the schema for user add/edit regarding the current user's role
"""
excludes = ('name', 'tva_intracomm', 'function', 'registration')
schema = SQLAlchemySchemaNode(Customer, excludes=excludes)
schema = _customize_schema(schema)
schema['firstname'].title = u"Prénom"
schema['lastname'].title = u'Nom'
schema['civilite'].missing = colander.required
schema['lastname'].missing = colander.required
schema.after_bind = _customer_after_bind
return schema
示例15: get_sequence_model_admin
def get_sequence_model_admin(model, title=u"", excludes=(), **kw):
"""
Return a schema for configuring sequence of models
model
The SQLAlchemy model to configure
"""
node_schema = SQLAlchemySchemaNode(
model,
widget=CleanMappingWidget(),
excludes=excludes,
)
node_schema.name = 'data'
colanderalchemy_config = getattr(model, '__colanderalchemy_config__', {})
default_widget_options = dict(
orderable=True,
min_len=1,
)
widget_options = colanderalchemy_config.get('seq_widget_options', {})
widget_options.update(kw.get('widget_options', {}))
for key, value in widget_options.items():
default_widget_options[key] = value
schema = colander.SchemaNode(colander.Mapping())
schema.add(
colander.SchemaNode(
colander.Sequence(),
node_schema,
widget=CleanSequenceWidget(
**default_widget_options
),
title=title,
name='datas')
)
def dictify(models):
return {'datas': [node_schema.dictify(model) for model in models]}
def objectify(datas):
return [node_schema.objectify(data) for data in datas]
schema.dictify = dictify
schema.objectify = objectify
return schema