os / slacker

Full-featured Python interface for the Slack API
Apache License 2.0
1.6k stars 245 forks source link

Support connection pooling via requests.Session #111

Closed frostbtn closed 7 years ago

frostbtn commented 7 years ago

This addresses #100.

Slacker() now optionally receives requests.Session object to run requests through. If not provided it uses requests.get or requests.post as before (these create a separate session for each api call resulting in https handshake every time).

Implementation is straightforward. requests.get/requests.post are effectively inlined to utilize user provided session object.

I'm getting 30% off from mean time to request Slack (a chat archiving crawler) and like 60% off from traffic volume (https overhead).

alexwlchan commented 7 years ago

One nice side effect of this change is that it becomes easier to test code that uses slacker, because you can use something like betamax to cache API calls. I now have a nice little pytest fixture for creating a cached Slacker instance:

# -*- encoding: utf-8 -*-

import os

import betamax
import pytest
import requests
import slacker

SLACK_TOKEN = os.environ.get('SLACK_TOKEN', 'TEST_TOKEN')

with betamax.Betamax.configure() as config:
    config.cassette_library_dir = 'tests/cassettes'
    config.define_cassette_placeholder('<SLACK_TOKEN>', SLACK_TOKEN)

@pytest.fixture
def slack():
    session = requests.Session()
    with betamax.Betamax(session).use_cassette('slack'):
        yield slacker.Slacker(
            token=SLACK_TOKEN,
            session=session
        )

I’m installing from Git for now, but would love to see this in a public release soon. 😄

(I’ve just started a new project using slacker, and wanted to try betamax, so this is super convenient timing for me.)

simonsolnes commented 7 years ago

@alexwlchan Issued a version to os just now.