本文整理汇总了Python中corehq.apps.app_manager.xform.XForm类的典型用法代码示例。如果您正苦于以下问题:Python XForm类的具体用法?Python XForm怎么用?Python XForm使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了XForm类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: set_xmlns_on_form
def set_xmlns_on_form(form_id, xmlns, app_build, log_file, dry_run):
"""
Set the xmlns on a form and all the corresponding forms in the saved builds
that are copies of app.
(form is an app_manager.models.Form)
"""
try:
form_in_build = app_build.get_form(form_id)
except FormNotFoundException:
return
if form_in_build.xmlns == "undefined" or form_in_build.source.count('xmlns="undefined"') > 0:
if form_in_build.xmlns != "undefined":
assert form_in_build.xmlns == xmlns
xml = form_in_build.source
wrapped_xml = XForm(xml)
data = wrapped_xml.data_node.render().decode('utf-8')
data = data.replace("undefined", xmlns, 1)
wrapped_xml.instance_node.remove(wrapped_xml.data_node.xml)
wrapped_xml.instance_node.append(parse_xml(data))
new_xml = wrapped_xml.render().decode('utf-8')
form_in_build.source = new_xml
form_in_build.form_migrated_from_undefined_xmlns = datetime.utcnow()
log_file.write(
"New xmlns for form {form_id} in app {app_build._id} is {new_xmlns}\n".format(
form_id=form_id,
app_build=app_build,
new_xmlns=xmlns
))
if not dry_run:
app_build.save() # Magic happens on save
示例2: fix_user_props_copy
def fix_user_props_copy(app, module, form, form_ix, preloads, dry):
updated = False
xform = XForm(form.source)
refs = {xform.resolve_path(ref): prop for ref, prop in six.iteritems(preloads)}
for node in xform.model_node.findall("{f}setvalue"):
if (node.attrib.get('ref') in refs
and node.attrib.get('event') == "xforms-ready"):
ref = node.attrib.get('ref')
value = (node.attrib.get('value') or "").replace(" ", "")
prop = refs[ref]
userprop = "#user/" + prop
if value == get_bad_usercase_path(module, form, prop):
logger.info("%s setvalue %s -> %s", form_ix, userprop, ref)
node.attrib["value"] = USERPROP_PREFIX + prop
updated = True
elif value != USERPROP_PREFIX + prop:
logger.warn("%s %s has unexpected value: %r (not %s)",
form_ix, ref, value, userprop)
if updated:
if dry:
logger.info("updated setvalues in XML:\n%s", "\n".join(line
for line in ET.tostring(xform.xml).split("\n")
if "setvalue" in line))
else:
save_xform(app, form, ET.tostring(xform.xml))
return updated
示例3: get_form_data_source
def get_form_data_source(app, form):
xform = XForm(form.source)
form_name = form.default_name()
questions = xform.get_questions([])
return DataSourceConfiguration(
domain=app.domain,
referenced_doc_type="XFormInstance",
table_id=_clean_table_name(app.domain, form_name),
display_name=form_name,
configured_filter=make_form_data_source_filter(xform.data_node.tag_xmlns),
configured_indicators=[
make_form_question_indicator(q, column_id=get_column_name(q["value"])) for q in questions
]
+ [make_form_meta_block_indicator(field) for field in FORM_METADATA_PROPERTIES],
)
示例4: test_action_relevance
def test_action_relevance(self):
xform = XForm("")
def condition_case(expected, type=None, question=None, answer=None, operator=None):
condition = FormActionCondition(type=type, question=question, answer=answer, operator=operator)
return condition, expected
cases = [
(condition_case("true()", "always")),
(condition_case("false()", "never")),
(condition_case("/data/question1 = 'yes'", "if", "/data/question1", "yes")),
(condition_case("selected(/data/question1, 'yes')", "if", "/data/question1", "yes", "selected")),
]
for case in cases:
actual = xform.action_relevance(case[0])
self.assertEqual(actual, case[1])
示例5: migrate_app
def migrate_app(self, app_id):
app = Application.get(app_id)
modules = [m for m in app.modules if m.module_type == 'basic']
for module in modules:
forms = [f for f in module.forms if f.doc_type == 'Form']
for form in forms:
preload = form.actions.case_preload.preload
if preload:
xform = XForm(form.source)
xform.add_case_preloads(preload)
save_xform(app, form, ET.tostring(xform.xml))
form.actions.load_from_form = form.actions.case_preload
form.actions.case_preload = PreloadAction()
app.vellum_case_management = True
app.save()
示例6: get_questions
def get_questions(form):
xform = XForm(form.source)
prefix = '/%s/' % xform.data_node.tag_name
def remove_prefix(string):
if string.startswith(prefix):
return string[len(prefix):]
else:
raise Exception()
def transform_question(q):
return {
'id': remove_prefix(q['value']),
'type': q['tag'],
'text': q['label'] if q['tag'] != 'hidden' else ''
}
return [transform_question(q) for q in xform.get_questions(langs)]
示例7: migrate_preloads
def migrate_preloads(app, form, preload_items, form_ix, dry):
xform = XForm(form.source)
if form.case_references:
load_refs = form.case_references.load
else:
load_refs = {}
form.case_references = CaseReferences(load=load_refs)
for hashtag, preloads in preload_items:
if hashtag == "#case/":
xform.add_case_preloads(preloads)
elif hashtag == "#user/":
xform.add_casedb()
for nodeset, prop in preloads.items():
assert '/' not in prop, (app.id, form.unique_id, prop)
xform.add_setvalue(ref=nodeset, value=USERPROP_PREFIX + prop)
else:
raise ValueError("unknown hashtag: " + hashtag)
for nodeset, prop in six.iteritems(preloads):
load_refs.setdefault(nodeset, []).append(hashtag + prop)
logger.info("%s/%s %s setvalue %s = %s",
app.domain, app._id, form_ix, nodeset, hashtag + prop)
if dry:
logger.info("setvalue XML: %s", " ".join(line.strip()
for line in ET.tostring(xform.xml).split("\n")
if "setvalue" in line))
else:
save_xform(app, form, ET.tostring(xform.xml))
示例8: get_questions
def get_questions(form):
xform = XForm(form.source)
prefix = "/%s/" % xform.data_node.tag_name
def remove_prefix(string):
if string.startswith(prefix):
return string[len(prefix) :]
else:
raise Exception()
def transform_question(q):
return {
"id": remove_prefix(q["value"]),
"type": q["tag"],
"text": q["label"] if q["tag"] != "hidden" else "",
}
return [transform_question(q) for q in xform.get_questions(langs)]
示例9: save_xform
def save_xform(app, form, xml):
try:
xform = XForm(xml)
except XFormError:
pass
else:
duplicates = app.get_xmlns_map()[xform.data_node.tag_xmlns]
for duplicate in duplicates:
if form == duplicate:
continue
else:
data = xform.data_node.render()
xmlns = "http://openrosa.org/formdesigner/%s" % form.get_unique_id()
data = data.replace(xform.data_node.tag_xmlns, xmlns, 1)
xform.instance_node.remove(xform.data_node.xml)
xform.instance_node.append(parse_xml(data))
xml = xform.render()
break
form.source = xml
示例10: multimedia_list_download
def multimedia_list_download(request, domain, app_id):
app = get_app(domain, app_id)
include_audio = request.GET.get("audio", True)
include_images = request.GET.get("images", True)
strip_jr = request.GET.get("strip_jr", True)
filelist = []
for m in app.get_modules():
for f in m.get_forms():
parsed = XForm(f.source)
parsed.validate(version=app.application_version)
if include_images:
filelist.extend(parsed.image_references)
if include_audio:
filelist.extend(parsed.audio_references)
if strip_jr:
filelist = [s.replace("jr://file/", "") for s in filelist if s]
response = HttpResponse()
set_file_download(response, 'list.txt')
response.write("\n".join(sorted(set(filelist))))
return response
示例11: test_action_relevance
def test_action_relevance(self):
xform = XForm('')
def condition_case(expected, type=None, question=None, answer=None, operator=None):
condition = FormActionCondition(
type=type,
question=question,
answer=answer,
operator=operator
)
return condition, expected
cases = [
(condition_case('true()', 'always')),
(condition_case('false()', 'never')),
(condition_case("/data/question1 = 'yes'", 'if', '/data/question1', 'yes')),
(condition_case("selected(/data/question1, 'yes')", 'if', '/data/question1', 'yes', 'selected')),
]
for case in cases:
actual = xform.action_relevance(case[0])
self.assertEqual(actual, case[1])
示例12: fix_user_props_caseref
def fix_user_props_caseref(app, module, form, form_ix, dry):
updated = False
xform = XForm(form.source)
refs = {xform.resolve_path(ref): vals
for ref, vals in six.iteritems(form.case_references.load)
if any(v.startswith("#user/") for v in vals)}
ref_warnings = []
for node in xform.model_node.findall("{f}setvalue"):
if (node.attrib.get('ref') in refs
and node.attrib.get('event') == "xforms-ready"):
ref = node.attrib.get('ref')
ref_values = refs[ref]
if len(ref_values) != 1:
ref_warnings.append((ref, " ".join(ref_values)))
continue
value = (node.attrib.get('value') or "").replace(" ", "")
userprop = ref_values[0]
assert userprop.startswith("#user/"), (ref, userprop)
prop = userprop[len("#user/"):]
if value == get_bad_usercase_path(module, form, prop):
logger.info("%s setvalue %s -> %s", form_ix, userprop, ref)
node.attrib["value"] = USERPROP_PREFIX + prop
updated = True
elif value != (USERPROP_PREFIX + prop).replace(" ", ""):
ref_warnings.append((ref, "%r (%s)" % (value, userprop)))
if updated:
if dry:
logger.info("updated setvalues in XML:\n%s", "\n".join(line
for line in ET.tostring(xform.xml).split("\n")
if "setvalue" in line))
else:
save_xform(app, form, ET.tostring(xform.xml))
if ref_warnings:
for ref, ref_values in ref_warnings:
logger.warning("%s %s has unexpected #user refs: %s",
form_ix, ref, ref_values)
return updated
示例13: __init__
def __init__(self, domain, app, source_type, source_id):
assert (source_type in ['case', 'form'])
self.domain = domain
self.app = app
self.source_type = source_type
# source_id is a case type of form id
self.source_id = source_id
if self.source_type == 'form':
self.source_form = Form.get_form(self.source_id)
self.source_xform = XForm(self.source_form.source)
if self.source_type == 'case':
prop_map = get_case_properties(
self.app, [self.source_id], defaults=DEFAULT_CASE_PROPERTY_DATATYPES.keys()
)
self.case_properties = sorted(set(prop_map[self.source_id]) | {'closed'})
示例14: __init__
def __init__(self, domain, app, source_type, source_id):
assert (source_type in ['case', 'form'])
self.domain = domain
self.app = app
self.source_type = source_type
# source_id is a case type of form id
self.source_id = source_id
if self.source_type == 'form':
self.source_form = Form.get_form(self.source_id)
self.source_xform = XForm(self.source_form.source)
if self.source_type == 'case':
property_builder = ParentCasePropertyBuilder(
self.app, DEFAULT_CASE_PROPERTY_DATATYPES.keys()
)
self.case_properties = list(
property_builder.get_properties(self.source_id) | {'closed'}
)
示例15: DataSourceBuilder
class DataSourceBuilder(object):
"""
When configuring a report, one can use DataSourceBuilder to determine some
of the properties of the required report data source, such as:
- referenced doc type
- filter
- indicators
"""
def __init__(self, domain, app, source_type, source_id):
assert (source_type in ['case', 'form'])
self.domain = domain
self.app = app
self.source_type = source_type
# source_id is a case type of form id
self.source_id = source_id
if self.source_type == 'form':
self.source_form = Form.get_form(self.source_id)
self.source_xform = XForm(self.source_form.source)
if self.source_type == 'case':
property_builder = ParentCasePropertyBuilder(
self.app, DEFAULT_CASE_PROPERTY_DATATYPES.keys()
)
self.case_properties = list(
property_builder.get_properties(self.source_id) | {'closed'}
)
@property
@memoized
def source_doc_type(self):
if self.source_type == "case":
return "CommCareCase"
if self.source_type == "form":
return "XFormInstance"
@property
@memoized
def filter(self):
"""
Return the filter configuration for the DataSourceConfiguration.
"""
if self.source_type == "case":
return make_case_data_source_filter(self.source_id)
if self.source_type == "form":
return make_form_data_source_filter(self.source_xform.data_node.tag_xmlns)
@property
@memoized
def indicators(self):
"""
Return all the dict data source indicator configurations that could be
used by a report that uses the same case type/form as this DataSourceConfiguration.
"""
ret = []
for prop in self.data_source_properties.values():
if prop['type'] == 'meta':
ret.append(make_form_meta_block_indicator(
prop['source'], prop['column_id']
))
elif prop['type'] == "question":
ret.append(make_form_question_indicator(
prop['source'], prop['column_id']
))
elif prop['type'] == 'case_property':
ret.append(make_case_property_indicator(
prop['source'], prop['column_id']
))
ret.append({
"display_name": "Count",
"type": "count",
"column_id": "count"
})
return ret
@property
@memoized
def data_source_properties(self):
"""
A dictionary containing the various properties that may be used as indicators
or columns in the data source or report.
Keys are strings that uniquely identify properties.
Values are dicts representing the properties, ex:
>> self.data_source_properties
{
"/data/question1": {
"type": "question",
"id": "/data/question1",
"text": "Enter the child's name",
"column_id": "data--question1",
"source": {
'repeat': None,
'group': None,
'value': '/data/question1',
'label': 'question1',
'tag': 'input',
'type': 'Text'
}
#.........这里部分代码省略.........