query: Port from JavaScript to Python

Port of query.js to query.py. Fix calls in view.py to this source.