Skip to content

Instantly share code, notes, and snippets.

@andyhd
Created July 13, 2012 08:33
Show Gist options
  • Save andyhd/3103669 to your computer and use it in GitHub Desktop.
Save andyhd/3103669 to your computer and use it in GitHub Desktop.
Python with statement using generator
@contextlib.contextmanager
def google_search_results(terms, page=1, custom_search_id=''):
params = {
'q': terms,
'cx': custom_search_id or app.config.get('GOOGLE_CUSTOM_SEARCH_ID', ''),
'start': ((page - 1) * 10) + 1,
'num': 10
}
yield custom_search_service.list(**params).execute()
@app.route('/search/')
def results():
page = int(request.args.get('page', '1'))
terms = request.args.get('terms', '')
with google_search_results(terms, page=page) as results:
total = int(results['searchInformation']['totalResults'])
params = {
'num_pages': int(ceil(total / 10)),
'terms': terms,
'page': page,
'results': results
}
return render_template('results.jinja', **params)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment