Skip to content

Instantly share code, notes, and snippets.

@LucianU
Created June 4, 2025 06:00
Show Gist options
  • Save LucianU/d7064ab033dd375f3aeb1a01bacd1c7d to your computer and use it in GitHub Desktop.
Save LucianU/d7064ab033dd375f3aeb1a01bacd1c7d to your computer and use it in GitHub Desktop.
Script that uses token-based auth to connect to Azure SQL Server
import requests
import pytds
import os
import logging
logging.basicConfig(level=logging.DEBUG)
# Set these based on your Azure App registration
TENANT_ID = os.getenv('TENANT_ID')
CLIENT_ID = os.getenv('CLIENT_ID')
CLIENT_SECRET = os.getenv('CLIENT_SECRET')
SQL_SERVER = 'pytds.database.windows.net'
DATABASE = 'master'
CAFILE = '/etc/ssl/cert.pem'
# Authority and scope
AUTHORITY = f'https://login.microsoftonline.com/{TENANT_ID}'
TOKEN_URL = f'{AUTHORITY}/oauth2/v2.0/token'
SCOPE = 'https://database.windows.net/.default'
# Request the token
resp = requests.post(TOKEN_URL, data={
'client_id': CLIENT_ID,
'client_secret': CLIENT_SECRET,
'scope': SCOPE,
'grant_type': 'client_credentials',
})
resp.raise_for_status()
access_token = resp.json()['access_token']
# Connect using pytds with access_token (this assumes patched pytds)
with pytds.connect(server=SQL_SERVER,
database=DATABASE,
access_token=access_token,
tds_version=pytds.tds_base.TDS74,
cafile=CAFILE,
) as conn:
with conn.cursor() as cursor:
cursor.execute("SELECT @@VERSION")
print(cursor.fetchone())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment