ligo.gracedb: removed all trailing whitespace

because I'm pedantic
parent b963f2f1
......@@ -29,7 +29,7 @@ DEFAULT_BASIC_URL = "https://gracedb.ligo.org/apibasic/"
GIT_TAG = 'gracedb-1.25-1'
DEFAULT_COLUMNS = "graceid,labels,group,pipeline,search,far,gpstime,created,dataurl"
#-----------------------------------------------------------------
# Util routines
......@@ -78,8 +78,8 @@ typeCodeMap = {
validTypes = list(typeCodeMap.keys())
#-----------------------------------------------------------------
# This is a factory for client classes.
# Given a base client class with the correct properties, derive
# This is a factory for client classes.
# Given a base client class with the correct properties, derive
# one suitable for use with this command-line tool. In practice,
# the base class here will either be the X509 auth GraceDb class
# or the basic auth GraceDbBasic class.
......@@ -129,7 +129,7 @@ def derive_client(ClientBase=GraceDb):
Client = derive_client()
#-----------------------------------------------------------------
# Main
# Main
def main():
......@@ -152,11 +152,11 @@ def main():
%%prog [options] ping
Test server connection
%%prog [options] upload GRACEID FILE [COMMENT]
%%prog [options] upload GRACEID FILE [COMMENT]
where GRACEID is the id of an existing candidate event in GraCEDb
FILE is the name of the file to upload. '-' indicates stdin.
COMMENT is an optional annotation to enter into the log
Upload FILE to the private data area for a candidate event. To apply
Upload FILE to the private data area for a candidate event. To apply
a tag, use the --tag-name option (and --tag-display-name if desired.)
%%prog [options] download GRACEID FILE [DESTINATION]
......@@ -180,12 +180,12 @@ def main():
LOG_N is the number of the log message.
TAG_NAME is the name of the tag
DISP_NAME is the tag display name (ignored for existing tags)
Tag an existing log message. Alternatively, the tag name and
display name can be passed in with the --tag-name and
Tag an existing log message. Alternatively, the tag name and
display name can be passed in with the --tag-name and
--tag-display-name options.
%%prog [options] delete_tag GRACEID LOG_N TAG_NAME
Remove a tag from a log message. Alternatively, the tag name
Remove a tag from a log message. Alternatively, the tag name
can be passed in with the --tag-name option.
%%prog [options] search SEARCH PARAMS
......@@ -286,7 +286,7 @@ Longer strings will be truncated.""" % {
# If the user requested a specific service, but also wants basic auth,
# then the service had better be a basic auth endpoint. Otherwise die.
# On the other hand, if the user did not specify a service url, then we
# On the other hand, if the user did not specify a service url, then we
# will use the default basic URL if basic auth was requested.
if options.use_basic_auth:
if options.service or os.environ.get('GRACEDB_SERVICE_URL', None):
......@@ -296,7 +296,7 @@ Longer strings will be truncated.""" % {
else:
service = DEFAULT_BASIC_URL
# Client subclass according to preferred auth method.
# Client subclass according to preferred auth method.
global Client
if options.use_basic_auth:
Client = derive_client(GraceDbBasic)
......@@ -424,7 +424,7 @@ Longer strings will be truncated.""" % {
response = client.writeLabel(graceid, label)
elif args[0] == 'search':
query = " ".join(args[1:])
columns = options.columns
columns = columns.replace('DEFAULTS',DEFAULT_COLUMNS)
columns = columns.split(',')
......@@ -461,7 +461,7 @@ Longer strings will be truncated.""" % {
row = [ accessFun.get(column, lambda e: defaultAccess(e,column))(e) for column in columns ]
row = "\t".join(row)
output(row)
return 0
elif args[0] == 'replace':
if len(args) != 3:
......
......@@ -26,13 +26,13 @@ Usage:
import logging
import ligo.gracedb.rest
import ligo.gracedb.logging
logging.basicConfig()
log = logging.getLogger('testing')
gracedb = ligo.gracedb.rest.GraceDb()
graceid = 'T62829'
log.addHandler(ligo.gracedb.logging.GraceDbLogHandler(gracedb, graceid))
# The following will create a log entry on the gracedb server
......
......@@ -58,7 +58,7 @@ if sys.hexversion < 0x20709f0:
ssl.wrap_socket = wrap_socket_patched
#-----------------------------------------------------------------
# Utilities
# Utilities
class safe_netrc(netrc):
"""The netrc.netrc class from the Python standard library applies access
......@@ -93,7 +93,7 @@ class safe_netrc(netrc):
# XXX It would be nice to get rid of this if we can.
# It seems that you can pass python lists via the requests package.
# That would make putting our lists into comma-separated strings
# That would make putting our lists into comma-separated strings
# unnecessary.
def cleanListInput(list_arg):
stringified_list = list_arg
......@@ -101,7 +101,7 @@ def cleanListInput(list_arg):
stringified_value = str(list_arg)
return stringified_value
if not isinstance(list_arg, six.string_types):
stringified_list = ','.join(map(str,list_arg))
stringified_list = ','.join(map(str,list_arg))
return stringified_list
# The following are used to check whether a user has tried to use
......@@ -226,10 +226,10 @@ class ProxyHTTPSConnection(ProxyHTTPConnection):
class GsiRest(object):
"""docstring for GracedbRest"""
def __init__(self,
url=DEFAULT_SERVICE_URL,
proxy_host=None,
proxy_port=3128,
def __init__(self,
url=DEFAULT_SERVICE_URL,
proxy_host=None,
proxy_port=3128,
cred=None):
if not cred:
cred = findUserCredentials()
......@@ -270,19 +270,19 @@ class GsiRest(object):
ssl_context.verify_mode = ssl.CERT_REQUIRED
ssl_context.check_hostname = True
# Find the various CA cert bundles stored on the system
ssl_context.load_default_certs()
ssl_context.load_default_certs()
if proxy_host:
self.connector = lambda: ProxyHTTPSConnection(proxy_host, proxy_port, context=ssl_context)
else:
self.connector = lambda: six.moves.http_client.HTTPSConnection(host, port, context=ssl_context)
self.connector = lambda: six.moves.http_client.HTTPSConnection(host, port, context=ssl_context)
else:
# Using and older version of python. We'll pass in the cert and key files.
if proxy_host:
self.connector = lambda: ProxyHTTPSConnection(proxy_host, proxy_port,
self.connector = lambda: ProxyHTTPSConnection(proxy_host, proxy_port,
key_file=self.key, cert_file=self.cert)
else:
self.connector = lambda: six.moves.http_client.HTTPSConnection(host, port,
self.connector = lambda: six.moves.http_client.HTTPSConnection(host, port,
key_file=self.key, cert_file=self.cert)
......@@ -291,7 +291,7 @@ class GsiRest(object):
# When there is a problem with the SSL connection or cert authentication,
# either conn.request() or conn.getresponse() will throw an exception.
# The following two wrappers are intended to catch these exceptions and
# The following two wrappers are intended to catch these exceptions and
# return an intelligible error message to the user.
# A wrapper for getting the response:
def get_response(self, conn):
......@@ -324,7 +324,7 @@ class GsiRest(object):
msg = "\nERROR \n\n"
msg += "Problem establishing secure connection: %s \n\n" % str(e)
self.output_and_die(msg)
def request(self, method, url, body=None, headers=None, priming_url=None):
# Bug in Python (versions < 2.7.1 (?))
# http://bugs.python.org/issue11898
......@@ -360,7 +360,7 @@ class GsiRest(object):
rdict['retry-after'] = response.getheader('x-throttle-wait-seconds')
response_content = json.dumps(rdict)
except:
pass
pass
raise HTTPError(response.status, response.reason, response_content)
response.json = lambda: self.load_json_or_die(response)
return response
......@@ -443,7 +443,7 @@ class GsiRest(object):
class GraceDb(GsiRest):
"""Example GraceDb REST client
The GraceDB service URL may be passed to the constructor
if an alternate GraceDb instance is desired:
......@@ -454,7 +454,7 @@ class GraceDb(GsiRest):
GraceDB behind a proxy. For other kwargs accepted by the constructor,
consult the source code.
"""
def __init__(self, service_url=DEFAULT_SERVICE_URL,
def __init__(self, service_url=DEFAULT_SERVICE_URL,
proxy_host=None, proxy_port=3128, *args, **kwargs):
GsiRest.__init__(self, service_url, proxy_host, proxy_port, *args, **kwargs)
......@@ -479,7 +479,7 @@ class GraceDb(GsiRest):
@property
def groups(self):
return self.service_info.get('groups')
@property
def pipelines(self):
return self.service_info.get('pipelines')
......@@ -593,7 +593,7 @@ class GraceDb(GsiRest):
filename = 'initial.data'
filecontents = sys.stdin.read()
else:
filecontents = open(filename, 'rb').read()
filecontents = open(filename, 'rb').read()
# Join labels list as a comma-separated string
# which will be parsed by the server.
......@@ -623,12 +623,12 @@ class GraceDb(GsiRest):
Required args: graceid, filename
This function uploads a new event file, hence changing the basic details
of an existing event.
of an existing event.
Example:
>>> g = GraceDb()
>>> r = g.replaceEvent('T101383', '/path/to/new/something.xml')
>>> r = g.replaceEvent('T101383', '/path/to/new/something.xml')
"""
if filecontents is None:
......@@ -642,7 +642,7 @@ class GraceDb(GsiRest):
def event(self, graceid):
"""Get information about a specific event
Args: graceid
Args: graceid
Example:
......@@ -657,8 +657,8 @@ class GraceDb(GsiRest):
"""Get a iterator of events in response to a query
This function returns an iterator which yields event dictionaries.
Optional arguments are query, orderby, count, and columns. The
columns argument is a comma separated list of attributes that the
Optional arguments are query, orderby, count, and columns. The
columns argument is a comma separated list of attributes that the
user would like in each event dictionary. If columns are not specified,
all attributes of the events are returned.
......@@ -686,7 +686,7 @@ class GraceDb(GsiRest):
yield event
def numEvents(self, query=None):
"""Get the number of events satisfying a query
"""Get the number of events satisfying a query
Example:
......@@ -733,9 +733,9 @@ class GraceDb(GsiRest):
Required args: graceid, filename
This method creates a new log message with your file attached. It is
This method creates a new log message with your file attached. It is
strongly preferred to use writeLog() instead of writeFile() so that you
can add a more suitable comment. That will make it easier for other
can add a more suitable comment. That will make it easier for other
users to know what your file contains.
Example:
......@@ -765,7 +765,7 @@ class GraceDb(GsiRest):
Required args: graceid
This function returns a JSON representation of all of an event's
log messages.
log messages.
Example:
......@@ -781,7 +781,7 @@ class GraceDb(GsiRest):
uri = template.format(graceid=graceid)
return self.get(uri)
def writeLog(self, graceid, message, filename=None, filecontents=None,
def writeLog(self, graceid, message, filename=None, filecontents=None,
tagname=None, displayName=None):
"""Create a new log message
......@@ -795,8 +795,8 @@ class GraceDb(GsiRest):
tagname = ["sky_loc", "my_lovely_skymap"]
If only graceid and message are provided, a text comment will be created
in the event log. If a filename is also specified, the file will be attached
to the log message and displayed along side the message text. If a tagname
in the event log. If a filename is also specified, the file will be attached
to the log message and displayed along side the message text. If a tagname
is provided, the message will be tagged.
Example:
......@@ -821,38 +821,38 @@ class GraceDb(GsiRest):
filecontents = filecontents.read()
files = [('upload', os.path.basename(filename), filecontents)]
# Let's see if tagname is a string or a list
# Let's see if tagname is a string or a list
if tagname and not isinstance(tagname, six.string_types):
tagnames = ','.join(tagname)
else:
tagnames = tagname if tagname else None
return self.post(uri, body={'message' : message, 'tagname': tagnames,
return self.post(uri, body={'message' : message, 'tagname': tagnames,
'displayName': displayName}, files=files)
def eels(self, graceid):
"""Given a GraceID, get a list of EMBB log entries
"""Given a GraceID, get a list of EMBB log entries
Example:
>>> g = GraceDb()
>>> r = g.eels('T101383')
>>> g = GraceDb()
>>> r = g.eels('T101383')
>>> full_dictionary = r.json() # Convert the response to a dictionary
>>> eel_list = full_dictionary['embblog'] # Pull out a list of EEL dicts
"""
template = self.templates['embb-event-log-template']
uri = template.format(graceid=graceid)
return self.get(uri)
def writeEel(self, graceid, group, waveband, eel_status,
def writeEel(self, graceid, group, waveband, eel_status,
obs_status, **kwargs):
"""Write an EMBB event log entry
"""Write an EMBB event log entry
Required args: graceid, group, waveband, eel_status, obs_status
(Note that 'group' here is the name of the EM MOU group, not
(Note that 'group' here is the name of the EM MOU group, not
the LVC data analysis group responsible for the original detection.)
Additional keyword arguments may be passed in to be sent in the POST
......@@ -871,11 +871,11 @@ class GraceDb(GsiRest):
wish to convey.
Any other kwargs will be ignored.
"""
"""
# validate facility, waveband, eel_status, and obs_status
if not group in self.em_groups:
raise ValueError("group must be one of %s" % self.em_groups)
if not waveband in list(self.wavebands.keys()):
raise ValueError("waveband must be one of %s" % list(self.wavebands.keys()))
......@@ -900,35 +900,35 @@ class GraceDb(GsiRest):
return self.post(uri, body=body)
def emobservations(self, graceid):
"""Given a GraceID, get a list of EM observation entries
"""Given a GraceID, get a list of EM observation entries
Example:
>>> g = GraceDb()
>>> r = g.emobserations('T101383')
>>> g = GraceDb()
>>> r = g.emobserations('T101383')
>>> full_dictionary = r.json() # Convert the response to a dictionary
>>> emo_list = full_dictionary['observations'] # Pull out a list of EMO dicts
"""
template = self.templates['emobservation-list-template']
uri = template.format(graceid=graceid)
return self.get(uri)
def writeEMObservation(self, graceid, group, raList, raWidthList,
decList, decWidthList, startTimeList, durationList, comment=None):
"""Write an EM observation entry
"""Write an EM observation entry
Required args: graceid, group, raList, decList, raWidthList,
decWidthList, startTimeList, durationList
The various lists arguments should contain Python lists or
comma-separated values (or a single value). Start times are
The various lists arguments should contain Python lists or
comma-separated values (or a single value). Start times are
in ISO 8601 UTC. Durations are in seconds.
(Note that 'group' here is the name of the EM MOU group, not
(Note that 'group' here is the name of the EM MOU group, not
the LVC data analysis group responsible for the original detection.)
"""
"""
# validate facility, waveband, eel_status, and obs_status
if not group in self.em_groups:
raise ValueError("group must be one of %s" % self.em_groups)
......@@ -936,23 +936,23 @@ class GraceDb(GsiRest):
# NOTE: One could do validation of the various list inputs here
# rather than relying on the server.
# These arguments can consist of a single element, a python
# list, or a string. Transform the list args to csv (unless they
# list, or a string. Transform the list args to csv (unless they
# already are)
raList, raWidthList, decList, decWidthList, startTimeList, durationList = list(map(
cleanListInput,
cleanListInput,
[raList, raWidthList, decList, decWidthList, startTimeList, durationList]))
template = self.templates['emobservation-list-template']
uri = template.format(graceid=graceid)
body = {
'group' : group,
body = {
'group' : group,
'raList' : raList,
'raWidthList': raWidthList,
'decList' : decList,
'decWidthList': decWidthList,
'startTimeList': startTimeList,
'durationList': durationList,
'durationList': durationList,
'comment': comment,
}
return self.post(uri, body=body)
......@@ -978,7 +978,7 @@ class GraceDb(GsiRest):
Required args: graceid, label name
The label name must correspond to one of the existing
The label name must correspond to one of the existing
GraceDB labels, else an error will result.
Example:
......@@ -1036,7 +1036,7 @@ class GraceDb(GsiRest):
Required arguments: graceid, n (the number of the log message)
and the tagname. If a displayName is provided (and if the tag
doesn't already exist), a new tag will be created with the
doesn't already exist), a new tag will be created with the
provided display name.
Example:
......@@ -1055,10 +1055,10 @@ class GraceDb(GsiRest):
"""Remove a tag from a given log message
Required arguments: graceid, n (the number of the log message)
and the tagname.
and the tagname.
Example:
>>> g = GraceDb()
>>> r = g.deleteTag('T101383', 56, 'sky_loc')
>>> r.status
......@@ -1089,20 +1089,20 @@ class GraceDb(GsiRest):
"""Given a GraceID, get a list of VOEvents
Example:
>>> g = GraceDb()
>>> r = g.voevents('T101383')
>>> voevent_list = r.json()['voevents']
>>> g = GraceDb()
>>> r = g.voevents('T101383')
>>> voevent_list = r.json()['voevents']
"""
template = self.templates['voevent-list-template']
uri = template.format(graceid=graceid)
return self.get(uri)
def createVOEvent(self, graceid, voevent_type, **kwargs):
"""Create a new VOEvent
Required args: graceid, voevent_type
Additional keyword arguments may be passed in to be sent in the POST
......@@ -1111,7 +1111,7 @@ class GraceDb(GsiRest):
skyamp_type
Any other kwargs will be ignored.
"""
"""
# validate facility, waveband, eel_status, and obs_status
voevent_type = self._getCode(voevent_type.lower(), self.voevent_types)
if not voevent_type:
......@@ -1147,7 +1147,7 @@ class GraceDb(GsiRest):
class GraceDbBasic(GraceDb):
"""Example GraceDb REST client with basic auth
The GraceDB service URL may be passed to the constructor
if an alternate GraceDb instance is desired:
......@@ -1159,7 +1159,7 @@ class GraceDbBasic(GraceDb):
consult the source code.
"""
def __init__(self, service_url=DEFAULT_BASIC_SERVICE_URL,
proxy_host=None, proxy_port=3128, username=None, password=None,
proxy_host=None, proxy_port=3128, username=None, password=None,
*args, **kwargs):
o = urlparse(service_url)
......@@ -1175,7 +1175,7 @@ class GraceDbBasic(GraceDb):
if not username or not password:
msg = "\nERROR: Could not find user credentials. \n\n"
msg +="Please use a .netrc file or provide username and password.\n\n"
msg +="Please use a .netrc file or provide username and password.\n\n"
self.output_and_die(msg)
# Construct authorization header
......@@ -1197,12 +1197,12 @@ class GraceDbBasic(GraceDb):
ssl_context.verify_mode = ssl.CERT_REQUIRED
ssl_context.check_hostname = True
# Find the various CA cert bundles stored on the system
ssl_context.load_default_certs()
ssl_context.load_default_certs()
if proxy_host:
self.connector = lambda: ProxyHTTPSConnection(proxy_host, proxy_port, context=ssl_context)
else:
self.connector = lambda: six.moves.http_client.HTTPSConnection(host, port, context=ssl_context)
self.connector = lambda: six.moves.http_client.HTTPSConnection(host, port, context=ssl_context)
else:
# Using and older version of python. We'll pass in the cert and key files.
if proxy_host:
......@@ -1244,10 +1244,10 @@ class GraceDbBasic(GraceDb):
try:
msg = "\nERROR: %s \n\n" % json.loads(response.read())['error']
except:
msg = "\nERROR: \n\n"
msg = "\nERROR: \n\n"
msg += "Please check the username/password in your .netrc file. \n"
msg += "Note: If your password is more than a year old, you will \n"
msg += "need to use the web interface to generate a new one. \n\n"
msg += "need to use the web interface to generate a new one. \n\n"
self.output_and_die(msg)
return self.adjustResponse(response)
......
......@@ -31,7 +31,7 @@ from six.moves import range
# To run:
#
# python $PATH_TO_GRACEDB_LIB/test/test.py
#
#
# Environment Variables:
#
# TEST_SERVICE
......@@ -94,7 +94,7 @@ class TestGraceDb(unittest.TestCase):
# Create event and get its graceid
eventFile = os.path.join(testdatadir, "cbc-lm.xml")
createdEvent = gracedb.createEvent("Test", "gstlal", eventFile,
createdEvent = gracedb.createEvent("Test", "gstlal", eventFile,
"LowMass", offline=offline).json()
eventId = createdEvent["graceid"]
......@@ -356,7 +356,7 @@ class TestGraceDb(unittest.TestCase):
import logging
import ligo.gracedb.rest
import ligo.gracedb.logging
logging.basicConfig()
log = logging.getLogger('testing')
log.propagate = False # Don't write to console
......
......@@ -75,7 +75,7 @@ class TestGraceDbVOEvents(unittest.TestCase):
def test_retrieve_preliminary_voevent(self):
r = gracedb.voevents(graceid)
voevent_list = r.json()['voevents']
self.assertTrue(len(voevent_list) == 1 and
self.assertTrue(len(voevent_list) == 1 and
voevent_list[0]['voevent_type'] == 'PR')
def test_create_update_voevent(self):
......
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment