Skip to content

Instantly share code, notes, and snippets.

@snopoke
Last active August 29, 2015 14:03
Show Gist options
  • Save snopoke/a51e577ab19e7b083df9 to your computer and use it in GitHub Desktop.
Save snopoke/a51e577ab19e7b083df9 to your computer and use it in GitHub Desktop.
commcare-export demo
import sys
from commcare_export import writers, excel_query
from commcare_export.commcare_hq_client import CommCareHqClient
from commcare_export.commcare_minilinq import CommCareHqEnv
from commcare_export.env import BuiltInEnv, JsonPathEnv
from commcare_export.minilinq import Map, Apply, Reference, Literal, List, MiniLinq, Emit
def query_from_dict():
"""
Use a Python dictionary as the query.
This could also be loaded from JSON
"""
dict_query = {
"Emit": {
"headings": [
{
"Lit": "Received On"
},
{
"Lit": "Gender"
}
],
"source": {
"Map": {
"body": {
"List": [
{
"Ref": "received_on"
},
{
"Ref": "form.gender"
}
]
},
"name": None,
"source": {
"Apply": {
"args": [
{
"Lit": "form"
},
{
"Lit": {
"filter": {
"term": {
"app_id": "whatever"
}
}
}
}
],
"fn": {
"Ref": "api_data"
}
}
}
}
},
"table": "demo-table"
}
}
return MiniLinq.from_jvalue(dict_query)
def query_from_api():
"""
Code the query using the Python API
"""
source = Map(
source=Apply(
Reference("api_data"),
Literal("form"),
Literal({"filter": {"term": {"app_id": "whatever"}}})
),
body=List([
Reference("received_on"),
Reference("form.gender"),
])
)
return Emit(
'demo-table',
[
Literal('Received On'),
Literal('Gender')
],
source
)
def query_from_excel():
"""
Load the query from an Excel file
"""
import openpyxl
workbook = openpyxl.load_workbook('excel-query.xlsx')
return excel_query.compile_workbook(workbook)
api_client = CommCareHqClient(
url="http://www.commcarehq.org",
project='project-space',
version='0.5'
)
api_client = api_client.authenticated(username='username', password='password', mode='digest')
env = BuiltInEnv() | CommCareHqEnv(api_client) | JsonPathEnv({})
query = query_from_dict()
results = query.eval(env)
if len(list(env.emitted_tables())) > 0:
# with writers.Excel2007TableWriter("excel-output.xlsx") as writer:
with writers.StreamingMarkdownTableWriter(sys.stdout) as writer:
for table in env.emitted_tables():
writer.write_table(table)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment