Skip to content

Instantly share code, notes, and snippets.

@amix
Last active April 16, 2019 09:52
Show Gist options
  • Save amix/adf549778a855ed871dfb8dd5aa1104a to your computer and use it in GitHub Desktop.
Save amix/adf549778a855ed871dfb8dd5aa1104a to your computer and use it in GitHub Desktop.
Inspects Twist team retention and extracts a CSV report
from datetime import datetime
from csv import DictWriter
from cStringIO import StringIO
from parts.util.encoding import ensure_str
from twist.init import init_twist
init_twist(EXPOSE_MODULES=False)
from twist.models.database import main_db, close_current_connections
from twist.models import workspaces
from twist.models import users
from twist.models import user_presence
CSV_COLS = ('WORKSPACE_ID', 'PLAN', 'WORKSPACE_ACTIVE', 'WORKSPACE_AGE',
'USERS_ONBOARDED', 'USERS_ACTIVE', 'USERS_ACTIVE_PCT',
'CREATOR_ID', 'CREATOR_EMAIL')
def get_pct(count_filter, count_all):
if count_all == 0:
return 0
else:
return int(count_filter / float(count_all) * 100)
if __name__ == '__main__':
output = StringIO()
writer = DictWriter(output, fieldnames=CSV_COLS, extrasaction="ignore")
writer.writerow({i: i for i in CSV_COLS})
for (count, ws) in enumerate(workspaces.get_all()):
ws_users = list(
user for user in ws.get_users(with_setup_pending=False)
if not user.is_bot)
users_len = sum(1 for user in ws_users)
if ws.plan == workspaces.PLAN_TYPES.free:
plan = 'FREE'
else:
plan = 'UNLIMITED'
workspace_age = (datetime.utcnow() - ws.created).days
users_active = sum(
1 if user_presence.is_user_active(u.id) else 0
for u in ws_users)
users_active_pct = get_pct(users_active, len(ws_users))
creator = users.getone(ws.creator)
try:
creator_email = creator.get_primary_email()
except Exception:
creator_email = None
writer.writerow({
'WORKSPACE_ID': ws.id,
'WORKSPACE_NAME': ensure_str(ws.name),
'PLAN': plan,
'WORKSPACE_ACTIVE': users_active_pct >= 30 and 'Active' or 'Inactive',
'WORKSPACE_AGE': workspace_age,
'USERS_ONBOARDED': users_len,
'USERS_ACTIVE': users_active,
'USERS_ACTIVE_PCT': users_active_pct,
'CREATOR_ID': ws.creator,
'CREATOR_EMAIL': ensure_str(creator_email)
}) # yapf: disable
open('workspace_retention.csv',
'wb').write(output.getvalue().strip('\r\n'))
if count % 500 == 0:
count = 0
close_current_connections()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment