Skip to content

Instantly share code, notes, and snippets.

@snowch
Last active December 26, 2016 08:39
Show Gist options
  • Save snowch/eb996c2035f5d4cdfcbe to your computer and use it in GitHub Desktop.
Save snowch/eb996c2035f5d4cdfcbe to your computer and use it in GitHub Desktop.
Cloudant Python connection pooling and cookie renewal (Gunicorn)
# WARNING: THIS CODE HAS NOT BEEN TESTED!
from apscheduler.scheduler import Scheduler
from requests.adapters import HTTPAdapter
import cloudant
import logging
import json
import os
# setup connection pooling - see http://stackoverflow.com/questions/29046503/cloudant-python-https-connection-pooling
httpAdapter = HTTPAdapter(pool_connections=10, pool_maxsize=100)
account = cloudant.Account('education', async=False)
account._session.adapters['https://'] = httpAdapter
account.login(os.environ['cl_username'], os.environ['cl_password'])
# schedule job to renew cookie
def renew_session_cookie():
# TODO: is this threadsafe?
account.login(os.environ['cl_username'], os.environ['cl_password'])
apsched = Scheduler()
apsched.start()
apsched.add_interval_job(renew_session_cookie, hours=1)
# Gunicorn Rest handler method ...
def app(environ, start_response):
db = account.database('foundbite')
db_response = db.get( '_all_docs' )
data = str.encode(json.dumps(db_response.json()))
status = str(db_response.status_code)
response_headers = [
('Content-type', 'application/json'),
('Content-Length', str(len(data))),
]
start_response(status, response_headers)
return iter([data])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment