Python Example | Teradata Query Service - Python Example - Teradata Query Service

Teradata® Query Service Installation, Configuration, and Usage Guide for Customers - 4.01.03.01, 4.01.07.00

Deployment
VantageCloud
VantageCore
Edition
Enterprise
IntelliFlex
VMware
Product
Teradata Query Service
Release Number
4.01.03.01, 4.01.07.00
Published
September 2023
Language
English (United States)
Last Update
2024-02-16
dita:mapPath
qla1666844235399.ditamap
dita:ditavalPath
ft:empty
dita:id
enn1467244092237
Product Category
Analytical Ecosystem

The following example uses Python to query a Teradata Database for the version information. The example includes additional options like setting query bands, getting responses in GZIP compressed format, and using HTTPS.

#!/usr/bin/python
import json
import urllib2
import base64
import zlib

username = 'myusername'
password = 'mypassword'
teradataDatabaseAlias = 'mysystem'

# HTTP
url = 'http://sdl57120.labs.teradata.com:1080/systems/' + teradataDatabaseAlias + '/queries'

# HTTPS 
#url = 'https://sdl57120.labs.teradata.com:1443/systems/' + teradataDatabaseAlias + '/queries'

# Setup required HTTP headers
headers={}
headers['Content-Type'] = 'application/json'
headers['Accept'] = 'application/vnd.com.teradata.rest-v1.0+json'
headers['Authorization'] = "Basic %s" % base64.encodestring('%s:%s' % (username, password)).replace('\n', ''); 

# Uncomment to receive results gzip compressed.
#headers['Accept-Encoding'] = 'gzip'

# Set query bands
queryBands = {}
queryBands['applicationName'] = 'MyApp'
queryBands['version'] = '1.0'

# Set request fields, including SQL.
data = {}
data['query'] = 'SELECT * FROM DBC.DBCInfo'
data['queryBands'] = queryBands
data['format'] = 'array'

# Build request.
request = urllib2.Request(url, json.dumps(data), headers)

#Submit request
try:
  response = urllib2.urlopen(request);
  # Check if result have been compressed.
  if response.info().get('Content-Encoding') == 'gzip':  
    response = zlib.decompress(response.read(), 16+zlib.MAX_WBITS)    
  else:
    response = response.read();
except urllib2.HTTPError, e:
    print 'HTTPError = ' + str(e.code)
    response = e.read();
except urllib2.URLError, e:
    print 'URLError = ' + str(e.reason)
    response = e.read();

# Parse response to confirm value JSON.
results = json.loads(response);

# Print formatted results
print json.dumps(results, indent=4, sort_keys=True)

# Do something with the result.
data = results['results'][0]['data']
for d in data:
    if d[0] == 'VERSION':
        print '\nThe version of the Teradata Database is ' + d[1]