Created
July 13, 2012 08:33
-
-
Save andyhd/3103669 to your computer and use it in GitHub Desktop.
Python with statement using generator
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@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