repository_name stringclasses 316 values | func_path_in_repository stringlengths 6 223 | func_name stringlengths 1 134 | language stringclasses 1 value | func_code_string stringlengths 57 65.5k | func_documentation_string stringlengths 1 46.3k | split_name stringclasses 1 value | func_code_url stringlengths 91 315 | called_functions listlengths 1 156 ⌀ | enclosing_scope stringlengths 2 1.48M |
|---|---|---|---|---|---|---|---|---|---|
EnergieID/smappy | smappy/smappy.py | authenticated | python | def authenticated(func):
@wraps(func)
def wrapper(*args, **kwargs):
self = args[0]
if self.refresh_token is not None and \
self.token_expiration_time <= dt.datetime.utcnow():
self.re_authenticate()
return func(*args, **kwargs)
return wrapper | Decorator to check if Smappee's access token has expired.
If it has, use the refresh token to request a new access token | train | https://github.com/EnergieID/smappy/blob/1ada3abc9a51c76205c072369258f6f4f4e8fd0f/smappy/smappy.py#L18-L30 | null | import requests
import datetime as dt
from functools import wraps
import pytz
import numbers
__title__ = "smappy"
__version__ = "0.2.16"
__author__ = "EnergieID.be"
__license__ = "MIT"
URLS = {
'token': 'https://app1pub.smappee.net/dev/v2/oauth2/token',
'servicelocation': 'https://app1pub.smappee.net/dev/v2/servicelocation'
}
class Smappee(object):
"""
Object containing Smappee's API-methods.
See https://smappee.atlassian.net/wiki/display/DEVAPI/API+Methods
"""
def __init__(self, client_id=None, client_secret=None):
"""
To receive a client id and secret,
you need to request via the Smappee support
Parameters
----------
client_id : str, optional
client_secret : str, optional
If None, you won't be able to do any authorisation,
so it requires that you already have an access token somewhere.
In that case, the SimpleSmappee class is something for you.
"""
self.client_id = client_id
self.client_secret = client_secret
self.access_token = None
self.refresh_token = None
self.token_expiration_time = None
def authenticate(self, username, password):
"""
Uses a Smappee username and password to request an access token,
refresh token and expiry date.
Parameters
----------
username : str
password : str
Returns
-------
requests.Response
access token is saved in self.access_token
refresh token is saved in self.refresh_token
expiration time is set in self.token_expiration_time as
datetime.datetime
"""
url = URLS['token']
data = {
"grant_type": "password",
"client_id": self.client_id,
"client_secret": self.client_secret,
"username": username,
"password": password
}
r = requests.post(url, data=data)
r.raise_for_status()
j = r.json()
self.access_token = j['access_token']
self.refresh_token = j['refresh_token']
self._set_token_expiration_time(expires_in=j['expires_in'])
return r
def _set_token_expiration_time(self, expires_in):
"""
Saves the token expiration time by adding the 'expires in' parameter
to the current datetime (in utc).
Parameters
----------
expires_in : int
number of seconds from the time of the request until expiration
Returns
-------
nothing
saves expiration time in self.token_expiration_time as
datetime.datetime
"""
self.token_expiration_time = dt.datetime.utcnow() + \
dt.timedelta(0, expires_in) # timedelta(days, seconds)
def re_authenticate(self):
"""
Uses the refresh token to request a new access token, refresh token and
expiration date.
Returns
-------
requests.Response
access token is saved in self.access_token
refresh token is saved in self.refresh_token
expiration time is set in self.token_expiration_time as
datetime.datetime
"""
url = URLS['token']
data = {
"grant_type": "refresh_token",
"refresh_token": self.refresh_token,
"client_id": self.client_id,
"client_secret": self.client_secret
}
r = requests.post(url, data=data)
r.raise_for_status()
j = r.json()
self.access_token = j['access_token']
self.refresh_token = j['refresh_token']
self._set_token_expiration_time(expires_in=j['expires_in'])
return r
@authenticated
def get_service_locations(self):
"""
Request service locations
Returns
-------
dict
"""
url = URLS['servicelocation']
headers = {"Authorization": "Bearer {}".format(self.access_token)}
r = requests.get(url, headers=headers)
r.raise_for_status()
return r.json()
@authenticated
def get_service_location_info(self, service_location_id):
"""
Request service location info
Parameters
----------
service_location_id : int
Returns
-------
dict
"""
url = urljoin(URLS['servicelocation'], service_location_id, "info")
headers = {"Authorization": "Bearer {}".format(self.access_token)}
r = requests.get(url, headers=headers)
r.raise_for_status()
return r.json()
@authenticated
def get_consumption(self, service_location_id, start, end, aggregation, raw=False):
"""
Request Elektricity consumption and Solar production
for a given service location.
Parameters
----------
service_location_id : int
start : int | dt.datetime | pd.Timestamp
end : int | dt.datetime | pd.Timestamp
start and end support epoch (in milliseconds),
datetime and Pandas Timestamp
aggregation : int
1 = 5 min values (only available for the last 14 days)
2 = hourly values
3 = daily values
4 = monthly values
5 = quarterly values
raw : bool
default False
if True: Return the data "as is" from the server
if False: convert the 'alwaysOn' value to Wh.
(the server returns this value as the sum of the power,
measured in 5 minute blocks. This means that it is 12 times
higher than the consumption in Wh.
See https://github.com/EnergieID/smappy/issues/24)
Returns
-------
dict
"""
url = urljoin(URLS['servicelocation'], service_location_id,
"consumption")
d = self._get_consumption(url=url, start=start, end=end,
aggregation=aggregation)
if not raw:
for block in d['consumptions']:
if 'alwaysOn' not in block.keys():
break
block.update({'alwaysOn': block['alwaysOn'] / 12})
return d
@authenticated
def get_sensor_consumption(self, service_location_id, sensor_id, start,
end, aggregation):
"""
Request consumption for a given sensor in a given service location
Parameters
----------
service_location_id : int
sensor_id : int
start : int | dt.datetime | pd.Timestamp
end : int | dt.datetime | pd.Timestamp
start and end support epoch (in milliseconds),
datetime and Pandas Timestamp
timezone-naive datetimes are assumed to be in UTC
aggregation : int
1 = 5 min values (only available for the last 14 days)
2 = hourly values
3 = daily values
4 = monthly values
5 = quarterly values
Returns
-------
dict
"""
url = urljoin(URLS['servicelocation'], service_location_id, "sensor",
sensor_id, "consumption")
return self._get_consumption(url=url, start=start, end=end,
aggregation=aggregation)
def _get_consumption(self, url, start, end, aggregation):
"""
Request for both the get_consumption and
get_sensor_consumption methods.
Parameters
----------
url : str
start : dt.datetime
end : dt.datetime
aggregation : int
Returns
-------
dict
"""
start = self._to_milliseconds(start)
end = self._to_milliseconds(end)
headers = {"Authorization": "Bearer {}".format(self.access_token)}
params = {
"aggregation": aggregation,
"from": start,
"to": end
}
r = requests.get(url, headers=headers, params=params)
r.raise_for_status()
return r.json()
@authenticated
def get_events(self, service_location_id, appliance_id, start, end,
max_number=None):
"""
Request events for a given appliance
Parameters
----------
service_location_id : int
appliance_id : int
start : int | dt.datetime | pd.Timestamp
end : int | dt.datetime | pd.Timestamp
start and end support epoch (in milliseconds),
datetime and Pandas Timestamp
timezone-naive datetimes are assumed to be in UTC
max_number : int, optional
The maximum number of events that should be returned by this query
Default returns all events in the selected period
Returns
-------
dict
"""
start = self._to_milliseconds(start)
end = self._to_milliseconds(end)
url = urljoin(URLS['servicelocation'], service_location_id, "events")
headers = {"Authorization": "Bearer {}".format(self.access_token)}
params = {
"from": start,
"to": end,
"applianceId": appliance_id,
"maxNumber": max_number
}
r = requests.get(url, headers=headers, params=params)
r.raise_for_status()
return r.json()
@authenticated
def actuator_on(self, service_location_id, actuator_id, duration=None):
"""
Turn actuator on
Parameters
----------
service_location_id : int
actuator_id : int
duration : int, optional
300,900,1800 or 3600 , specifying the time in seconds the actuator
should be turned on. Any other value results in turning on for an
undetermined period of time.
Returns
-------
requests.Response
"""
return self._actuator_on_off(
on_off='on', service_location_id=service_location_id,
actuator_id=actuator_id, duration=duration)
@authenticated
def actuator_off(self, service_location_id, actuator_id, duration=None):
"""
Turn actuator off
Parameters
----------
service_location_id : int
actuator_id : int
duration : int, optional
300,900,1800 or 3600 , specifying the time in seconds the actuator
should be turned on. Any other value results in turning on for an
undetermined period of time.
Returns
-------
requests.Response
"""
return self._actuator_on_off(
on_off='off', service_location_id=service_location_id,
actuator_id=actuator_id, duration=duration)
def _actuator_on_off(self, on_off, service_location_id, actuator_id,
duration=None):
"""
Turn actuator on or off
Parameters
----------
on_off : str
'on' or 'off'
service_location_id : int
actuator_id : int
duration : int, optional
300,900,1800 or 3600 , specifying the time in seconds the actuator
should be turned on. Any other value results in turning on for an
undetermined period of time.
Returns
-------
requests.Response
"""
url = urljoin(URLS['servicelocation'], service_location_id,
"actuator", actuator_id, on_off)
headers = {"Authorization": "Bearer {}".format(self.access_token)}
if duration is not None:
data = {"duration": duration}
else:
data = {}
r = requests.post(url, headers=headers, json=data)
r.raise_for_status()
return r
def get_consumption_dataframe(self, service_location_id, start, end,
aggregation, sensor_id=None, localize=False,
raw=False):
"""
Extends get_consumption() AND get_sensor_consumption(),
parses the results in a Pandas DataFrame
Parameters
----------
service_location_id : int
start : dt.datetime | int
end : dt.datetime | int
timezone-naive datetimes are assumed to be in UTC
epoch timestamps need to be in milliseconds
aggregation : int
sensor_id : int, optional
If a sensor id is passed, api method get_sensor_consumption will
be used otherwise (by default),
the get_consumption method will be used: this returns Electricity
and Solar consumption and production.
localize : bool
default False
default returns timestamps in UTC
if True, timezone is fetched from service location info and
Data Frame is localized
raw : bool
default False
if True: Return the data "as is" from the server
if False: convert the 'alwaysOn' value to Wh.
(the server returns this value as the sum of the power,
measured in 5 minute blocks. This means that it is 12 times
higher than the consumption in Wh.
See https://github.com/EnergieID/smappy/issues/24)
Returns
-------
pd.DataFrame
"""
import pandas as pd
if sensor_id is None:
data = self.get_consumption(
service_location_id=service_location_id, start=start,
end=end, aggregation=aggregation, raw=raw)
consumptions = data['consumptions']
else:
data = self.get_sensor_consumption(
service_location_id=service_location_id, sensor_id=sensor_id,
start=start, end=end, aggregation=aggregation)
# yeah please someone explain me why they had to name this
# differently...
consumptions = data['records']
df = pd.DataFrame.from_dict(consumptions)
if not df.empty:
df.set_index('timestamp', inplace=True)
df.index = pd.to_datetime(df.index, unit='ms', utc=True)
if localize:
info = self.get_service_location_info(
service_location_id=service_location_id)
timezone = info['timezone']
df = df.tz_convert(timezone)
return df
def _to_milliseconds(self, time):
"""
Converts a datetime-like object to epoch, in milliseconds
Timezone-naive datetime objects are assumed to be in UTC
Parameters
----------
time : dt.datetime | pd.Timestamp | int
Returns
-------
int
epoch milliseconds
"""
if isinstance(time, dt.datetime):
if time.tzinfo is None:
time = time.replace(tzinfo=pytz.UTC)
return int(time.timestamp() * 1e3)
elif isinstance(time, numbers.Number):
return time
else:
raise NotImplementedError("Time format not supported. Use milliseconds since epoch,\
Datetime or Pandas Datetime")
class SimpleSmappee(Smappee):
"""
Object to use if you have no client id, client secret, refresh token etc,
for instance if everything concerning
oAuth is handed off to a different process like a web layer.
This object only uses a given access token.
It has no means of refreshing it when it expires, in which case
the requests will return errors.
"""
def __init__(self, access_token):
"""
Parameters
----------
access_token : str
"""
super(SimpleSmappee, self).__init__(client_id=None, client_secret=None)
self.access_token = access_token
class LocalSmappee(object):
"""
Access a Smappee in your local network
"""
def __init__(self, ip):
"""
Parameters
----------
ip : str
local IP-address of your Smappee
"""
self.ip = ip
self.headers = {'Content-Type': 'application/json;charset=UTF-8'}
self.session = requests.Session()
@property
def base_url(self):
url = urljoin('http://', self.ip, 'gateway', 'apipublic')
return url
def _basic_post(self, url, data=None):
"""
Because basically every post request is the same
Parameters
----------
url : str
data : str, optional
Returns
-------
requests.Response
"""
_url = urljoin(self.base_url, url)
r = self.session.post(_url, data=data, headers=self.headers, timeout=5)
r.raise_for_status()
return r
def _basic_get(self, url, params=None):
_url = urljoin(self.base_url, url)
r = self.session.get(_url, params=params, headers=self.headers,
timeout=5)
r.raise_for_status()
return r
def logon(self, password='admin'):
"""
Parameters
----------
password : str
default 'admin'
Returns
-------
dict
"""
r = self._basic_post(url='logon', data=password)
return r.json()
def report_instantaneous_values(self):
"""
Returns
-------
dict
"""
r = self._basic_get(url='reportInstantaneousValues')
return r.json()
def load_instantaneous(self):
"""
Returns
-------
dict
"""
r = self._basic_post(url='instantaneous', data="loadInstantaneous")
return r.json()
def active_power(self):
"""
Takes the sum of all instantaneous active power values
Returns them in kWh
Returns
-------
float
"""
inst = self.load_instantaneous()
values = [float(i['value']) for i in inst if i['key'].endswith('ActivePower')]
return sum(values) / 1000
def active_cosfi(self):
"""
Takes the average of all instantaneous cosfi values
Returns
-------
float
"""
inst = self.load_instantaneous()
values = [float(i['value']) for i in inst if i['key'].endswith('Cosfi')]
return sum(values) / len(values)
def restart(self):
"""
Returns
-------
requests.Response
"""
return self._basic_get(url='restartSmappee?action=2')
def reset_active_power_peaks(self):
"""
Returns
-------
requests.Response
"""
return self._basic_post(url='resetActivePowerPeaks')
def reset_ip_scan_cache(self):
"""
Returns
-------
requests.Response
"""
return self._basic_post(url='resetIPScanCache')
def reset_sensor_cache(self):
"""
Returns
-------
requests.Response
"""
return self._basic_post(url='resetSensorCache')
def reset_data(self):
"""
Returns
-------
requests.Response
"""
return self._basic_post(url='clearData')
def clear_appliances(self):
"""
Returns
-------
requests.Response
"""
return self._basic_post(url='clearAppliances')
def load_advanced_config(self):
"""
Returns
-------
dict
"""
r = self._basic_post(url='advancedConfigPublic', data='load')
return r.json()
def load_config(self):
"""
Returns
-------
dict
"""
r = self._basic_post(url='configPublic', data='load')
return r.json()
def save_config(self, *args, **kwargs):
"""
Parameters
----------
args
kwargs
Raises
------
NotImplementedError
"""
raise NotImplementedError("JavaScript Code can be found on "
"https://github.com/EnergyID/smappy/issues/16"
", feel free to implement it, or create an "
"issue if you have need for this function")
def load_command_control_config(self):
"""
Returns
-------
dict
"""
r = self._basic_post(url='commandControlPublic', data='load')
return r.json()
def send_group(self):
"""
Returns
-------
requests.Response
"""
return self._basic_post(url='commandControlPublic', data='controlGroup')
def on_command_control(self, val_id):
"""
Parameters
----------
val_id : str
Returns
-------
requests.Response
"""
data = "control,controlId=1|" + val_id
return self._basic_post(url='commandControlPublic', data=data)
def off_command_control(self, val_id):
"""
Parameters
----------
val_id : str
Returns
-------
requests.Response
"""
data = "control,controlId=0|" + val_id
return self._basic_post(url='commandControlPublic', data=data)
def add_command_control(self, *args, **kwargs):
"""
Parameters
----------
args
kwargs
Raises
-------
NotImplementedError
"""
raise NotImplementedError("JavaScript Code can be found on "
"https://github.com/EnergyID/smappy/issues/16"
", feel free to implement it, or create an "
"issue if you have need for this function")
def delete_command_control(self, val_id):
"""
Parameters
----------
val_id : str
Returns
-------
requests.Response
"""
data = "delete,controlId=" + val_id
return self._basic_post(url='commandControlPublic', data=data)
def delete_command_control_timers(self, val_id):
"""
Parameters
----------
val_id : str
Returns
-------
requests.Response
"""
data = "deleteTimers,controlId=" + val_id
return self._basic_post(url='commandControlPublic', data=data)
def add_command_control_timed(self, *args, **kwargs):
"""
Parameters
----------
args
kwargs
Raises
-------
NotImplementedError
"""
raise NotImplementedError("JavaScript Code can be found on "
"https://github.com/EnergyID/smappy/issues/16"
", feel free to implement it, or create an "
"issue if you have need for this function")
def load_logfiles(self):
"""
Returns
-------
dict
"""
r = self._basic_post(url='logBrowser', data='logFileList')
return r.json()
def select_logfile(self, logfile):
"""
Parameters
----------
logfile : str
Returns
-------
dict
"""
data = 'logFileSelect,' + logfile
r = self._basic_post(url='logBrowser', data=data)
return r.json()
def urljoin(*parts):
"""
Join terms together with forward slashes
Parameters
----------
parts
Returns
-------
str
"""
# first strip extra forward slashes (except http:// and the likes) and
# create list
part_list = []
for part in parts:
p = str(part)
if p.endswith('//'):
p = p[0:-1]
else:
p = p.strip('/')
part_list.append(p)
# join everything together
url = '/'.join(part_list)
return url
|
EnergieID/smappy | smappy/smappy.py | urljoin | python | def urljoin(*parts):
# first strip extra forward slashes (except http:// and the likes) and
# create list
part_list = []
for part in parts:
p = str(part)
if p.endswith('//'):
p = p[0:-1]
else:
p = p.strip('/')
part_list.append(p)
# join everything together
url = '/'.join(part_list)
return url | Join terms together with forward slashes
Parameters
----------
parts
Returns
-------
str | train | https://github.com/EnergieID/smappy/blob/1ada3abc9a51c76205c072369258f6f4f4e8fd0f/smappy/smappy.py#L806-L830 | null | import requests
import datetime as dt
from functools import wraps
import pytz
import numbers
__title__ = "smappy"
__version__ = "0.2.16"
__author__ = "EnergieID.be"
__license__ = "MIT"
URLS = {
'token': 'https://app1pub.smappee.net/dev/v2/oauth2/token',
'servicelocation': 'https://app1pub.smappee.net/dev/v2/servicelocation'
}
def authenticated(func):
"""
Decorator to check if Smappee's access token has expired.
If it has, use the refresh token to request a new access token
"""
@wraps(func)
def wrapper(*args, **kwargs):
self = args[0]
if self.refresh_token is not None and \
self.token_expiration_time <= dt.datetime.utcnow():
self.re_authenticate()
return func(*args, **kwargs)
return wrapper
class Smappee(object):
"""
Object containing Smappee's API-methods.
See https://smappee.atlassian.net/wiki/display/DEVAPI/API+Methods
"""
def __init__(self, client_id=None, client_secret=None):
"""
To receive a client id and secret,
you need to request via the Smappee support
Parameters
----------
client_id : str, optional
client_secret : str, optional
If None, you won't be able to do any authorisation,
so it requires that you already have an access token somewhere.
In that case, the SimpleSmappee class is something for you.
"""
self.client_id = client_id
self.client_secret = client_secret
self.access_token = None
self.refresh_token = None
self.token_expiration_time = None
def authenticate(self, username, password):
"""
Uses a Smappee username and password to request an access token,
refresh token and expiry date.
Parameters
----------
username : str
password : str
Returns
-------
requests.Response
access token is saved in self.access_token
refresh token is saved in self.refresh_token
expiration time is set in self.token_expiration_time as
datetime.datetime
"""
url = URLS['token']
data = {
"grant_type": "password",
"client_id": self.client_id,
"client_secret": self.client_secret,
"username": username,
"password": password
}
r = requests.post(url, data=data)
r.raise_for_status()
j = r.json()
self.access_token = j['access_token']
self.refresh_token = j['refresh_token']
self._set_token_expiration_time(expires_in=j['expires_in'])
return r
def _set_token_expiration_time(self, expires_in):
"""
Saves the token expiration time by adding the 'expires in' parameter
to the current datetime (in utc).
Parameters
----------
expires_in : int
number of seconds from the time of the request until expiration
Returns
-------
nothing
saves expiration time in self.token_expiration_time as
datetime.datetime
"""
self.token_expiration_time = dt.datetime.utcnow() + \
dt.timedelta(0, expires_in) # timedelta(days, seconds)
def re_authenticate(self):
"""
Uses the refresh token to request a new access token, refresh token and
expiration date.
Returns
-------
requests.Response
access token is saved in self.access_token
refresh token is saved in self.refresh_token
expiration time is set in self.token_expiration_time as
datetime.datetime
"""
url = URLS['token']
data = {
"grant_type": "refresh_token",
"refresh_token": self.refresh_token,
"client_id": self.client_id,
"client_secret": self.client_secret
}
r = requests.post(url, data=data)
r.raise_for_status()
j = r.json()
self.access_token = j['access_token']
self.refresh_token = j['refresh_token']
self._set_token_expiration_time(expires_in=j['expires_in'])
return r
@authenticated
def get_service_locations(self):
"""
Request service locations
Returns
-------
dict
"""
url = URLS['servicelocation']
headers = {"Authorization": "Bearer {}".format(self.access_token)}
r = requests.get(url, headers=headers)
r.raise_for_status()
return r.json()
@authenticated
def get_service_location_info(self, service_location_id):
"""
Request service location info
Parameters
----------
service_location_id : int
Returns
-------
dict
"""
url = urljoin(URLS['servicelocation'], service_location_id, "info")
headers = {"Authorization": "Bearer {}".format(self.access_token)}
r = requests.get(url, headers=headers)
r.raise_for_status()
return r.json()
@authenticated
def get_consumption(self, service_location_id, start, end, aggregation, raw=False):
"""
Request Elektricity consumption and Solar production
for a given service location.
Parameters
----------
service_location_id : int
start : int | dt.datetime | pd.Timestamp
end : int | dt.datetime | pd.Timestamp
start and end support epoch (in milliseconds),
datetime and Pandas Timestamp
aggregation : int
1 = 5 min values (only available for the last 14 days)
2 = hourly values
3 = daily values
4 = monthly values
5 = quarterly values
raw : bool
default False
if True: Return the data "as is" from the server
if False: convert the 'alwaysOn' value to Wh.
(the server returns this value as the sum of the power,
measured in 5 minute blocks. This means that it is 12 times
higher than the consumption in Wh.
See https://github.com/EnergieID/smappy/issues/24)
Returns
-------
dict
"""
url = urljoin(URLS['servicelocation'], service_location_id,
"consumption")
d = self._get_consumption(url=url, start=start, end=end,
aggregation=aggregation)
if not raw:
for block in d['consumptions']:
if 'alwaysOn' not in block.keys():
break
block.update({'alwaysOn': block['alwaysOn'] / 12})
return d
@authenticated
def get_sensor_consumption(self, service_location_id, sensor_id, start,
end, aggregation):
"""
Request consumption for a given sensor in a given service location
Parameters
----------
service_location_id : int
sensor_id : int
start : int | dt.datetime | pd.Timestamp
end : int | dt.datetime | pd.Timestamp
start and end support epoch (in milliseconds),
datetime and Pandas Timestamp
timezone-naive datetimes are assumed to be in UTC
aggregation : int
1 = 5 min values (only available for the last 14 days)
2 = hourly values
3 = daily values
4 = monthly values
5 = quarterly values
Returns
-------
dict
"""
url = urljoin(URLS['servicelocation'], service_location_id, "sensor",
sensor_id, "consumption")
return self._get_consumption(url=url, start=start, end=end,
aggregation=aggregation)
def _get_consumption(self, url, start, end, aggregation):
"""
Request for both the get_consumption and
get_sensor_consumption methods.
Parameters
----------
url : str
start : dt.datetime
end : dt.datetime
aggregation : int
Returns
-------
dict
"""
start = self._to_milliseconds(start)
end = self._to_milliseconds(end)
headers = {"Authorization": "Bearer {}".format(self.access_token)}
params = {
"aggregation": aggregation,
"from": start,
"to": end
}
r = requests.get(url, headers=headers, params=params)
r.raise_for_status()
return r.json()
@authenticated
def get_events(self, service_location_id, appliance_id, start, end,
max_number=None):
"""
Request events for a given appliance
Parameters
----------
service_location_id : int
appliance_id : int
start : int | dt.datetime | pd.Timestamp
end : int | dt.datetime | pd.Timestamp
start and end support epoch (in milliseconds),
datetime and Pandas Timestamp
timezone-naive datetimes are assumed to be in UTC
max_number : int, optional
The maximum number of events that should be returned by this query
Default returns all events in the selected period
Returns
-------
dict
"""
start = self._to_milliseconds(start)
end = self._to_milliseconds(end)
url = urljoin(URLS['servicelocation'], service_location_id, "events")
headers = {"Authorization": "Bearer {}".format(self.access_token)}
params = {
"from": start,
"to": end,
"applianceId": appliance_id,
"maxNumber": max_number
}
r = requests.get(url, headers=headers, params=params)
r.raise_for_status()
return r.json()
@authenticated
def actuator_on(self, service_location_id, actuator_id, duration=None):
"""
Turn actuator on
Parameters
----------
service_location_id : int
actuator_id : int
duration : int, optional
300,900,1800 or 3600 , specifying the time in seconds the actuator
should be turned on. Any other value results in turning on for an
undetermined period of time.
Returns
-------
requests.Response
"""
return self._actuator_on_off(
on_off='on', service_location_id=service_location_id,
actuator_id=actuator_id, duration=duration)
@authenticated
def actuator_off(self, service_location_id, actuator_id, duration=None):
"""
Turn actuator off
Parameters
----------
service_location_id : int
actuator_id : int
duration : int, optional
300,900,1800 or 3600 , specifying the time in seconds the actuator
should be turned on. Any other value results in turning on for an
undetermined period of time.
Returns
-------
requests.Response
"""
return self._actuator_on_off(
on_off='off', service_location_id=service_location_id,
actuator_id=actuator_id, duration=duration)
def _actuator_on_off(self, on_off, service_location_id, actuator_id,
duration=None):
"""
Turn actuator on or off
Parameters
----------
on_off : str
'on' or 'off'
service_location_id : int
actuator_id : int
duration : int, optional
300,900,1800 or 3600 , specifying the time in seconds the actuator
should be turned on. Any other value results in turning on for an
undetermined period of time.
Returns
-------
requests.Response
"""
url = urljoin(URLS['servicelocation'], service_location_id,
"actuator", actuator_id, on_off)
headers = {"Authorization": "Bearer {}".format(self.access_token)}
if duration is not None:
data = {"duration": duration}
else:
data = {}
r = requests.post(url, headers=headers, json=data)
r.raise_for_status()
return r
def get_consumption_dataframe(self, service_location_id, start, end,
aggregation, sensor_id=None, localize=False,
raw=False):
"""
Extends get_consumption() AND get_sensor_consumption(),
parses the results in a Pandas DataFrame
Parameters
----------
service_location_id : int
start : dt.datetime | int
end : dt.datetime | int
timezone-naive datetimes are assumed to be in UTC
epoch timestamps need to be in milliseconds
aggregation : int
sensor_id : int, optional
If a sensor id is passed, api method get_sensor_consumption will
be used otherwise (by default),
the get_consumption method will be used: this returns Electricity
and Solar consumption and production.
localize : bool
default False
default returns timestamps in UTC
if True, timezone is fetched from service location info and
Data Frame is localized
raw : bool
default False
if True: Return the data "as is" from the server
if False: convert the 'alwaysOn' value to Wh.
(the server returns this value as the sum of the power,
measured in 5 minute blocks. This means that it is 12 times
higher than the consumption in Wh.
See https://github.com/EnergieID/smappy/issues/24)
Returns
-------
pd.DataFrame
"""
import pandas as pd
if sensor_id is None:
data = self.get_consumption(
service_location_id=service_location_id, start=start,
end=end, aggregation=aggregation, raw=raw)
consumptions = data['consumptions']
else:
data = self.get_sensor_consumption(
service_location_id=service_location_id, sensor_id=sensor_id,
start=start, end=end, aggregation=aggregation)
# yeah please someone explain me why they had to name this
# differently...
consumptions = data['records']
df = pd.DataFrame.from_dict(consumptions)
if not df.empty:
df.set_index('timestamp', inplace=True)
df.index = pd.to_datetime(df.index, unit='ms', utc=True)
if localize:
info = self.get_service_location_info(
service_location_id=service_location_id)
timezone = info['timezone']
df = df.tz_convert(timezone)
return df
def _to_milliseconds(self, time):
"""
Converts a datetime-like object to epoch, in milliseconds
Timezone-naive datetime objects are assumed to be in UTC
Parameters
----------
time : dt.datetime | pd.Timestamp | int
Returns
-------
int
epoch milliseconds
"""
if isinstance(time, dt.datetime):
if time.tzinfo is None:
time = time.replace(tzinfo=pytz.UTC)
return int(time.timestamp() * 1e3)
elif isinstance(time, numbers.Number):
return time
else:
raise NotImplementedError("Time format not supported. Use milliseconds since epoch,\
Datetime or Pandas Datetime")
class SimpleSmappee(Smappee):
"""
Object to use if you have no client id, client secret, refresh token etc,
for instance if everything concerning
oAuth is handed off to a different process like a web layer.
This object only uses a given access token.
It has no means of refreshing it when it expires, in which case
the requests will return errors.
"""
def __init__(self, access_token):
"""
Parameters
----------
access_token : str
"""
super(SimpleSmappee, self).__init__(client_id=None, client_secret=None)
self.access_token = access_token
class LocalSmappee(object):
"""
Access a Smappee in your local network
"""
def __init__(self, ip):
"""
Parameters
----------
ip : str
local IP-address of your Smappee
"""
self.ip = ip
self.headers = {'Content-Type': 'application/json;charset=UTF-8'}
self.session = requests.Session()
@property
def base_url(self):
url = urljoin('http://', self.ip, 'gateway', 'apipublic')
return url
def _basic_post(self, url, data=None):
"""
Because basically every post request is the same
Parameters
----------
url : str
data : str, optional
Returns
-------
requests.Response
"""
_url = urljoin(self.base_url, url)
r = self.session.post(_url, data=data, headers=self.headers, timeout=5)
r.raise_for_status()
return r
def _basic_get(self, url, params=None):
_url = urljoin(self.base_url, url)
r = self.session.get(_url, params=params, headers=self.headers,
timeout=5)
r.raise_for_status()
return r
def logon(self, password='admin'):
"""
Parameters
----------
password : str
default 'admin'
Returns
-------
dict
"""
r = self._basic_post(url='logon', data=password)
return r.json()
def report_instantaneous_values(self):
"""
Returns
-------
dict
"""
r = self._basic_get(url='reportInstantaneousValues')
return r.json()
def load_instantaneous(self):
"""
Returns
-------
dict
"""
r = self._basic_post(url='instantaneous', data="loadInstantaneous")
return r.json()
def active_power(self):
"""
Takes the sum of all instantaneous active power values
Returns them in kWh
Returns
-------
float
"""
inst = self.load_instantaneous()
values = [float(i['value']) for i in inst if i['key'].endswith('ActivePower')]
return sum(values) / 1000
def active_cosfi(self):
"""
Takes the average of all instantaneous cosfi values
Returns
-------
float
"""
inst = self.load_instantaneous()
values = [float(i['value']) for i in inst if i['key'].endswith('Cosfi')]
return sum(values) / len(values)
def restart(self):
"""
Returns
-------
requests.Response
"""
return self._basic_get(url='restartSmappee?action=2')
def reset_active_power_peaks(self):
"""
Returns
-------
requests.Response
"""
return self._basic_post(url='resetActivePowerPeaks')
def reset_ip_scan_cache(self):
"""
Returns
-------
requests.Response
"""
return self._basic_post(url='resetIPScanCache')
def reset_sensor_cache(self):
"""
Returns
-------
requests.Response
"""
return self._basic_post(url='resetSensorCache')
def reset_data(self):
"""
Returns
-------
requests.Response
"""
return self._basic_post(url='clearData')
def clear_appliances(self):
"""
Returns
-------
requests.Response
"""
return self._basic_post(url='clearAppliances')
def load_advanced_config(self):
"""
Returns
-------
dict
"""
r = self._basic_post(url='advancedConfigPublic', data='load')
return r.json()
def load_config(self):
"""
Returns
-------
dict
"""
r = self._basic_post(url='configPublic', data='load')
return r.json()
def save_config(self, *args, **kwargs):
"""
Parameters
----------
args
kwargs
Raises
------
NotImplementedError
"""
raise NotImplementedError("JavaScript Code can be found on "
"https://github.com/EnergyID/smappy/issues/16"
", feel free to implement it, or create an "
"issue if you have need for this function")
def load_command_control_config(self):
"""
Returns
-------
dict
"""
r = self._basic_post(url='commandControlPublic', data='load')
return r.json()
def send_group(self):
"""
Returns
-------
requests.Response
"""
return self._basic_post(url='commandControlPublic', data='controlGroup')
def on_command_control(self, val_id):
"""
Parameters
----------
val_id : str
Returns
-------
requests.Response
"""
data = "control,controlId=1|" + val_id
return self._basic_post(url='commandControlPublic', data=data)
def off_command_control(self, val_id):
"""
Parameters
----------
val_id : str
Returns
-------
requests.Response
"""
data = "control,controlId=0|" + val_id
return self._basic_post(url='commandControlPublic', data=data)
def add_command_control(self, *args, **kwargs):
"""
Parameters
----------
args
kwargs
Raises
-------
NotImplementedError
"""
raise NotImplementedError("JavaScript Code can be found on "
"https://github.com/EnergyID/smappy/issues/16"
", feel free to implement it, or create an "
"issue if you have need for this function")
def delete_command_control(self, val_id):
"""
Parameters
----------
val_id : str
Returns
-------
requests.Response
"""
data = "delete,controlId=" + val_id
return self._basic_post(url='commandControlPublic', data=data)
def delete_command_control_timers(self, val_id):
"""
Parameters
----------
val_id : str
Returns
-------
requests.Response
"""
data = "deleteTimers,controlId=" + val_id
return self._basic_post(url='commandControlPublic', data=data)
def add_command_control_timed(self, *args, **kwargs):
"""
Parameters
----------
args
kwargs
Raises
-------
NotImplementedError
"""
raise NotImplementedError("JavaScript Code can be found on "
"https://github.com/EnergyID/smappy/issues/16"
", feel free to implement it, or create an "
"issue if you have need for this function")
def load_logfiles(self):
"""
Returns
-------
dict
"""
r = self._basic_post(url='logBrowser', data='logFileList')
return r.json()
def select_logfile(self, logfile):
"""
Parameters
----------
logfile : str
Returns
-------
dict
"""
data = 'logFileSelect,' + logfile
r = self._basic_post(url='logBrowser', data=data)
return r.json()
|
EnergieID/smappy | smappy/smappy.py | Smappee.authenticate | python | def authenticate(self, username, password):
url = URLS['token']
data = {
"grant_type": "password",
"client_id": self.client_id,
"client_secret": self.client_secret,
"username": username,
"password": password
}
r = requests.post(url, data=data)
r.raise_for_status()
j = r.json()
self.access_token = j['access_token']
self.refresh_token = j['refresh_token']
self._set_token_expiration_time(expires_in=j['expires_in'])
return r | Uses a Smappee username and password to request an access token,
refresh token and expiry date.
Parameters
----------
username : str
password : str
Returns
-------
requests.Response
access token is saved in self.access_token
refresh token is saved in self.refresh_token
expiration time is set in self.token_expiration_time as
datetime.datetime | train | https://github.com/EnergieID/smappy/blob/1ada3abc9a51c76205c072369258f6f4f4e8fd0f/smappy/smappy.py#L57-L89 | [
"def _set_token_expiration_time(self, expires_in):\n \"\"\"\n Saves the token expiration time by adding the 'expires in' parameter\n to the current datetime (in utc).\n\n Parameters\n ----------\n expires_in : int\n number of seconds from the time of the request until expiration\n\n Retu... | class Smappee(object):
"""
Object containing Smappee's API-methods.
See https://smappee.atlassian.net/wiki/display/DEVAPI/API+Methods
"""
def __init__(self, client_id=None, client_secret=None):
"""
To receive a client id and secret,
you need to request via the Smappee support
Parameters
----------
client_id : str, optional
client_secret : str, optional
If None, you won't be able to do any authorisation,
so it requires that you already have an access token somewhere.
In that case, the SimpleSmappee class is something for you.
"""
self.client_id = client_id
self.client_secret = client_secret
self.access_token = None
self.refresh_token = None
self.token_expiration_time = None
def _set_token_expiration_time(self, expires_in):
"""
Saves the token expiration time by adding the 'expires in' parameter
to the current datetime (in utc).
Parameters
----------
expires_in : int
number of seconds from the time of the request until expiration
Returns
-------
nothing
saves expiration time in self.token_expiration_time as
datetime.datetime
"""
self.token_expiration_time = dt.datetime.utcnow() + \
dt.timedelta(0, expires_in) # timedelta(days, seconds)
def re_authenticate(self):
"""
Uses the refresh token to request a new access token, refresh token and
expiration date.
Returns
-------
requests.Response
access token is saved in self.access_token
refresh token is saved in self.refresh_token
expiration time is set in self.token_expiration_time as
datetime.datetime
"""
url = URLS['token']
data = {
"grant_type": "refresh_token",
"refresh_token": self.refresh_token,
"client_id": self.client_id,
"client_secret": self.client_secret
}
r = requests.post(url, data=data)
r.raise_for_status()
j = r.json()
self.access_token = j['access_token']
self.refresh_token = j['refresh_token']
self._set_token_expiration_time(expires_in=j['expires_in'])
return r
@authenticated
def get_service_locations(self):
"""
Request service locations
Returns
-------
dict
"""
url = URLS['servicelocation']
headers = {"Authorization": "Bearer {}".format(self.access_token)}
r = requests.get(url, headers=headers)
r.raise_for_status()
return r.json()
@authenticated
def get_service_location_info(self, service_location_id):
"""
Request service location info
Parameters
----------
service_location_id : int
Returns
-------
dict
"""
url = urljoin(URLS['servicelocation'], service_location_id, "info")
headers = {"Authorization": "Bearer {}".format(self.access_token)}
r = requests.get(url, headers=headers)
r.raise_for_status()
return r.json()
@authenticated
def get_consumption(self, service_location_id, start, end, aggregation, raw=False):
"""
Request Elektricity consumption and Solar production
for a given service location.
Parameters
----------
service_location_id : int
start : int | dt.datetime | pd.Timestamp
end : int | dt.datetime | pd.Timestamp
start and end support epoch (in milliseconds),
datetime and Pandas Timestamp
aggregation : int
1 = 5 min values (only available for the last 14 days)
2 = hourly values
3 = daily values
4 = monthly values
5 = quarterly values
raw : bool
default False
if True: Return the data "as is" from the server
if False: convert the 'alwaysOn' value to Wh.
(the server returns this value as the sum of the power,
measured in 5 minute blocks. This means that it is 12 times
higher than the consumption in Wh.
See https://github.com/EnergieID/smappy/issues/24)
Returns
-------
dict
"""
url = urljoin(URLS['servicelocation'], service_location_id,
"consumption")
d = self._get_consumption(url=url, start=start, end=end,
aggregation=aggregation)
if not raw:
for block in d['consumptions']:
if 'alwaysOn' not in block.keys():
break
block.update({'alwaysOn': block['alwaysOn'] / 12})
return d
@authenticated
def get_sensor_consumption(self, service_location_id, sensor_id, start,
end, aggregation):
"""
Request consumption for a given sensor in a given service location
Parameters
----------
service_location_id : int
sensor_id : int
start : int | dt.datetime | pd.Timestamp
end : int | dt.datetime | pd.Timestamp
start and end support epoch (in milliseconds),
datetime and Pandas Timestamp
timezone-naive datetimes are assumed to be in UTC
aggregation : int
1 = 5 min values (only available for the last 14 days)
2 = hourly values
3 = daily values
4 = monthly values
5 = quarterly values
Returns
-------
dict
"""
url = urljoin(URLS['servicelocation'], service_location_id, "sensor",
sensor_id, "consumption")
return self._get_consumption(url=url, start=start, end=end,
aggregation=aggregation)
def _get_consumption(self, url, start, end, aggregation):
"""
Request for both the get_consumption and
get_sensor_consumption methods.
Parameters
----------
url : str
start : dt.datetime
end : dt.datetime
aggregation : int
Returns
-------
dict
"""
start = self._to_milliseconds(start)
end = self._to_milliseconds(end)
headers = {"Authorization": "Bearer {}".format(self.access_token)}
params = {
"aggregation": aggregation,
"from": start,
"to": end
}
r = requests.get(url, headers=headers, params=params)
r.raise_for_status()
return r.json()
@authenticated
def get_events(self, service_location_id, appliance_id, start, end,
max_number=None):
"""
Request events for a given appliance
Parameters
----------
service_location_id : int
appliance_id : int
start : int | dt.datetime | pd.Timestamp
end : int | dt.datetime | pd.Timestamp
start and end support epoch (in milliseconds),
datetime and Pandas Timestamp
timezone-naive datetimes are assumed to be in UTC
max_number : int, optional
The maximum number of events that should be returned by this query
Default returns all events in the selected period
Returns
-------
dict
"""
start = self._to_milliseconds(start)
end = self._to_milliseconds(end)
url = urljoin(URLS['servicelocation'], service_location_id, "events")
headers = {"Authorization": "Bearer {}".format(self.access_token)}
params = {
"from": start,
"to": end,
"applianceId": appliance_id,
"maxNumber": max_number
}
r = requests.get(url, headers=headers, params=params)
r.raise_for_status()
return r.json()
@authenticated
def actuator_on(self, service_location_id, actuator_id, duration=None):
"""
Turn actuator on
Parameters
----------
service_location_id : int
actuator_id : int
duration : int, optional
300,900,1800 or 3600 , specifying the time in seconds the actuator
should be turned on. Any other value results in turning on for an
undetermined period of time.
Returns
-------
requests.Response
"""
return self._actuator_on_off(
on_off='on', service_location_id=service_location_id,
actuator_id=actuator_id, duration=duration)
@authenticated
def actuator_off(self, service_location_id, actuator_id, duration=None):
"""
Turn actuator off
Parameters
----------
service_location_id : int
actuator_id : int
duration : int, optional
300,900,1800 or 3600 , specifying the time in seconds the actuator
should be turned on. Any other value results in turning on for an
undetermined period of time.
Returns
-------
requests.Response
"""
return self._actuator_on_off(
on_off='off', service_location_id=service_location_id,
actuator_id=actuator_id, duration=duration)
def _actuator_on_off(self, on_off, service_location_id, actuator_id,
duration=None):
"""
Turn actuator on or off
Parameters
----------
on_off : str
'on' or 'off'
service_location_id : int
actuator_id : int
duration : int, optional
300,900,1800 or 3600 , specifying the time in seconds the actuator
should be turned on. Any other value results in turning on for an
undetermined period of time.
Returns
-------
requests.Response
"""
url = urljoin(URLS['servicelocation'], service_location_id,
"actuator", actuator_id, on_off)
headers = {"Authorization": "Bearer {}".format(self.access_token)}
if duration is not None:
data = {"duration": duration}
else:
data = {}
r = requests.post(url, headers=headers, json=data)
r.raise_for_status()
return r
def get_consumption_dataframe(self, service_location_id, start, end,
aggregation, sensor_id=None, localize=False,
raw=False):
"""
Extends get_consumption() AND get_sensor_consumption(),
parses the results in a Pandas DataFrame
Parameters
----------
service_location_id : int
start : dt.datetime | int
end : dt.datetime | int
timezone-naive datetimes are assumed to be in UTC
epoch timestamps need to be in milliseconds
aggregation : int
sensor_id : int, optional
If a sensor id is passed, api method get_sensor_consumption will
be used otherwise (by default),
the get_consumption method will be used: this returns Electricity
and Solar consumption and production.
localize : bool
default False
default returns timestamps in UTC
if True, timezone is fetched from service location info and
Data Frame is localized
raw : bool
default False
if True: Return the data "as is" from the server
if False: convert the 'alwaysOn' value to Wh.
(the server returns this value as the sum of the power,
measured in 5 minute blocks. This means that it is 12 times
higher than the consumption in Wh.
See https://github.com/EnergieID/smappy/issues/24)
Returns
-------
pd.DataFrame
"""
import pandas as pd
if sensor_id is None:
data = self.get_consumption(
service_location_id=service_location_id, start=start,
end=end, aggregation=aggregation, raw=raw)
consumptions = data['consumptions']
else:
data = self.get_sensor_consumption(
service_location_id=service_location_id, sensor_id=sensor_id,
start=start, end=end, aggregation=aggregation)
# yeah please someone explain me why they had to name this
# differently...
consumptions = data['records']
df = pd.DataFrame.from_dict(consumptions)
if not df.empty:
df.set_index('timestamp', inplace=True)
df.index = pd.to_datetime(df.index, unit='ms', utc=True)
if localize:
info = self.get_service_location_info(
service_location_id=service_location_id)
timezone = info['timezone']
df = df.tz_convert(timezone)
return df
def _to_milliseconds(self, time):
"""
Converts a datetime-like object to epoch, in milliseconds
Timezone-naive datetime objects are assumed to be in UTC
Parameters
----------
time : dt.datetime | pd.Timestamp | int
Returns
-------
int
epoch milliseconds
"""
if isinstance(time, dt.datetime):
if time.tzinfo is None:
time = time.replace(tzinfo=pytz.UTC)
return int(time.timestamp() * 1e3)
elif isinstance(time, numbers.Number):
return time
else:
raise NotImplementedError("Time format not supported. Use milliseconds since epoch,\
Datetime or Pandas Datetime")
|
EnergieID/smappy | smappy/smappy.py | Smappee._set_token_expiration_time | python | def _set_token_expiration_time(self, expires_in):
self.token_expiration_time = dt.datetime.utcnow() + \
dt.timedelta(0, expires_in) | Saves the token expiration time by adding the 'expires in' parameter
to the current datetime (in utc).
Parameters
----------
expires_in : int
number of seconds from the time of the request until expiration
Returns
-------
nothing
saves expiration time in self.token_expiration_time as
datetime.datetime | train | https://github.com/EnergieID/smappy/blob/1ada3abc9a51c76205c072369258f6f4f4e8fd0f/smappy/smappy.py#L91-L108 | null | class Smappee(object):
"""
Object containing Smappee's API-methods.
See https://smappee.atlassian.net/wiki/display/DEVAPI/API+Methods
"""
def __init__(self, client_id=None, client_secret=None):
"""
To receive a client id and secret,
you need to request via the Smappee support
Parameters
----------
client_id : str, optional
client_secret : str, optional
If None, you won't be able to do any authorisation,
so it requires that you already have an access token somewhere.
In that case, the SimpleSmappee class is something for you.
"""
self.client_id = client_id
self.client_secret = client_secret
self.access_token = None
self.refresh_token = None
self.token_expiration_time = None
def authenticate(self, username, password):
"""
Uses a Smappee username and password to request an access token,
refresh token and expiry date.
Parameters
----------
username : str
password : str
Returns
-------
requests.Response
access token is saved in self.access_token
refresh token is saved in self.refresh_token
expiration time is set in self.token_expiration_time as
datetime.datetime
"""
url = URLS['token']
data = {
"grant_type": "password",
"client_id": self.client_id,
"client_secret": self.client_secret,
"username": username,
"password": password
}
r = requests.post(url, data=data)
r.raise_for_status()
j = r.json()
self.access_token = j['access_token']
self.refresh_token = j['refresh_token']
self._set_token_expiration_time(expires_in=j['expires_in'])
return r
# timedelta(days, seconds)
def re_authenticate(self):
"""
Uses the refresh token to request a new access token, refresh token and
expiration date.
Returns
-------
requests.Response
access token is saved in self.access_token
refresh token is saved in self.refresh_token
expiration time is set in self.token_expiration_time as
datetime.datetime
"""
url = URLS['token']
data = {
"grant_type": "refresh_token",
"refresh_token": self.refresh_token,
"client_id": self.client_id,
"client_secret": self.client_secret
}
r = requests.post(url, data=data)
r.raise_for_status()
j = r.json()
self.access_token = j['access_token']
self.refresh_token = j['refresh_token']
self._set_token_expiration_time(expires_in=j['expires_in'])
return r
@authenticated
def get_service_locations(self):
"""
Request service locations
Returns
-------
dict
"""
url = URLS['servicelocation']
headers = {"Authorization": "Bearer {}".format(self.access_token)}
r = requests.get(url, headers=headers)
r.raise_for_status()
return r.json()
@authenticated
def get_service_location_info(self, service_location_id):
"""
Request service location info
Parameters
----------
service_location_id : int
Returns
-------
dict
"""
url = urljoin(URLS['servicelocation'], service_location_id, "info")
headers = {"Authorization": "Bearer {}".format(self.access_token)}
r = requests.get(url, headers=headers)
r.raise_for_status()
return r.json()
@authenticated
def get_consumption(self, service_location_id, start, end, aggregation, raw=False):
"""
Request Elektricity consumption and Solar production
for a given service location.
Parameters
----------
service_location_id : int
start : int | dt.datetime | pd.Timestamp
end : int | dt.datetime | pd.Timestamp
start and end support epoch (in milliseconds),
datetime and Pandas Timestamp
aggregation : int
1 = 5 min values (only available for the last 14 days)
2 = hourly values
3 = daily values
4 = monthly values
5 = quarterly values
raw : bool
default False
if True: Return the data "as is" from the server
if False: convert the 'alwaysOn' value to Wh.
(the server returns this value as the sum of the power,
measured in 5 minute blocks. This means that it is 12 times
higher than the consumption in Wh.
See https://github.com/EnergieID/smappy/issues/24)
Returns
-------
dict
"""
url = urljoin(URLS['servicelocation'], service_location_id,
"consumption")
d = self._get_consumption(url=url, start=start, end=end,
aggregation=aggregation)
if not raw:
for block in d['consumptions']:
if 'alwaysOn' not in block.keys():
break
block.update({'alwaysOn': block['alwaysOn'] / 12})
return d
@authenticated
def get_sensor_consumption(self, service_location_id, sensor_id, start,
end, aggregation):
"""
Request consumption for a given sensor in a given service location
Parameters
----------
service_location_id : int
sensor_id : int
start : int | dt.datetime | pd.Timestamp
end : int | dt.datetime | pd.Timestamp
start and end support epoch (in milliseconds),
datetime and Pandas Timestamp
timezone-naive datetimes are assumed to be in UTC
aggregation : int
1 = 5 min values (only available for the last 14 days)
2 = hourly values
3 = daily values
4 = monthly values
5 = quarterly values
Returns
-------
dict
"""
url = urljoin(URLS['servicelocation'], service_location_id, "sensor",
sensor_id, "consumption")
return self._get_consumption(url=url, start=start, end=end,
aggregation=aggregation)
def _get_consumption(self, url, start, end, aggregation):
"""
Request for both the get_consumption and
get_sensor_consumption methods.
Parameters
----------
url : str
start : dt.datetime
end : dt.datetime
aggregation : int
Returns
-------
dict
"""
start = self._to_milliseconds(start)
end = self._to_milliseconds(end)
headers = {"Authorization": "Bearer {}".format(self.access_token)}
params = {
"aggregation": aggregation,
"from": start,
"to": end
}
r = requests.get(url, headers=headers, params=params)
r.raise_for_status()
return r.json()
@authenticated
def get_events(self, service_location_id, appliance_id, start, end,
max_number=None):
"""
Request events for a given appliance
Parameters
----------
service_location_id : int
appliance_id : int
start : int | dt.datetime | pd.Timestamp
end : int | dt.datetime | pd.Timestamp
start and end support epoch (in milliseconds),
datetime and Pandas Timestamp
timezone-naive datetimes are assumed to be in UTC
max_number : int, optional
The maximum number of events that should be returned by this query
Default returns all events in the selected period
Returns
-------
dict
"""
start = self._to_milliseconds(start)
end = self._to_milliseconds(end)
url = urljoin(URLS['servicelocation'], service_location_id, "events")
headers = {"Authorization": "Bearer {}".format(self.access_token)}
params = {
"from": start,
"to": end,
"applianceId": appliance_id,
"maxNumber": max_number
}
r = requests.get(url, headers=headers, params=params)
r.raise_for_status()
return r.json()
@authenticated
def actuator_on(self, service_location_id, actuator_id, duration=None):
"""
Turn actuator on
Parameters
----------
service_location_id : int
actuator_id : int
duration : int, optional
300,900,1800 or 3600 , specifying the time in seconds the actuator
should be turned on. Any other value results in turning on for an
undetermined period of time.
Returns
-------
requests.Response
"""
return self._actuator_on_off(
on_off='on', service_location_id=service_location_id,
actuator_id=actuator_id, duration=duration)
@authenticated
def actuator_off(self, service_location_id, actuator_id, duration=None):
"""
Turn actuator off
Parameters
----------
service_location_id : int
actuator_id : int
duration : int, optional
300,900,1800 or 3600 , specifying the time in seconds the actuator
should be turned on. Any other value results in turning on for an
undetermined period of time.
Returns
-------
requests.Response
"""
return self._actuator_on_off(
on_off='off', service_location_id=service_location_id,
actuator_id=actuator_id, duration=duration)
def _actuator_on_off(self, on_off, service_location_id, actuator_id,
duration=None):
"""
Turn actuator on or off
Parameters
----------
on_off : str
'on' or 'off'
service_location_id : int
actuator_id : int
duration : int, optional
300,900,1800 or 3600 , specifying the time in seconds the actuator
should be turned on. Any other value results in turning on for an
undetermined period of time.
Returns
-------
requests.Response
"""
url = urljoin(URLS['servicelocation'], service_location_id,
"actuator", actuator_id, on_off)
headers = {"Authorization": "Bearer {}".format(self.access_token)}
if duration is not None:
data = {"duration": duration}
else:
data = {}
r = requests.post(url, headers=headers, json=data)
r.raise_for_status()
return r
def get_consumption_dataframe(self, service_location_id, start, end,
aggregation, sensor_id=None, localize=False,
raw=False):
"""
Extends get_consumption() AND get_sensor_consumption(),
parses the results in a Pandas DataFrame
Parameters
----------
service_location_id : int
start : dt.datetime | int
end : dt.datetime | int
timezone-naive datetimes are assumed to be in UTC
epoch timestamps need to be in milliseconds
aggregation : int
sensor_id : int, optional
If a sensor id is passed, api method get_sensor_consumption will
be used otherwise (by default),
the get_consumption method will be used: this returns Electricity
and Solar consumption and production.
localize : bool
default False
default returns timestamps in UTC
if True, timezone is fetched from service location info and
Data Frame is localized
raw : bool
default False
if True: Return the data "as is" from the server
if False: convert the 'alwaysOn' value to Wh.
(the server returns this value as the sum of the power,
measured in 5 minute blocks. This means that it is 12 times
higher than the consumption in Wh.
See https://github.com/EnergieID/smappy/issues/24)
Returns
-------
pd.DataFrame
"""
import pandas as pd
if sensor_id is None:
data = self.get_consumption(
service_location_id=service_location_id, start=start,
end=end, aggregation=aggregation, raw=raw)
consumptions = data['consumptions']
else:
data = self.get_sensor_consumption(
service_location_id=service_location_id, sensor_id=sensor_id,
start=start, end=end, aggregation=aggregation)
# yeah please someone explain me why they had to name this
# differently...
consumptions = data['records']
df = pd.DataFrame.from_dict(consumptions)
if not df.empty:
df.set_index('timestamp', inplace=True)
df.index = pd.to_datetime(df.index, unit='ms', utc=True)
if localize:
info = self.get_service_location_info(
service_location_id=service_location_id)
timezone = info['timezone']
df = df.tz_convert(timezone)
return df
def _to_milliseconds(self, time):
"""
Converts a datetime-like object to epoch, in milliseconds
Timezone-naive datetime objects are assumed to be in UTC
Parameters
----------
time : dt.datetime | pd.Timestamp | int
Returns
-------
int
epoch milliseconds
"""
if isinstance(time, dt.datetime):
if time.tzinfo is None:
time = time.replace(tzinfo=pytz.UTC)
return int(time.timestamp() * 1e3)
elif isinstance(time, numbers.Number):
return time
else:
raise NotImplementedError("Time format not supported. Use milliseconds since epoch,\
Datetime or Pandas Datetime")
|
EnergieID/smappy | smappy/smappy.py | Smappee.get_service_locations | python | def get_service_locations(self):
url = URLS['servicelocation']
headers = {"Authorization": "Bearer {}".format(self.access_token)}
r = requests.get(url, headers=headers)
r.raise_for_status()
return r.json() | Request service locations
Returns
-------
dict | train | https://github.com/EnergieID/smappy/blob/1ada3abc9a51c76205c072369258f6f4f4e8fd0f/smappy/smappy.py#L139-L151 | null | class Smappee(object):
"""
Object containing Smappee's API-methods.
See https://smappee.atlassian.net/wiki/display/DEVAPI/API+Methods
"""
def __init__(self, client_id=None, client_secret=None):
"""
To receive a client id and secret,
you need to request via the Smappee support
Parameters
----------
client_id : str, optional
client_secret : str, optional
If None, you won't be able to do any authorisation,
so it requires that you already have an access token somewhere.
In that case, the SimpleSmappee class is something for you.
"""
self.client_id = client_id
self.client_secret = client_secret
self.access_token = None
self.refresh_token = None
self.token_expiration_time = None
def authenticate(self, username, password):
"""
Uses a Smappee username and password to request an access token,
refresh token and expiry date.
Parameters
----------
username : str
password : str
Returns
-------
requests.Response
access token is saved in self.access_token
refresh token is saved in self.refresh_token
expiration time is set in self.token_expiration_time as
datetime.datetime
"""
url = URLS['token']
data = {
"grant_type": "password",
"client_id": self.client_id,
"client_secret": self.client_secret,
"username": username,
"password": password
}
r = requests.post(url, data=data)
r.raise_for_status()
j = r.json()
self.access_token = j['access_token']
self.refresh_token = j['refresh_token']
self._set_token_expiration_time(expires_in=j['expires_in'])
return r
def _set_token_expiration_time(self, expires_in):
"""
Saves the token expiration time by adding the 'expires in' parameter
to the current datetime (in utc).
Parameters
----------
expires_in : int
number of seconds from the time of the request until expiration
Returns
-------
nothing
saves expiration time in self.token_expiration_time as
datetime.datetime
"""
self.token_expiration_time = dt.datetime.utcnow() + \
dt.timedelta(0, expires_in) # timedelta(days, seconds)
def re_authenticate(self):
"""
Uses the refresh token to request a new access token, refresh token and
expiration date.
Returns
-------
requests.Response
access token is saved in self.access_token
refresh token is saved in self.refresh_token
expiration time is set in self.token_expiration_time as
datetime.datetime
"""
url = URLS['token']
data = {
"grant_type": "refresh_token",
"refresh_token": self.refresh_token,
"client_id": self.client_id,
"client_secret": self.client_secret
}
r = requests.post(url, data=data)
r.raise_for_status()
j = r.json()
self.access_token = j['access_token']
self.refresh_token = j['refresh_token']
self._set_token_expiration_time(expires_in=j['expires_in'])
return r
@authenticated
@authenticated
def get_service_location_info(self, service_location_id):
"""
Request service location info
Parameters
----------
service_location_id : int
Returns
-------
dict
"""
url = urljoin(URLS['servicelocation'], service_location_id, "info")
headers = {"Authorization": "Bearer {}".format(self.access_token)}
r = requests.get(url, headers=headers)
r.raise_for_status()
return r.json()
@authenticated
def get_consumption(self, service_location_id, start, end, aggregation, raw=False):
"""
Request Elektricity consumption and Solar production
for a given service location.
Parameters
----------
service_location_id : int
start : int | dt.datetime | pd.Timestamp
end : int | dt.datetime | pd.Timestamp
start and end support epoch (in milliseconds),
datetime and Pandas Timestamp
aggregation : int
1 = 5 min values (only available for the last 14 days)
2 = hourly values
3 = daily values
4 = monthly values
5 = quarterly values
raw : bool
default False
if True: Return the data "as is" from the server
if False: convert the 'alwaysOn' value to Wh.
(the server returns this value as the sum of the power,
measured in 5 minute blocks. This means that it is 12 times
higher than the consumption in Wh.
See https://github.com/EnergieID/smappy/issues/24)
Returns
-------
dict
"""
url = urljoin(URLS['servicelocation'], service_location_id,
"consumption")
d = self._get_consumption(url=url, start=start, end=end,
aggregation=aggregation)
if not raw:
for block in d['consumptions']:
if 'alwaysOn' not in block.keys():
break
block.update({'alwaysOn': block['alwaysOn'] / 12})
return d
@authenticated
def get_sensor_consumption(self, service_location_id, sensor_id, start,
end, aggregation):
"""
Request consumption for a given sensor in a given service location
Parameters
----------
service_location_id : int
sensor_id : int
start : int | dt.datetime | pd.Timestamp
end : int | dt.datetime | pd.Timestamp
start and end support epoch (in milliseconds),
datetime and Pandas Timestamp
timezone-naive datetimes are assumed to be in UTC
aggregation : int
1 = 5 min values (only available for the last 14 days)
2 = hourly values
3 = daily values
4 = monthly values
5 = quarterly values
Returns
-------
dict
"""
url = urljoin(URLS['servicelocation'], service_location_id, "sensor",
sensor_id, "consumption")
return self._get_consumption(url=url, start=start, end=end,
aggregation=aggregation)
def _get_consumption(self, url, start, end, aggregation):
"""
Request for both the get_consumption and
get_sensor_consumption methods.
Parameters
----------
url : str
start : dt.datetime
end : dt.datetime
aggregation : int
Returns
-------
dict
"""
start = self._to_milliseconds(start)
end = self._to_milliseconds(end)
headers = {"Authorization": "Bearer {}".format(self.access_token)}
params = {
"aggregation": aggregation,
"from": start,
"to": end
}
r = requests.get(url, headers=headers, params=params)
r.raise_for_status()
return r.json()
@authenticated
def get_events(self, service_location_id, appliance_id, start, end,
max_number=None):
"""
Request events for a given appliance
Parameters
----------
service_location_id : int
appliance_id : int
start : int | dt.datetime | pd.Timestamp
end : int | dt.datetime | pd.Timestamp
start and end support epoch (in milliseconds),
datetime and Pandas Timestamp
timezone-naive datetimes are assumed to be in UTC
max_number : int, optional
The maximum number of events that should be returned by this query
Default returns all events in the selected period
Returns
-------
dict
"""
start = self._to_milliseconds(start)
end = self._to_milliseconds(end)
url = urljoin(URLS['servicelocation'], service_location_id, "events")
headers = {"Authorization": "Bearer {}".format(self.access_token)}
params = {
"from": start,
"to": end,
"applianceId": appliance_id,
"maxNumber": max_number
}
r = requests.get(url, headers=headers, params=params)
r.raise_for_status()
return r.json()
@authenticated
def actuator_on(self, service_location_id, actuator_id, duration=None):
"""
Turn actuator on
Parameters
----------
service_location_id : int
actuator_id : int
duration : int, optional
300,900,1800 or 3600 , specifying the time in seconds the actuator
should be turned on. Any other value results in turning on for an
undetermined period of time.
Returns
-------
requests.Response
"""
return self._actuator_on_off(
on_off='on', service_location_id=service_location_id,
actuator_id=actuator_id, duration=duration)
@authenticated
def actuator_off(self, service_location_id, actuator_id, duration=None):
"""
Turn actuator off
Parameters
----------
service_location_id : int
actuator_id : int
duration : int, optional
300,900,1800 or 3600 , specifying the time in seconds the actuator
should be turned on. Any other value results in turning on for an
undetermined period of time.
Returns
-------
requests.Response
"""
return self._actuator_on_off(
on_off='off', service_location_id=service_location_id,
actuator_id=actuator_id, duration=duration)
def _actuator_on_off(self, on_off, service_location_id, actuator_id,
duration=None):
"""
Turn actuator on or off
Parameters
----------
on_off : str
'on' or 'off'
service_location_id : int
actuator_id : int
duration : int, optional
300,900,1800 or 3600 , specifying the time in seconds the actuator
should be turned on. Any other value results in turning on for an
undetermined period of time.
Returns
-------
requests.Response
"""
url = urljoin(URLS['servicelocation'], service_location_id,
"actuator", actuator_id, on_off)
headers = {"Authorization": "Bearer {}".format(self.access_token)}
if duration is not None:
data = {"duration": duration}
else:
data = {}
r = requests.post(url, headers=headers, json=data)
r.raise_for_status()
return r
def get_consumption_dataframe(self, service_location_id, start, end,
aggregation, sensor_id=None, localize=False,
raw=False):
"""
Extends get_consumption() AND get_sensor_consumption(),
parses the results in a Pandas DataFrame
Parameters
----------
service_location_id : int
start : dt.datetime | int
end : dt.datetime | int
timezone-naive datetimes are assumed to be in UTC
epoch timestamps need to be in milliseconds
aggregation : int
sensor_id : int, optional
If a sensor id is passed, api method get_sensor_consumption will
be used otherwise (by default),
the get_consumption method will be used: this returns Electricity
and Solar consumption and production.
localize : bool
default False
default returns timestamps in UTC
if True, timezone is fetched from service location info and
Data Frame is localized
raw : bool
default False
if True: Return the data "as is" from the server
if False: convert the 'alwaysOn' value to Wh.
(the server returns this value as the sum of the power,
measured in 5 minute blocks. This means that it is 12 times
higher than the consumption in Wh.
See https://github.com/EnergieID/smappy/issues/24)
Returns
-------
pd.DataFrame
"""
import pandas as pd
if sensor_id is None:
data = self.get_consumption(
service_location_id=service_location_id, start=start,
end=end, aggregation=aggregation, raw=raw)
consumptions = data['consumptions']
else:
data = self.get_sensor_consumption(
service_location_id=service_location_id, sensor_id=sensor_id,
start=start, end=end, aggregation=aggregation)
# yeah please someone explain me why they had to name this
# differently...
consumptions = data['records']
df = pd.DataFrame.from_dict(consumptions)
if not df.empty:
df.set_index('timestamp', inplace=True)
df.index = pd.to_datetime(df.index, unit='ms', utc=True)
if localize:
info = self.get_service_location_info(
service_location_id=service_location_id)
timezone = info['timezone']
df = df.tz_convert(timezone)
return df
def _to_milliseconds(self, time):
"""
Converts a datetime-like object to epoch, in milliseconds
Timezone-naive datetime objects are assumed to be in UTC
Parameters
----------
time : dt.datetime | pd.Timestamp | int
Returns
-------
int
epoch milliseconds
"""
if isinstance(time, dt.datetime):
if time.tzinfo is None:
time = time.replace(tzinfo=pytz.UTC)
return int(time.timestamp() * 1e3)
elif isinstance(time, numbers.Number):
return time
else:
raise NotImplementedError("Time format not supported. Use milliseconds since epoch,\
Datetime or Pandas Datetime")
|
EnergieID/smappy | smappy/smappy.py | Smappee.get_service_location_info | python | def get_service_location_info(self, service_location_id):
url = urljoin(URLS['servicelocation'], service_location_id, "info")
headers = {"Authorization": "Bearer {}".format(self.access_token)}
r = requests.get(url, headers=headers)
r.raise_for_status()
return r.json() | Request service location info
Parameters
----------
service_location_id : int
Returns
-------
dict | train | https://github.com/EnergieID/smappy/blob/1ada3abc9a51c76205c072369258f6f4f4e8fd0f/smappy/smappy.py#L154-L170 | [
"def urljoin(*parts):\n \"\"\"\n Join terms together with forward slashes\n\n Parameters\n ----------\n parts\n\n Returns\n -------\n str\n \"\"\"\n # first strip extra forward slashes (except http:// and the likes) and\n # create list\n part_list = []\n for part in parts:\n ... | class Smappee(object):
"""
Object containing Smappee's API-methods.
See https://smappee.atlassian.net/wiki/display/DEVAPI/API+Methods
"""
def __init__(self, client_id=None, client_secret=None):
"""
To receive a client id and secret,
you need to request via the Smappee support
Parameters
----------
client_id : str, optional
client_secret : str, optional
If None, you won't be able to do any authorisation,
so it requires that you already have an access token somewhere.
In that case, the SimpleSmappee class is something for you.
"""
self.client_id = client_id
self.client_secret = client_secret
self.access_token = None
self.refresh_token = None
self.token_expiration_time = None
def authenticate(self, username, password):
"""
Uses a Smappee username and password to request an access token,
refresh token and expiry date.
Parameters
----------
username : str
password : str
Returns
-------
requests.Response
access token is saved in self.access_token
refresh token is saved in self.refresh_token
expiration time is set in self.token_expiration_time as
datetime.datetime
"""
url = URLS['token']
data = {
"grant_type": "password",
"client_id": self.client_id,
"client_secret": self.client_secret,
"username": username,
"password": password
}
r = requests.post(url, data=data)
r.raise_for_status()
j = r.json()
self.access_token = j['access_token']
self.refresh_token = j['refresh_token']
self._set_token_expiration_time(expires_in=j['expires_in'])
return r
def _set_token_expiration_time(self, expires_in):
"""
Saves the token expiration time by adding the 'expires in' parameter
to the current datetime (in utc).
Parameters
----------
expires_in : int
number of seconds from the time of the request until expiration
Returns
-------
nothing
saves expiration time in self.token_expiration_time as
datetime.datetime
"""
self.token_expiration_time = dt.datetime.utcnow() + \
dt.timedelta(0, expires_in) # timedelta(days, seconds)
def re_authenticate(self):
"""
Uses the refresh token to request a new access token, refresh token and
expiration date.
Returns
-------
requests.Response
access token is saved in self.access_token
refresh token is saved in self.refresh_token
expiration time is set in self.token_expiration_time as
datetime.datetime
"""
url = URLS['token']
data = {
"grant_type": "refresh_token",
"refresh_token": self.refresh_token,
"client_id": self.client_id,
"client_secret": self.client_secret
}
r = requests.post(url, data=data)
r.raise_for_status()
j = r.json()
self.access_token = j['access_token']
self.refresh_token = j['refresh_token']
self._set_token_expiration_time(expires_in=j['expires_in'])
return r
@authenticated
def get_service_locations(self):
"""
Request service locations
Returns
-------
dict
"""
url = URLS['servicelocation']
headers = {"Authorization": "Bearer {}".format(self.access_token)}
r = requests.get(url, headers=headers)
r.raise_for_status()
return r.json()
@authenticated
@authenticated
def get_consumption(self, service_location_id, start, end, aggregation, raw=False):
"""
Request Elektricity consumption and Solar production
for a given service location.
Parameters
----------
service_location_id : int
start : int | dt.datetime | pd.Timestamp
end : int | dt.datetime | pd.Timestamp
start and end support epoch (in milliseconds),
datetime and Pandas Timestamp
aggregation : int
1 = 5 min values (only available for the last 14 days)
2 = hourly values
3 = daily values
4 = monthly values
5 = quarterly values
raw : bool
default False
if True: Return the data "as is" from the server
if False: convert the 'alwaysOn' value to Wh.
(the server returns this value as the sum of the power,
measured in 5 minute blocks. This means that it is 12 times
higher than the consumption in Wh.
See https://github.com/EnergieID/smappy/issues/24)
Returns
-------
dict
"""
url = urljoin(URLS['servicelocation'], service_location_id,
"consumption")
d = self._get_consumption(url=url, start=start, end=end,
aggregation=aggregation)
if not raw:
for block in d['consumptions']:
if 'alwaysOn' not in block.keys():
break
block.update({'alwaysOn': block['alwaysOn'] / 12})
return d
@authenticated
def get_sensor_consumption(self, service_location_id, sensor_id, start,
end, aggregation):
"""
Request consumption for a given sensor in a given service location
Parameters
----------
service_location_id : int
sensor_id : int
start : int | dt.datetime | pd.Timestamp
end : int | dt.datetime | pd.Timestamp
start and end support epoch (in milliseconds),
datetime and Pandas Timestamp
timezone-naive datetimes are assumed to be in UTC
aggregation : int
1 = 5 min values (only available for the last 14 days)
2 = hourly values
3 = daily values
4 = monthly values
5 = quarterly values
Returns
-------
dict
"""
url = urljoin(URLS['servicelocation'], service_location_id, "sensor",
sensor_id, "consumption")
return self._get_consumption(url=url, start=start, end=end,
aggregation=aggregation)
def _get_consumption(self, url, start, end, aggregation):
"""
Request for both the get_consumption and
get_sensor_consumption methods.
Parameters
----------
url : str
start : dt.datetime
end : dt.datetime
aggregation : int
Returns
-------
dict
"""
start = self._to_milliseconds(start)
end = self._to_milliseconds(end)
headers = {"Authorization": "Bearer {}".format(self.access_token)}
params = {
"aggregation": aggregation,
"from": start,
"to": end
}
r = requests.get(url, headers=headers, params=params)
r.raise_for_status()
return r.json()
@authenticated
def get_events(self, service_location_id, appliance_id, start, end,
max_number=None):
"""
Request events for a given appliance
Parameters
----------
service_location_id : int
appliance_id : int
start : int | dt.datetime | pd.Timestamp
end : int | dt.datetime | pd.Timestamp
start and end support epoch (in milliseconds),
datetime and Pandas Timestamp
timezone-naive datetimes are assumed to be in UTC
max_number : int, optional
The maximum number of events that should be returned by this query
Default returns all events in the selected period
Returns
-------
dict
"""
start = self._to_milliseconds(start)
end = self._to_milliseconds(end)
url = urljoin(URLS['servicelocation'], service_location_id, "events")
headers = {"Authorization": "Bearer {}".format(self.access_token)}
params = {
"from": start,
"to": end,
"applianceId": appliance_id,
"maxNumber": max_number
}
r = requests.get(url, headers=headers, params=params)
r.raise_for_status()
return r.json()
@authenticated
def actuator_on(self, service_location_id, actuator_id, duration=None):
"""
Turn actuator on
Parameters
----------
service_location_id : int
actuator_id : int
duration : int, optional
300,900,1800 or 3600 , specifying the time in seconds the actuator
should be turned on. Any other value results in turning on for an
undetermined period of time.
Returns
-------
requests.Response
"""
return self._actuator_on_off(
on_off='on', service_location_id=service_location_id,
actuator_id=actuator_id, duration=duration)
@authenticated
def actuator_off(self, service_location_id, actuator_id, duration=None):
"""
Turn actuator off
Parameters
----------
service_location_id : int
actuator_id : int
duration : int, optional
300,900,1800 or 3600 , specifying the time in seconds the actuator
should be turned on. Any other value results in turning on for an
undetermined period of time.
Returns
-------
requests.Response
"""
return self._actuator_on_off(
on_off='off', service_location_id=service_location_id,
actuator_id=actuator_id, duration=duration)
def _actuator_on_off(self, on_off, service_location_id, actuator_id,
duration=None):
"""
Turn actuator on or off
Parameters
----------
on_off : str
'on' or 'off'
service_location_id : int
actuator_id : int
duration : int, optional
300,900,1800 or 3600 , specifying the time in seconds the actuator
should be turned on. Any other value results in turning on for an
undetermined period of time.
Returns
-------
requests.Response
"""
url = urljoin(URLS['servicelocation'], service_location_id,
"actuator", actuator_id, on_off)
headers = {"Authorization": "Bearer {}".format(self.access_token)}
if duration is not None:
data = {"duration": duration}
else:
data = {}
r = requests.post(url, headers=headers, json=data)
r.raise_for_status()
return r
def get_consumption_dataframe(self, service_location_id, start, end,
aggregation, sensor_id=None, localize=False,
raw=False):
"""
Extends get_consumption() AND get_sensor_consumption(),
parses the results in a Pandas DataFrame
Parameters
----------
service_location_id : int
start : dt.datetime | int
end : dt.datetime | int
timezone-naive datetimes are assumed to be in UTC
epoch timestamps need to be in milliseconds
aggregation : int
sensor_id : int, optional
If a sensor id is passed, api method get_sensor_consumption will
be used otherwise (by default),
the get_consumption method will be used: this returns Electricity
and Solar consumption and production.
localize : bool
default False
default returns timestamps in UTC
if True, timezone is fetched from service location info and
Data Frame is localized
raw : bool
default False
if True: Return the data "as is" from the server
if False: convert the 'alwaysOn' value to Wh.
(the server returns this value as the sum of the power,
measured in 5 minute blocks. This means that it is 12 times
higher than the consumption in Wh.
See https://github.com/EnergieID/smappy/issues/24)
Returns
-------
pd.DataFrame
"""
import pandas as pd
if sensor_id is None:
data = self.get_consumption(
service_location_id=service_location_id, start=start,
end=end, aggregation=aggregation, raw=raw)
consumptions = data['consumptions']
else:
data = self.get_sensor_consumption(
service_location_id=service_location_id, sensor_id=sensor_id,
start=start, end=end, aggregation=aggregation)
# yeah please someone explain me why they had to name this
# differently...
consumptions = data['records']
df = pd.DataFrame.from_dict(consumptions)
if not df.empty:
df.set_index('timestamp', inplace=True)
df.index = pd.to_datetime(df.index, unit='ms', utc=True)
if localize:
info = self.get_service_location_info(
service_location_id=service_location_id)
timezone = info['timezone']
df = df.tz_convert(timezone)
return df
def _to_milliseconds(self, time):
"""
Converts a datetime-like object to epoch, in milliseconds
Timezone-naive datetime objects are assumed to be in UTC
Parameters
----------
time : dt.datetime | pd.Timestamp | int
Returns
-------
int
epoch milliseconds
"""
if isinstance(time, dt.datetime):
if time.tzinfo is None:
time = time.replace(tzinfo=pytz.UTC)
return int(time.timestamp() * 1e3)
elif isinstance(time, numbers.Number):
return time
else:
raise NotImplementedError("Time format not supported. Use milliseconds since epoch,\
Datetime or Pandas Datetime")
|
EnergieID/smappy | smappy/smappy.py | Smappee.get_consumption | python | def get_consumption(self, service_location_id, start, end, aggregation, raw=False):
url = urljoin(URLS['servicelocation'], service_location_id,
"consumption")
d = self._get_consumption(url=url, start=start, end=end,
aggregation=aggregation)
if not raw:
for block in d['consumptions']:
if 'alwaysOn' not in block.keys():
break
block.update({'alwaysOn': block['alwaysOn'] / 12})
return d | Request Elektricity consumption and Solar production
for a given service location.
Parameters
----------
service_location_id : int
start : int | dt.datetime | pd.Timestamp
end : int | dt.datetime | pd.Timestamp
start and end support epoch (in milliseconds),
datetime and Pandas Timestamp
aggregation : int
1 = 5 min values (only available for the last 14 days)
2 = hourly values
3 = daily values
4 = monthly values
5 = quarterly values
raw : bool
default False
if True: Return the data "as is" from the server
if False: convert the 'alwaysOn' value to Wh.
(the server returns this value as the sum of the power,
measured in 5 minute blocks. This means that it is 12 times
higher than the consumption in Wh.
See https://github.com/EnergieID/smappy/issues/24)
Returns
-------
dict | train | https://github.com/EnergieID/smappy/blob/1ada3abc9a51c76205c072369258f6f4f4e8fd0f/smappy/smappy.py#L173-L213 | [
"def urljoin(*parts):\n \"\"\"\n Join terms together with forward slashes\n\n Parameters\n ----------\n parts\n\n Returns\n -------\n str\n \"\"\"\n # first strip extra forward slashes (except http:// and the likes) and\n # create list\n part_list = []\n for part in parts:\n ... | class Smappee(object):
"""
Object containing Smappee's API-methods.
See https://smappee.atlassian.net/wiki/display/DEVAPI/API+Methods
"""
def __init__(self, client_id=None, client_secret=None):
"""
To receive a client id and secret,
you need to request via the Smappee support
Parameters
----------
client_id : str, optional
client_secret : str, optional
If None, you won't be able to do any authorisation,
so it requires that you already have an access token somewhere.
In that case, the SimpleSmappee class is something for you.
"""
self.client_id = client_id
self.client_secret = client_secret
self.access_token = None
self.refresh_token = None
self.token_expiration_time = None
def authenticate(self, username, password):
"""
Uses a Smappee username and password to request an access token,
refresh token and expiry date.
Parameters
----------
username : str
password : str
Returns
-------
requests.Response
access token is saved in self.access_token
refresh token is saved in self.refresh_token
expiration time is set in self.token_expiration_time as
datetime.datetime
"""
url = URLS['token']
data = {
"grant_type": "password",
"client_id": self.client_id,
"client_secret": self.client_secret,
"username": username,
"password": password
}
r = requests.post(url, data=data)
r.raise_for_status()
j = r.json()
self.access_token = j['access_token']
self.refresh_token = j['refresh_token']
self._set_token_expiration_time(expires_in=j['expires_in'])
return r
def _set_token_expiration_time(self, expires_in):
"""
Saves the token expiration time by adding the 'expires in' parameter
to the current datetime (in utc).
Parameters
----------
expires_in : int
number of seconds from the time of the request until expiration
Returns
-------
nothing
saves expiration time in self.token_expiration_time as
datetime.datetime
"""
self.token_expiration_time = dt.datetime.utcnow() + \
dt.timedelta(0, expires_in) # timedelta(days, seconds)
def re_authenticate(self):
"""
Uses the refresh token to request a new access token, refresh token and
expiration date.
Returns
-------
requests.Response
access token is saved in self.access_token
refresh token is saved in self.refresh_token
expiration time is set in self.token_expiration_time as
datetime.datetime
"""
url = URLS['token']
data = {
"grant_type": "refresh_token",
"refresh_token": self.refresh_token,
"client_id": self.client_id,
"client_secret": self.client_secret
}
r = requests.post(url, data=data)
r.raise_for_status()
j = r.json()
self.access_token = j['access_token']
self.refresh_token = j['refresh_token']
self._set_token_expiration_time(expires_in=j['expires_in'])
return r
@authenticated
def get_service_locations(self):
"""
Request service locations
Returns
-------
dict
"""
url = URLS['servicelocation']
headers = {"Authorization": "Bearer {}".format(self.access_token)}
r = requests.get(url, headers=headers)
r.raise_for_status()
return r.json()
@authenticated
def get_service_location_info(self, service_location_id):
"""
Request service location info
Parameters
----------
service_location_id : int
Returns
-------
dict
"""
url = urljoin(URLS['servicelocation'], service_location_id, "info")
headers = {"Authorization": "Bearer {}".format(self.access_token)}
r = requests.get(url, headers=headers)
r.raise_for_status()
return r.json()
@authenticated
@authenticated
def get_sensor_consumption(self, service_location_id, sensor_id, start,
end, aggregation):
"""
Request consumption for a given sensor in a given service location
Parameters
----------
service_location_id : int
sensor_id : int
start : int | dt.datetime | pd.Timestamp
end : int | dt.datetime | pd.Timestamp
start and end support epoch (in milliseconds),
datetime and Pandas Timestamp
timezone-naive datetimes are assumed to be in UTC
aggregation : int
1 = 5 min values (only available for the last 14 days)
2 = hourly values
3 = daily values
4 = monthly values
5 = quarterly values
Returns
-------
dict
"""
url = urljoin(URLS['servicelocation'], service_location_id, "sensor",
sensor_id, "consumption")
return self._get_consumption(url=url, start=start, end=end,
aggregation=aggregation)
def _get_consumption(self, url, start, end, aggregation):
"""
Request for both the get_consumption and
get_sensor_consumption methods.
Parameters
----------
url : str
start : dt.datetime
end : dt.datetime
aggregation : int
Returns
-------
dict
"""
start = self._to_milliseconds(start)
end = self._to_milliseconds(end)
headers = {"Authorization": "Bearer {}".format(self.access_token)}
params = {
"aggregation": aggregation,
"from": start,
"to": end
}
r = requests.get(url, headers=headers, params=params)
r.raise_for_status()
return r.json()
@authenticated
def get_events(self, service_location_id, appliance_id, start, end,
max_number=None):
"""
Request events for a given appliance
Parameters
----------
service_location_id : int
appliance_id : int
start : int | dt.datetime | pd.Timestamp
end : int | dt.datetime | pd.Timestamp
start and end support epoch (in milliseconds),
datetime and Pandas Timestamp
timezone-naive datetimes are assumed to be in UTC
max_number : int, optional
The maximum number of events that should be returned by this query
Default returns all events in the selected period
Returns
-------
dict
"""
start = self._to_milliseconds(start)
end = self._to_milliseconds(end)
url = urljoin(URLS['servicelocation'], service_location_id, "events")
headers = {"Authorization": "Bearer {}".format(self.access_token)}
params = {
"from": start,
"to": end,
"applianceId": appliance_id,
"maxNumber": max_number
}
r = requests.get(url, headers=headers, params=params)
r.raise_for_status()
return r.json()
@authenticated
def actuator_on(self, service_location_id, actuator_id, duration=None):
"""
Turn actuator on
Parameters
----------
service_location_id : int
actuator_id : int
duration : int, optional
300,900,1800 or 3600 , specifying the time in seconds the actuator
should be turned on. Any other value results in turning on for an
undetermined period of time.
Returns
-------
requests.Response
"""
return self._actuator_on_off(
on_off='on', service_location_id=service_location_id,
actuator_id=actuator_id, duration=duration)
@authenticated
def actuator_off(self, service_location_id, actuator_id, duration=None):
"""
Turn actuator off
Parameters
----------
service_location_id : int
actuator_id : int
duration : int, optional
300,900,1800 or 3600 , specifying the time in seconds the actuator
should be turned on. Any other value results in turning on for an
undetermined period of time.
Returns
-------
requests.Response
"""
return self._actuator_on_off(
on_off='off', service_location_id=service_location_id,
actuator_id=actuator_id, duration=duration)
def _actuator_on_off(self, on_off, service_location_id, actuator_id,
duration=None):
"""
Turn actuator on or off
Parameters
----------
on_off : str
'on' or 'off'
service_location_id : int
actuator_id : int
duration : int, optional
300,900,1800 or 3600 , specifying the time in seconds the actuator
should be turned on. Any other value results in turning on for an
undetermined period of time.
Returns
-------
requests.Response
"""
url = urljoin(URLS['servicelocation'], service_location_id,
"actuator", actuator_id, on_off)
headers = {"Authorization": "Bearer {}".format(self.access_token)}
if duration is not None:
data = {"duration": duration}
else:
data = {}
r = requests.post(url, headers=headers, json=data)
r.raise_for_status()
return r
def get_consumption_dataframe(self, service_location_id, start, end,
aggregation, sensor_id=None, localize=False,
raw=False):
"""
Extends get_consumption() AND get_sensor_consumption(),
parses the results in a Pandas DataFrame
Parameters
----------
service_location_id : int
start : dt.datetime | int
end : dt.datetime | int
timezone-naive datetimes are assumed to be in UTC
epoch timestamps need to be in milliseconds
aggregation : int
sensor_id : int, optional
If a sensor id is passed, api method get_sensor_consumption will
be used otherwise (by default),
the get_consumption method will be used: this returns Electricity
and Solar consumption and production.
localize : bool
default False
default returns timestamps in UTC
if True, timezone is fetched from service location info and
Data Frame is localized
raw : bool
default False
if True: Return the data "as is" from the server
if False: convert the 'alwaysOn' value to Wh.
(the server returns this value as the sum of the power,
measured in 5 minute blocks. This means that it is 12 times
higher than the consumption in Wh.
See https://github.com/EnergieID/smappy/issues/24)
Returns
-------
pd.DataFrame
"""
import pandas as pd
if sensor_id is None:
data = self.get_consumption(
service_location_id=service_location_id, start=start,
end=end, aggregation=aggregation, raw=raw)
consumptions = data['consumptions']
else:
data = self.get_sensor_consumption(
service_location_id=service_location_id, sensor_id=sensor_id,
start=start, end=end, aggregation=aggregation)
# yeah please someone explain me why they had to name this
# differently...
consumptions = data['records']
df = pd.DataFrame.from_dict(consumptions)
if not df.empty:
df.set_index('timestamp', inplace=True)
df.index = pd.to_datetime(df.index, unit='ms', utc=True)
if localize:
info = self.get_service_location_info(
service_location_id=service_location_id)
timezone = info['timezone']
df = df.tz_convert(timezone)
return df
def _to_milliseconds(self, time):
"""
Converts a datetime-like object to epoch, in milliseconds
Timezone-naive datetime objects are assumed to be in UTC
Parameters
----------
time : dt.datetime | pd.Timestamp | int
Returns
-------
int
epoch milliseconds
"""
if isinstance(time, dt.datetime):
if time.tzinfo is None:
time = time.replace(tzinfo=pytz.UTC)
return int(time.timestamp() * 1e3)
elif isinstance(time, numbers.Number):
return time
else:
raise NotImplementedError("Time format not supported. Use milliseconds since epoch,\
Datetime or Pandas Datetime")
|
EnergieID/smappy | smappy/smappy.py | Smappee.get_sensor_consumption | python | def get_sensor_consumption(self, service_location_id, sensor_id, start,
end, aggregation):
url = urljoin(URLS['servicelocation'], service_location_id, "sensor",
sensor_id, "consumption")
return self._get_consumption(url=url, start=start, end=end,
aggregation=aggregation) | Request consumption for a given sensor in a given service location
Parameters
----------
service_location_id : int
sensor_id : int
start : int | dt.datetime | pd.Timestamp
end : int | dt.datetime | pd.Timestamp
start and end support epoch (in milliseconds),
datetime and Pandas Timestamp
timezone-naive datetimes are assumed to be in UTC
aggregation : int
1 = 5 min values (only available for the last 14 days)
2 = hourly values
3 = daily values
4 = monthly values
5 = quarterly values
Returns
-------
dict | train | https://github.com/EnergieID/smappy/blob/1ada3abc9a51c76205c072369258f6f4f4e8fd0f/smappy/smappy.py#L216-L244 | [
"def urljoin(*parts):\n \"\"\"\n Join terms together with forward slashes\n\n Parameters\n ----------\n parts\n\n Returns\n -------\n str\n \"\"\"\n # first strip extra forward slashes (except http:// and the likes) and\n # create list\n part_list = []\n for part in parts:\n ... | class Smappee(object):
"""
Object containing Smappee's API-methods.
See https://smappee.atlassian.net/wiki/display/DEVAPI/API+Methods
"""
def __init__(self, client_id=None, client_secret=None):
"""
To receive a client id and secret,
you need to request via the Smappee support
Parameters
----------
client_id : str, optional
client_secret : str, optional
If None, you won't be able to do any authorisation,
so it requires that you already have an access token somewhere.
In that case, the SimpleSmappee class is something for you.
"""
self.client_id = client_id
self.client_secret = client_secret
self.access_token = None
self.refresh_token = None
self.token_expiration_time = None
def authenticate(self, username, password):
"""
Uses a Smappee username and password to request an access token,
refresh token and expiry date.
Parameters
----------
username : str
password : str
Returns
-------
requests.Response
access token is saved in self.access_token
refresh token is saved in self.refresh_token
expiration time is set in self.token_expiration_time as
datetime.datetime
"""
url = URLS['token']
data = {
"grant_type": "password",
"client_id": self.client_id,
"client_secret": self.client_secret,
"username": username,
"password": password
}
r = requests.post(url, data=data)
r.raise_for_status()
j = r.json()
self.access_token = j['access_token']
self.refresh_token = j['refresh_token']
self._set_token_expiration_time(expires_in=j['expires_in'])
return r
def _set_token_expiration_time(self, expires_in):
"""
Saves the token expiration time by adding the 'expires in' parameter
to the current datetime (in utc).
Parameters
----------
expires_in : int
number of seconds from the time of the request until expiration
Returns
-------
nothing
saves expiration time in self.token_expiration_time as
datetime.datetime
"""
self.token_expiration_time = dt.datetime.utcnow() + \
dt.timedelta(0, expires_in) # timedelta(days, seconds)
def re_authenticate(self):
"""
Uses the refresh token to request a new access token, refresh token and
expiration date.
Returns
-------
requests.Response
access token is saved in self.access_token
refresh token is saved in self.refresh_token
expiration time is set in self.token_expiration_time as
datetime.datetime
"""
url = URLS['token']
data = {
"grant_type": "refresh_token",
"refresh_token": self.refresh_token,
"client_id": self.client_id,
"client_secret": self.client_secret
}
r = requests.post(url, data=data)
r.raise_for_status()
j = r.json()
self.access_token = j['access_token']
self.refresh_token = j['refresh_token']
self._set_token_expiration_time(expires_in=j['expires_in'])
return r
@authenticated
def get_service_locations(self):
"""
Request service locations
Returns
-------
dict
"""
url = URLS['servicelocation']
headers = {"Authorization": "Bearer {}".format(self.access_token)}
r = requests.get(url, headers=headers)
r.raise_for_status()
return r.json()
@authenticated
def get_service_location_info(self, service_location_id):
"""
Request service location info
Parameters
----------
service_location_id : int
Returns
-------
dict
"""
url = urljoin(URLS['servicelocation'], service_location_id, "info")
headers = {"Authorization": "Bearer {}".format(self.access_token)}
r = requests.get(url, headers=headers)
r.raise_for_status()
return r.json()
@authenticated
def get_consumption(self, service_location_id, start, end, aggregation, raw=False):
"""
Request Elektricity consumption and Solar production
for a given service location.
Parameters
----------
service_location_id : int
start : int | dt.datetime | pd.Timestamp
end : int | dt.datetime | pd.Timestamp
start and end support epoch (in milliseconds),
datetime and Pandas Timestamp
aggregation : int
1 = 5 min values (only available for the last 14 days)
2 = hourly values
3 = daily values
4 = monthly values
5 = quarterly values
raw : bool
default False
if True: Return the data "as is" from the server
if False: convert the 'alwaysOn' value to Wh.
(the server returns this value as the sum of the power,
measured in 5 minute blocks. This means that it is 12 times
higher than the consumption in Wh.
See https://github.com/EnergieID/smappy/issues/24)
Returns
-------
dict
"""
url = urljoin(URLS['servicelocation'], service_location_id,
"consumption")
d = self._get_consumption(url=url, start=start, end=end,
aggregation=aggregation)
if not raw:
for block in d['consumptions']:
if 'alwaysOn' not in block.keys():
break
block.update({'alwaysOn': block['alwaysOn'] / 12})
return d
@authenticated
def _get_consumption(self, url, start, end, aggregation):
"""
Request for both the get_consumption and
get_sensor_consumption methods.
Parameters
----------
url : str
start : dt.datetime
end : dt.datetime
aggregation : int
Returns
-------
dict
"""
start = self._to_milliseconds(start)
end = self._to_milliseconds(end)
headers = {"Authorization": "Bearer {}".format(self.access_token)}
params = {
"aggregation": aggregation,
"from": start,
"to": end
}
r = requests.get(url, headers=headers, params=params)
r.raise_for_status()
return r.json()
@authenticated
def get_events(self, service_location_id, appliance_id, start, end,
max_number=None):
"""
Request events for a given appliance
Parameters
----------
service_location_id : int
appliance_id : int
start : int | dt.datetime | pd.Timestamp
end : int | dt.datetime | pd.Timestamp
start and end support epoch (in milliseconds),
datetime and Pandas Timestamp
timezone-naive datetimes are assumed to be in UTC
max_number : int, optional
The maximum number of events that should be returned by this query
Default returns all events in the selected period
Returns
-------
dict
"""
start = self._to_milliseconds(start)
end = self._to_milliseconds(end)
url = urljoin(URLS['servicelocation'], service_location_id, "events")
headers = {"Authorization": "Bearer {}".format(self.access_token)}
params = {
"from": start,
"to": end,
"applianceId": appliance_id,
"maxNumber": max_number
}
r = requests.get(url, headers=headers, params=params)
r.raise_for_status()
return r.json()
@authenticated
def actuator_on(self, service_location_id, actuator_id, duration=None):
"""
Turn actuator on
Parameters
----------
service_location_id : int
actuator_id : int
duration : int, optional
300,900,1800 or 3600 , specifying the time in seconds the actuator
should be turned on. Any other value results in turning on for an
undetermined period of time.
Returns
-------
requests.Response
"""
return self._actuator_on_off(
on_off='on', service_location_id=service_location_id,
actuator_id=actuator_id, duration=duration)
@authenticated
def actuator_off(self, service_location_id, actuator_id, duration=None):
"""
Turn actuator off
Parameters
----------
service_location_id : int
actuator_id : int
duration : int, optional
300,900,1800 or 3600 , specifying the time in seconds the actuator
should be turned on. Any other value results in turning on for an
undetermined period of time.
Returns
-------
requests.Response
"""
return self._actuator_on_off(
on_off='off', service_location_id=service_location_id,
actuator_id=actuator_id, duration=duration)
def _actuator_on_off(self, on_off, service_location_id, actuator_id,
duration=None):
"""
Turn actuator on or off
Parameters
----------
on_off : str
'on' or 'off'
service_location_id : int
actuator_id : int
duration : int, optional
300,900,1800 or 3600 , specifying the time in seconds the actuator
should be turned on. Any other value results in turning on for an
undetermined period of time.
Returns
-------
requests.Response
"""
url = urljoin(URLS['servicelocation'], service_location_id,
"actuator", actuator_id, on_off)
headers = {"Authorization": "Bearer {}".format(self.access_token)}
if duration is not None:
data = {"duration": duration}
else:
data = {}
r = requests.post(url, headers=headers, json=data)
r.raise_for_status()
return r
def get_consumption_dataframe(self, service_location_id, start, end,
aggregation, sensor_id=None, localize=False,
raw=False):
"""
Extends get_consumption() AND get_sensor_consumption(),
parses the results in a Pandas DataFrame
Parameters
----------
service_location_id : int
start : dt.datetime | int
end : dt.datetime | int
timezone-naive datetimes are assumed to be in UTC
epoch timestamps need to be in milliseconds
aggregation : int
sensor_id : int, optional
If a sensor id is passed, api method get_sensor_consumption will
be used otherwise (by default),
the get_consumption method will be used: this returns Electricity
and Solar consumption and production.
localize : bool
default False
default returns timestamps in UTC
if True, timezone is fetched from service location info and
Data Frame is localized
raw : bool
default False
if True: Return the data "as is" from the server
if False: convert the 'alwaysOn' value to Wh.
(the server returns this value as the sum of the power,
measured in 5 minute blocks. This means that it is 12 times
higher than the consumption in Wh.
See https://github.com/EnergieID/smappy/issues/24)
Returns
-------
pd.DataFrame
"""
import pandas as pd
if sensor_id is None:
data = self.get_consumption(
service_location_id=service_location_id, start=start,
end=end, aggregation=aggregation, raw=raw)
consumptions = data['consumptions']
else:
data = self.get_sensor_consumption(
service_location_id=service_location_id, sensor_id=sensor_id,
start=start, end=end, aggregation=aggregation)
# yeah please someone explain me why they had to name this
# differently...
consumptions = data['records']
df = pd.DataFrame.from_dict(consumptions)
if not df.empty:
df.set_index('timestamp', inplace=True)
df.index = pd.to_datetime(df.index, unit='ms', utc=True)
if localize:
info = self.get_service_location_info(
service_location_id=service_location_id)
timezone = info['timezone']
df = df.tz_convert(timezone)
return df
def _to_milliseconds(self, time):
"""
Converts a datetime-like object to epoch, in milliseconds
Timezone-naive datetime objects are assumed to be in UTC
Parameters
----------
time : dt.datetime | pd.Timestamp | int
Returns
-------
int
epoch milliseconds
"""
if isinstance(time, dt.datetime):
if time.tzinfo is None:
time = time.replace(tzinfo=pytz.UTC)
return int(time.timestamp() * 1e3)
elif isinstance(time, numbers.Number):
return time
else:
raise NotImplementedError("Time format not supported. Use milliseconds since epoch,\
Datetime or Pandas Datetime")
|
EnergieID/smappy | smappy/smappy.py | Smappee._get_consumption | python | def _get_consumption(self, url, start, end, aggregation):
start = self._to_milliseconds(start)
end = self._to_milliseconds(end)
headers = {"Authorization": "Bearer {}".format(self.access_token)}
params = {
"aggregation": aggregation,
"from": start,
"to": end
}
r = requests.get(url, headers=headers, params=params)
r.raise_for_status()
return r.json() | Request for both the get_consumption and
get_sensor_consumption methods.
Parameters
----------
url : str
start : dt.datetime
end : dt.datetime
aggregation : int
Returns
-------
dict | train | https://github.com/EnergieID/smappy/blob/1ada3abc9a51c76205c072369258f6f4f4e8fd0f/smappy/smappy.py#L246-L273 | [
"def _to_milliseconds(self, time):\n \"\"\"\n Converts a datetime-like object to epoch, in milliseconds\n Timezone-naive datetime objects are assumed to be in UTC\n\n Parameters\n ----------\n time : dt.datetime | pd.Timestamp | int\n\n Returns\n -------\n int\n epoch milliseconds\... | class Smappee(object):
"""
Object containing Smappee's API-methods.
See https://smappee.atlassian.net/wiki/display/DEVAPI/API+Methods
"""
def __init__(self, client_id=None, client_secret=None):
"""
To receive a client id and secret,
you need to request via the Smappee support
Parameters
----------
client_id : str, optional
client_secret : str, optional
If None, you won't be able to do any authorisation,
so it requires that you already have an access token somewhere.
In that case, the SimpleSmappee class is something for you.
"""
self.client_id = client_id
self.client_secret = client_secret
self.access_token = None
self.refresh_token = None
self.token_expiration_time = None
def authenticate(self, username, password):
"""
Uses a Smappee username and password to request an access token,
refresh token and expiry date.
Parameters
----------
username : str
password : str
Returns
-------
requests.Response
access token is saved in self.access_token
refresh token is saved in self.refresh_token
expiration time is set in self.token_expiration_time as
datetime.datetime
"""
url = URLS['token']
data = {
"grant_type": "password",
"client_id": self.client_id,
"client_secret": self.client_secret,
"username": username,
"password": password
}
r = requests.post(url, data=data)
r.raise_for_status()
j = r.json()
self.access_token = j['access_token']
self.refresh_token = j['refresh_token']
self._set_token_expiration_time(expires_in=j['expires_in'])
return r
def _set_token_expiration_time(self, expires_in):
"""
Saves the token expiration time by adding the 'expires in' parameter
to the current datetime (in utc).
Parameters
----------
expires_in : int
number of seconds from the time of the request until expiration
Returns
-------
nothing
saves expiration time in self.token_expiration_time as
datetime.datetime
"""
self.token_expiration_time = dt.datetime.utcnow() + \
dt.timedelta(0, expires_in) # timedelta(days, seconds)
def re_authenticate(self):
"""
Uses the refresh token to request a new access token, refresh token and
expiration date.
Returns
-------
requests.Response
access token is saved in self.access_token
refresh token is saved in self.refresh_token
expiration time is set in self.token_expiration_time as
datetime.datetime
"""
url = URLS['token']
data = {
"grant_type": "refresh_token",
"refresh_token": self.refresh_token,
"client_id": self.client_id,
"client_secret": self.client_secret
}
r = requests.post(url, data=data)
r.raise_for_status()
j = r.json()
self.access_token = j['access_token']
self.refresh_token = j['refresh_token']
self._set_token_expiration_time(expires_in=j['expires_in'])
return r
@authenticated
def get_service_locations(self):
"""
Request service locations
Returns
-------
dict
"""
url = URLS['servicelocation']
headers = {"Authorization": "Bearer {}".format(self.access_token)}
r = requests.get(url, headers=headers)
r.raise_for_status()
return r.json()
@authenticated
def get_service_location_info(self, service_location_id):
"""
Request service location info
Parameters
----------
service_location_id : int
Returns
-------
dict
"""
url = urljoin(URLS['servicelocation'], service_location_id, "info")
headers = {"Authorization": "Bearer {}".format(self.access_token)}
r = requests.get(url, headers=headers)
r.raise_for_status()
return r.json()
@authenticated
def get_consumption(self, service_location_id, start, end, aggregation, raw=False):
"""
Request Elektricity consumption and Solar production
for a given service location.
Parameters
----------
service_location_id : int
start : int | dt.datetime | pd.Timestamp
end : int | dt.datetime | pd.Timestamp
start and end support epoch (in milliseconds),
datetime and Pandas Timestamp
aggregation : int
1 = 5 min values (only available for the last 14 days)
2 = hourly values
3 = daily values
4 = monthly values
5 = quarterly values
raw : bool
default False
if True: Return the data "as is" from the server
if False: convert the 'alwaysOn' value to Wh.
(the server returns this value as the sum of the power,
measured in 5 minute blocks. This means that it is 12 times
higher than the consumption in Wh.
See https://github.com/EnergieID/smappy/issues/24)
Returns
-------
dict
"""
url = urljoin(URLS['servicelocation'], service_location_id,
"consumption")
d = self._get_consumption(url=url, start=start, end=end,
aggregation=aggregation)
if not raw:
for block in d['consumptions']:
if 'alwaysOn' not in block.keys():
break
block.update({'alwaysOn': block['alwaysOn'] / 12})
return d
@authenticated
def get_sensor_consumption(self, service_location_id, sensor_id, start,
end, aggregation):
"""
Request consumption for a given sensor in a given service location
Parameters
----------
service_location_id : int
sensor_id : int
start : int | dt.datetime | pd.Timestamp
end : int | dt.datetime | pd.Timestamp
start and end support epoch (in milliseconds),
datetime and Pandas Timestamp
timezone-naive datetimes are assumed to be in UTC
aggregation : int
1 = 5 min values (only available for the last 14 days)
2 = hourly values
3 = daily values
4 = monthly values
5 = quarterly values
Returns
-------
dict
"""
url = urljoin(URLS['servicelocation'], service_location_id, "sensor",
sensor_id, "consumption")
return self._get_consumption(url=url, start=start, end=end,
aggregation=aggregation)
@authenticated
def get_events(self, service_location_id, appliance_id, start, end,
max_number=None):
"""
Request events for a given appliance
Parameters
----------
service_location_id : int
appliance_id : int
start : int | dt.datetime | pd.Timestamp
end : int | dt.datetime | pd.Timestamp
start and end support epoch (in milliseconds),
datetime and Pandas Timestamp
timezone-naive datetimes are assumed to be in UTC
max_number : int, optional
The maximum number of events that should be returned by this query
Default returns all events in the selected period
Returns
-------
dict
"""
start = self._to_milliseconds(start)
end = self._to_milliseconds(end)
url = urljoin(URLS['servicelocation'], service_location_id, "events")
headers = {"Authorization": "Bearer {}".format(self.access_token)}
params = {
"from": start,
"to": end,
"applianceId": appliance_id,
"maxNumber": max_number
}
r = requests.get(url, headers=headers, params=params)
r.raise_for_status()
return r.json()
@authenticated
def actuator_on(self, service_location_id, actuator_id, duration=None):
"""
Turn actuator on
Parameters
----------
service_location_id : int
actuator_id : int
duration : int, optional
300,900,1800 or 3600 , specifying the time in seconds the actuator
should be turned on. Any other value results in turning on for an
undetermined period of time.
Returns
-------
requests.Response
"""
return self._actuator_on_off(
on_off='on', service_location_id=service_location_id,
actuator_id=actuator_id, duration=duration)
@authenticated
def actuator_off(self, service_location_id, actuator_id, duration=None):
"""
Turn actuator off
Parameters
----------
service_location_id : int
actuator_id : int
duration : int, optional
300,900,1800 or 3600 , specifying the time in seconds the actuator
should be turned on. Any other value results in turning on for an
undetermined period of time.
Returns
-------
requests.Response
"""
return self._actuator_on_off(
on_off='off', service_location_id=service_location_id,
actuator_id=actuator_id, duration=duration)
def _actuator_on_off(self, on_off, service_location_id, actuator_id,
duration=None):
"""
Turn actuator on or off
Parameters
----------
on_off : str
'on' or 'off'
service_location_id : int
actuator_id : int
duration : int, optional
300,900,1800 or 3600 , specifying the time in seconds the actuator
should be turned on. Any other value results in turning on for an
undetermined period of time.
Returns
-------
requests.Response
"""
url = urljoin(URLS['servicelocation'], service_location_id,
"actuator", actuator_id, on_off)
headers = {"Authorization": "Bearer {}".format(self.access_token)}
if duration is not None:
data = {"duration": duration}
else:
data = {}
r = requests.post(url, headers=headers, json=data)
r.raise_for_status()
return r
def get_consumption_dataframe(self, service_location_id, start, end,
aggregation, sensor_id=None, localize=False,
raw=False):
"""
Extends get_consumption() AND get_sensor_consumption(),
parses the results in a Pandas DataFrame
Parameters
----------
service_location_id : int
start : dt.datetime | int
end : dt.datetime | int
timezone-naive datetimes are assumed to be in UTC
epoch timestamps need to be in milliseconds
aggregation : int
sensor_id : int, optional
If a sensor id is passed, api method get_sensor_consumption will
be used otherwise (by default),
the get_consumption method will be used: this returns Electricity
and Solar consumption and production.
localize : bool
default False
default returns timestamps in UTC
if True, timezone is fetched from service location info and
Data Frame is localized
raw : bool
default False
if True: Return the data "as is" from the server
if False: convert the 'alwaysOn' value to Wh.
(the server returns this value as the sum of the power,
measured in 5 minute blocks. This means that it is 12 times
higher than the consumption in Wh.
See https://github.com/EnergieID/smappy/issues/24)
Returns
-------
pd.DataFrame
"""
import pandas as pd
if sensor_id is None:
data = self.get_consumption(
service_location_id=service_location_id, start=start,
end=end, aggregation=aggregation, raw=raw)
consumptions = data['consumptions']
else:
data = self.get_sensor_consumption(
service_location_id=service_location_id, sensor_id=sensor_id,
start=start, end=end, aggregation=aggregation)
# yeah please someone explain me why they had to name this
# differently...
consumptions = data['records']
df = pd.DataFrame.from_dict(consumptions)
if not df.empty:
df.set_index('timestamp', inplace=True)
df.index = pd.to_datetime(df.index, unit='ms', utc=True)
if localize:
info = self.get_service_location_info(
service_location_id=service_location_id)
timezone = info['timezone']
df = df.tz_convert(timezone)
return df
def _to_milliseconds(self, time):
"""
Converts a datetime-like object to epoch, in milliseconds
Timezone-naive datetime objects are assumed to be in UTC
Parameters
----------
time : dt.datetime | pd.Timestamp | int
Returns
-------
int
epoch milliseconds
"""
if isinstance(time, dt.datetime):
if time.tzinfo is None:
time = time.replace(tzinfo=pytz.UTC)
return int(time.timestamp() * 1e3)
elif isinstance(time, numbers.Number):
return time
else:
raise NotImplementedError("Time format not supported. Use milliseconds since epoch,\
Datetime or Pandas Datetime")
|
EnergieID/smappy | smappy/smappy.py | Smappee.get_events | python | def get_events(self, service_location_id, appliance_id, start, end,
max_number=None):
start = self._to_milliseconds(start)
end = self._to_milliseconds(end)
url = urljoin(URLS['servicelocation'], service_location_id, "events")
headers = {"Authorization": "Bearer {}".format(self.access_token)}
params = {
"from": start,
"to": end,
"applianceId": appliance_id,
"maxNumber": max_number
}
r = requests.get(url, headers=headers, params=params)
r.raise_for_status()
return r.json() | Request events for a given appliance
Parameters
----------
service_location_id : int
appliance_id : int
start : int | dt.datetime | pd.Timestamp
end : int | dt.datetime | pd.Timestamp
start and end support epoch (in milliseconds),
datetime and Pandas Timestamp
timezone-naive datetimes are assumed to be in UTC
max_number : int, optional
The maximum number of events that should be returned by this query
Default returns all events in the selected period
Returns
-------
dict | train | https://github.com/EnergieID/smappy/blob/1ada3abc9a51c76205c072369258f6f4f4e8fd0f/smappy/smappy.py#L276-L311 | [
"def urljoin(*parts):\n \"\"\"\n Join terms together with forward slashes\n\n Parameters\n ----------\n parts\n\n Returns\n -------\n str\n \"\"\"\n # first strip extra forward slashes (except http:// and the likes) and\n # create list\n part_list = []\n for part in parts:\n ... | class Smappee(object):
"""
Object containing Smappee's API-methods.
See https://smappee.atlassian.net/wiki/display/DEVAPI/API+Methods
"""
def __init__(self, client_id=None, client_secret=None):
"""
To receive a client id and secret,
you need to request via the Smappee support
Parameters
----------
client_id : str, optional
client_secret : str, optional
If None, you won't be able to do any authorisation,
so it requires that you already have an access token somewhere.
In that case, the SimpleSmappee class is something for you.
"""
self.client_id = client_id
self.client_secret = client_secret
self.access_token = None
self.refresh_token = None
self.token_expiration_time = None
def authenticate(self, username, password):
"""
Uses a Smappee username and password to request an access token,
refresh token and expiry date.
Parameters
----------
username : str
password : str
Returns
-------
requests.Response
access token is saved in self.access_token
refresh token is saved in self.refresh_token
expiration time is set in self.token_expiration_time as
datetime.datetime
"""
url = URLS['token']
data = {
"grant_type": "password",
"client_id": self.client_id,
"client_secret": self.client_secret,
"username": username,
"password": password
}
r = requests.post(url, data=data)
r.raise_for_status()
j = r.json()
self.access_token = j['access_token']
self.refresh_token = j['refresh_token']
self._set_token_expiration_time(expires_in=j['expires_in'])
return r
def _set_token_expiration_time(self, expires_in):
"""
Saves the token expiration time by adding the 'expires in' parameter
to the current datetime (in utc).
Parameters
----------
expires_in : int
number of seconds from the time of the request until expiration
Returns
-------
nothing
saves expiration time in self.token_expiration_time as
datetime.datetime
"""
self.token_expiration_time = dt.datetime.utcnow() + \
dt.timedelta(0, expires_in) # timedelta(days, seconds)
def re_authenticate(self):
"""
Uses the refresh token to request a new access token, refresh token and
expiration date.
Returns
-------
requests.Response
access token is saved in self.access_token
refresh token is saved in self.refresh_token
expiration time is set in self.token_expiration_time as
datetime.datetime
"""
url = URLS['token']
data = {
"grant_type": "refresh_token",
"refresh_token": self.refresh_token,
"client_id": self.client_id,
"client_secret": self.client_secret
}
r = requests.post(url, data=data)
r.raise_for_status()
j = r.json()
self.access_token = j['access_token']
self.refresh_token = j['refresh_token']
self._set_token_expiration_time(expires_in=j['expires_in'])
return r
@authenticated
def get_service_locations(self):
"""
Request service locations
Returns
-------
dict
"""
url = URLS['servicelocation']
headers = {"Authorization": "Bearer {}".format(self.access_token)}
r = requests.get(url, headers=headers)
r.raise_for_status()
return r.json()
@authenticated
def get_service_location_info(self, service_location_id):
"""
Request service location info
Parameters
----------
service_location_id : int
Returns
-------
dict
"""
url = urljoin(URLS['servicelocation'], service_location_id, "info")
headers = {"Authorization": "Bearer {}".format(self.access_token)}
r = requests.get(url, headers=headers)
r.raise_for_status()
return r.json()
@authenticated
def get_consumption(self, service_location_id, start, end, aggregation, raw=False):
"""
Request Elektricity consumption and Solar production
for a given service location.
Parameters
----------
service_location_id : int
start : int | dt.datetime | pd.Timestamp
end : int | dt.datetime | pd.Timestamp
start and end support epoch (in milliseconds),
datetime and Pandas Timestamp
aggregation : int
1 = 5 min values (only available for the last 14 days)
2 = hourly values
3 = daily values
4 = monthly values
5 = quarterly values
raw : bool
default False
if True: Return the data "as is" from the server
if False: convert the 'alwaysOn' value to Wh.
(the server returns this value as the sum of the power,
measured in 5 minute blocks. This means that it is 12 times
higher than the consumption in Wh.
See https://github.com/EnergieID/smappy/issues/24)
Returns
-------
dict
"""
url = urljoin(URLS['servicelocation'], service_location_id,
"consumption")
d = self._get_consumption(url=url, start=start, end=end,
aggregation=aggregation)
if not raw:
for block in d['consumptions']:
if 'alwaysOn' not in block.keys():
break
block.update({'alwaysOn': block['alwaysOn'] / 12})
return d
@authenticated
def get_sensor_consumption(self, service_location_id, sensor_id, start,
end, aggregation):
"""
Request consumption for a given sensor in a given service location
Parameters
----------
service_location_id : int
sensor_id : int
start : int | dt.datetime | pd.Timestamp
end : int | dt.datetime | pd.Timestamp
start and end support epoch (in milliseconds),
datetime and Pandas Timestamp
timezone-naive datetimes are assumed to be in UTC
aggregation : int
1 = 5 min values (only available for the last 14 days)
2 = hourly values
3 = daily values
4 = monthly values
5 = quarterly values
Returns
-------
dict
"""
url = urljoin(URLS['servicelocation'], service_location_id, "sensor",
sensor_id, "consumption")
return self._get_consumption(url=url, start=start, end=end,
aggregation=aggregation)
def _get_consumption(self, url, start, end, aggregation):
"""
Request for both the get_consumption and
get_sensor_consumption methods.
Parameters
----------
url : str
start : dt.datetime
end : dt.datetime
aggregation : int
Returns
-------
dict
"""
start = self._to_milliseconds(start)
end = self._to_milliseconds(end)
headers = {"Authorization": "Bearer {}".format(self.access_token)}
params = {
"aggregation": aggregation,
"from": start,
"to": end
}
r = requests.get(url, headers=headers, params=params)
r.raise_for_status()
return r.json()
@authenticated
@authenticated
def actuator_on(self, service_location_id, actuator_id, duration=None):
"""
Turn actuator on
Parameters
----------
service_location_id : int
actuator_id : int
duration : int, optional
300,900,1800 or 3600 , specifying the time in seconds the actuator
should be turned on. Any other value results in turning on for an
undetermined period of time.
Returns
-------
requests.Response
"""
return self._actuator_on_off(
on_off='on', service_location_id=service_location_id,
actuator_id=actuator_id, duration=duration)
@authenticated
def actuator_off(self, service_location_id, actuator_id, duration=None):
"""
Turn actuator off
Parameters
----------
service_location_id : int
actuator_id : int
duration : int, optional
300,900,1800 or 3600 , specifying the time in seconds the actuator
should be turned on. Any other value results in turning on for an
undetermined period of time.
Returns
-------
requests.Response
"""
return self._actuator_on_off(
on_off='off', service_location_id=service_location_id,
actuator_id=actuator_id, duration=duration)
def _actuator_on_off(self, on_off, service_location_id, actuator_id,
duration=None):
"""
Turn actuator on or off
Parameters
----------
on_off : str
'on' or 'off'
service_location_id : int
actuator_id : int
duration : int, optional
300,900,1800 or 3600 , specifying the time in seconds the actuator
should be turned on. Any other value results in turning on for an
undetermined period of time.
Returns
-------
requests.Response
"""
url = urljoin(URLS['servicelocation'], service_location_id,
"actuator", actuator_id, on_off)
headers = {"Authorization": "Bearer {}".format(self.access_token)}
if duration is not None:
data = {"duration": duration}
else:
data = {}
r = requests.post(url, headers=headers, json=data)
r.raise_for_status()
return r
def get_consumption_dataframe(self, service_location_id, start, end,
aggregation, sensor_id=None, localize=False,
raw=False):
"""
Extends get_consumption() AND get_sensor_consumption(),
parses the results in a Pandas DataFrame
Parameters
----------
service_location_id : int
start : dt.datetime | int
end : dt.datetime | int
timezone-naive datetimes are assumed to be in UTC
epoch timestamps need to be in milliseconds
aggregation : int
sensor_id : int, optional
If a sensor id is passed, api method get_sensor_consumption will
be used otherwise (by default),
the get_consumption method will be used: this returns Electricity
and Solar consumption and production.
localize : bool
default False
default returns timestamps in UTC
if True, timezone is fetched from service location info and
Data Frame is localized
raw : bool
default False
if True: Return the data "as is" from the server
if False: convert the 'alwaysOn' value to Wh.
(the server returns this value as the sum of the power,
measured in 5 minute blocks. This means that it is 12 times
higher than the consumption in Wh.
See https://github.com/EnergieID/smappy/issues/24)
Returns
-------
pd.DataFrame
"""
import pandas as pd
if sensor_id is None:
data = self.get_consumption(
service_location_id=service_location_id, start=start,
end=end, aggregation=aggregation, raw=raw)
consumptions = data['consumptions']
else:
data = self.get_sensor_consumption(
service_location_id=service_location_id, sensor_id=sensor_id,
start=start, end=end, aggregation=aggregation)
# yeah please someone explain me why they had to name this
# differently...
consumptions = data['records']
df = pd.DataFrame.from_dict(consumptions)
if not df.empty:
df.set_index('timestamp', inplace=True)
df.index = pd.to_datetime(df.index, unit='ms', utc=True)
if localize:
info = self.get_service_location_info(
service_location_id=service_location_id)
timezone = info['timezone']
df = df.tz_convert(timezone)
return df
def _to_milliseconds(self, time):
"""
Converts a datetime-like object to epoch, in milliseconds
Timezone-naive datetime objects are assumed to be in UTC
Parameters
----------
time : dt.datetime | pd.Timestamp | int
Returns
-------
int
epoch milliseconds
"""
if isinstance(time, dt.datetime):
if time.tzinfo is None:
time = time.replace(tzinfo=pytz.UTC)
return int(time.timestamp() * 1e3)
elif isinstance(time, numbers.Number):
return time
else:
raise NotImplementedError("Time format not supported. Use milliseconds since epoch,\
Datetime or Pandas Datetime")
|
EnergieID/smappy | smappy/smappy.py | Smappee.actuator_on | python | def actuator_on(self, service_location_id, actuator_id, duration=None):
return self._actuator_on_off(
on_off='on', service_location_id=service_location_id,
actuator_id=actuator_id, duration=duration) | Turn actuator on
Parameters
----------
service_location_id : int
actuator_id : int
duration : int, optional
300,900,1800 or 3600 , specifying the time in seconds the actuator
should be turned on. Any other value results in turning on for an
undetermined period of time.
Returns
-------
requests.Response | train | https://github.com/EnergieID/smappy/blob/1ada3abc9a51c76205c072369258f6f4f4e8fd0f/smappy/smappy.py#L314-L333 | [
"def _actuator_on_off(self, on_off, service_location_id, actuator_id,\n duration=None):\n \"\"\"\n Turn actuator on or off\n\n Parameters\n ----------\n on_off : str\n 'on' or 'off'\n service_location_id : int\n actuator_id : int\n duration : int, optional\n ... | class Smappee(object):
"""
Object containing Smappee's API-methods.
See https://smappee.atlassian.net/wiki/display/DEVAPI/API+Methods
"""
def __init__(self, client_id=None, client_secret=None):
"""
To receive a client id and secret,
you need to request via the Smappee support
Parameters
----------
client_id : str, optional
client_secret : str, optional
If None, you won't be able to do any authorisation,
so it requires that you already have an access token somewhere.
In that case, the SimpleSmappee class is something for you.
"""
self.client_id = client_id
self.client_secret = client_secret
self.access_token = None
self.refresh_token = None
self.token_expiration_time = None
def authenticate(self, username, password):
"""
Uses a Smappee username and password to request an access token,
refresh token and expiry date.
Parameters
----------
username : str
password : str
Returns
-------
requests.Response
access token is saved in self.access_token
refresh token is saved in self.refresh_token
expiration time is set in self.token_expiration_time as
datetime.datetime
"""
url = URLS['token']
data = {
"grant_type": "password",
"client_id": self.client_id,
"client_secret": self.client_secret,
"username": username,
"password": password
}
r = requests.post(url, data=data)
r.raise_for_status()
j = r.json()
self.access_token = j['access_token']
self.refresh_token = j['refresh_token']
self._set_token_expiration_time(expires_in=j['expires_in'])
return r
def _set_token_expiration_time(self, expires_in):
"""
Saves the token expiration time by adding the 'expires in' parameter
to the current datetime (in utc).
Parameters
----------
expires_in : int
number of seconds from the time of the request until expiration
Returns
-------
nothing
saves expiration time in self.token_expiration_time as
datetime.datetime
"""
self.token_expiration_time = dt.datetime.utcnow() + \
dt.timedelta(0, expires_in) # timedelta(days, seconds)
def re_authenticate(self):
"""
Uses the refresh token to request a new access token, refresh token and
expiration date.
Returns
-------
requests.Response
access token is saved in self.access_token
refresh token is saved in self.refresh_token
expiration time is set in self.token_expiration_time as
datetime.datetime
"""
url = URLS['token']
data = {
"grant_type": "refresh_token",
"refresh_token": self.refresh_token,
"client_id": self.client_id,
"client_secret": self.client_secret
}
r = requests.post(url, data=data)
r.raise_for_status()
j = r.json()
self.access_token = j['access_token']
self.refresh_token = j['refresh_token']
self._set_token_expiration_time(expires_in=j['expires_in'])
return r
@authenticated
def get_service_locations(self):
"""
Request service locations
Returns
-------
dict
"""
url = URLS['servicelocation']
headers = {"Authorization": "Bearer {}".format(self.access_token)}
r = requests.get(url, headers=headers)
r.raise_for_status()
return r.json()
@authenticated
def get_service_location_info(self, service_location_id):
"""
Request service location info
Parameters
----------
service_location_id : int
Returns
-------
dict
"""
url = urljoin(URLS['servicelocation'], service_location_id, "info")
headers = {"Authorization": "Bearer {}".format(self.access_token)}
r = requests.get(url, headers=headers)
r.raise_for_status()
return r.json()
@authenticated
def get_consumption(self, service_location_id, start, end, aggregation, raw=False):
"""
Request Elektricity consumption and Solar production
for a given service location.
Parameters
----------
service_location_id : int
start : int | dt.datetime | pd.Timestamp
end : int | dt.datetime | pd.Timestamp
start and end support epoch (in milliseconds),
datetime and Pandas Timestamp
aggregation : int
1 = 5 min values (only available for the last 14 days)
2 = hourly values
3 = daily values
4 = monthly values
5 = quarterly values
raw : bool
default False
if True: Return the data "as is" from the server
if False: convert the 'alwaysOn' value to Wh.
(the server returns this value as the sum of the power,
measured in 5 minute blocks. This means that it is 12 times
higher than the consumption in Wh.
See https://github.com/EnergieID/smappy/issues/24)
Returns
-------
dict
"""
url = urljoin(URLS['servicelocation'], service_location_id,
"consumption")
d = self._get_consumption(url=url, start=start, end=end,
aggregation=aggregation)
if not raw:
for block in d['consumptions']:
if 'alwaysOn' not in block.keys():
break
block.update({'alwaysOn': block['alwaysOn'] / 12})
return d
@authenticated
def get_sensor_consumption(self, service_location_id, sensor_id, start,
end, aggregation):
"""
Request consumption for a given sensor in a given service location
Parameters
----------
service_location_id : int
sensor_id : int
start : int | dt.datetime | pd.Timestamp
end : int | dt.datetime | pd.Timestamp
start and end support epoch (in milliseconds),
datetime and Pandas Timestamp
timezone-naive datetimes are assumed to be in UTC
aggregation : int
1 = 5 min values (only available for the last 14 days)
2 = hourly values
3 = daily values
4 = monthly values
5 = quarterly values
Returns
-------
dict
"""
url = urljoin(URLS['servicelocation'], service_location_id, "sensor",
sensor_id, "consumption")
return self._get_consumption(url=url, start=start, end=end,
aggregation=aggregation)
def _get_consumption(self, url, start, end, aggregation):
"""
Request for both the get_consumption and
get_sensor_consumption methods.
Parameters
----------
url : str
start : dt.datetime
end : dt.datetime
aggregation : int
Returns
-------
dict
"""
start = self._to_milliseconds(start)
end = self._to_milliseconds(end)
headers = {"Authorization": "Bearer {}".format(self.access_token)}
params = {
"aggregation": aggregation,
"from": start,
"to": end
}
r = requests.get(url, headers=headers, params=params)
r.raise_for_status()
return r.json()
@authenticated
def get_events(self, service_location_id, appliance_id, start, end,
max_number=None):
"""
Request events for a given appliance
Parameters
----------
service_location_id : int
appliance_id : int
start : int | dt.datetime | pd.Timestamp
end : int | dt.datetime | pd.Timestamp
start and end support epoch (in milliseconds),
datetime and Pandas Timestamp
timezone-naive datetimes are assumed to be in UTC
max_number : int, optional
The maximum number of events that should be returned by this query
Default returns all events in the selected period
Returns
-------
dict
"""
start = self._to_milliseconds(start)
end = self._to_milliseconds(end)
url = urljoin(URLS['servicelocation'], service_location_id, "events")
headers = {"Authorization": "Bearer {}".format(self.access_token)}
params = {
"from": start,
"to": end,
"applianceId": appliance_id,
"maxNumber": max_number
}
r = requests.get(url, headers=headers, params=params)
r.raise_for_status()
return r.json()
@authenticated
@authenticated
def actuator_off(self, service_location_id, actuator_id, duration=None):
"""
Turn actuator off
Parameters
----------
service_location_id : int
actuator_id : int
duration : int, optional
300,900,1800 or 3600 , specifying the time in seconds the actuator
should be turned on. Any other value results in turning on for an
undetermined period of time.
Returns
-------
requests.Response
"""
return self._actuator_on_off(
on_off='off', service_location_id=service_location_id,
actuator_id=actuator_id, duration=duration)
def _actuator_on_off(self, on_off, service_location_id, actuator_id,
duration=None):
"""
Turn actuator on or off
Parameters
----------
on_off : str
'on' or 'off'
service_location_id : int
actuator_id : int
duration : int, optional
300,900,1800 or 3600 , specifying the time in seconds the actuator
should be turned on. Any other value results in turning on for an
undetermined period of time.
Returns
-------
requests.Response
"""
url = urljoin(URLS['servicelocation'], service_location_id,
"actuator", actuator_id, on_off)
headers = {"Authorization": "Bearer {}".format(self.access_token)}
if duration is not None:
data = {"duration": duration}
else:
data = {}
r = requests.post(url, headers=headers, json=data)
r.raise_for_status()
return r
def get_consumption_dataframe(self, service_location_id, start, end,
aggregation, sensor_id=None, localize=False,
raw=False):
"""
Extends get_consumption() AND get_sensor_consumption(),
parses the results in a Pandas DataFrame
Parameters
----------
service_location_id : int
start : dt.datetime | int
end : dt.datetime | int
timezone-naive datetimes are assumed to be in UTC
epoch timestamps need to be in milliseconds
aggregation : int
sensor_id : int, optional
If a sensor id is passed, api method get_sensor_consumption will
be used otherwise (by default),
the get_consumption method will be used: this returns Electricity
and Solar consumption and production.
localize : bool
default False
default returns timestamps in UTC
if True, timezone is fetched from service location info and
Data Frame is localized
raw : bool
default False
if True: Return the data "as is" from the server
if False: convert the 'alwaysOn' value to Wh.
(the server returns this value as the sum of the power,
measured in 5 minute blocks. This means that it is 12 times
higher than the consumption in Wh.
See https://github.com/EnergieID/smappy/issues/24)
Returns
-------
pd.DataFrame
"""
import pandas as pd
if sensor_id is None:
data = self.get_consumption(
service_location_id=service_location_id, start=start,
end=end, aggregation=aggregation, raw=raw)
consumptions = data['consumptions']
else:
data = self.get_sensor_consumption(
service_location_id=service_location_id, sensor_id=sensor_id,
start=start, end=end, aggregation=aggregation)
# yeah please someone explain me why they had to name this
# differently...
consumptions = data['records']
df = pd.DataFrame.from_dict(consumptions)
if not df.empty:
df.set_index('timestamp', inplace=True)
df.index = pd.to_datetime(df.index, unit='ms', utc=True)
if localize:
info = self.get_service_location_info(
service_location_id=service_location_id)
timezone = info['timezone']
df = df.tz_convert(timezone)
return df
def _to_milliseconds(self, time):
"""
Converts a datetime-like object to epoch, in milliseconds
Timezone-naive datetime objects are assumed to be in UTC
Parameters
----------
time : dt.datetime | pd.Timestamp | int
Returns
-------
int
epoch milliseconds
"""
if isinstance(time, dt.datetime):
if time.tzinfo is None:
time = time.replace(tzinfo=pytz.UTC)
return int(time.timestamp() * 1e3)
elif isinstance(time, numbers.Number):
return time
else:
raise NotImplementedError("Time format not supported. Use milliseconds since epoch,\
Datetime or Pandas Datetime")
|
EnergieID/smappy | smappy/smappy.py | Smappee.actuator_off | python | def actuator_off(self, service_location_id, actuator_id, duration=None):
return self._actuator_on_off(
on_off='off', service_location_id=service_location_id,
actuator_id=actuator_id, duration=duration) | Turn actuator off
Parameters
----------
service_location_id : int
actuator_id : int
duration : int, optional
300,900,1800 or 3600 , specifying the time in seconds the actuator
should be turned on. Any other value results in turning on for an
undetermined period of time.
Returns
-------
requests.Response | train | https://github.com/EnergieID/smappy/blob/1ada3abc9a51c76205c072369258f6f4f4e8fd0f/smappy/smappy.py#L336-L355 | [
"def _actuator_on_off(self, on_off, service_location_id, actuator_id,\n duration=None):\n \"\"\"\n Turn actuator on or off\n\n Parameters\n ----------\n on_off : str\n 'on' or 'off'\n service_location_id : int\n actuator_id : int\n duration : int, optional\n ... | class Smappee(object):
"""
Object containing Smappee's API-methods.
See https://smappee.atlassian.net/wiki/display/DEVAPI/API+Methods
"""
def __init__(self, client_id=None, client_secret=None):
"""
To receive a client id and secret,
you need to request via the Smappee support
Parameters
----------
client_id : str, optional
client_secret : str, optional
If None, you won't be able to do any authorisation,
so it requires that you already have an access token somewhere.
In that case, the SimpleSmappee class is something for you.
"""
self.client_id = client_id
self.client_secret = client_secret
self.access_token = None
self.refresh_token = None
self.token_expiration_time = None
def authenticate(self, username, password):
"""
Uses a Smappee username and password to request an access token,
refresh token and expiry date.
Parameters
----------
username : str
password : str
Returns
-------
requests.Response
access token is saved in self.access_token
refresh token is saved in self.refresh_token
expiration time is set in self.token_expiration_time as
datetime.datetime
"""
url = URLS['token']
data = {
"grant_type": "password",
"client_id": self.client_id,
"client_secret": self.client_secret,
"username": username,
"password": password
}
r = requests.post(url, data=data)
r.raise_for_status()
j = r.json()
self.access_token = j['access_token']
self.refresh_token = j['refresh_token']
self._set_token_expiration_time(expires_in=j['expires_in'])
return r
def _set_token_expiration_time(self, expires_in):
"""
Saves the token expiration time by adding the 'expires in' parameter
to the current datetime (in utc).
Parameters
----------
expires_in : int
number of seconds from the time of the request until expiration
Returns
-------
nothing
saves expiration time in self.token_expiration_time as
datetime.datetime
"""
self.token_expiration_time = dt.datetime.utcnow() + \
dt.timedelta(0, expires_in) # timedelta(days, seconds)
def re_authenticate(self):
"""
Uses the refresh token to request a new access token, refresh token and
expiration date.
Returns
-------
requests.Response
access token is saved in self.access_token
refresh token is saved in self.refresh_token
expiration time is set in self.token_expiration_time as
datetime.datetime
"""
url = URLS['token']
data = {
"grant_type": "refresh_token",
"refresh_token": self.refresh_token,
"client_id": self.client_id,
"client_secret": self.client_secret
}
r = requests.post(url, data=data)
r.raise_for_status()
j = r.json()
self.access_token = j['access_token']
self.refresh_token = j['refresh_token']
self._set_token_expiration_time(expires_in=j['expires_in'])
return r
@authenticated
def get_service_locations(self):
"""
Request service locations
Returns
-------
dict
"""
url = URLS['servicelocation']
headers = {"Authorization": "Bearer {}".format(self.access_token)}
r = requests.get(url, headers=headers)
r.raise_for_status()
return r.json()
@authenticated
def get_service_location_info(self, service_location_id):
"""
Request service location info
Parameters
----------
service_location_id : int
Returns
-------
dict
"""
url = urljoin(URLS['servicelocation'], service_location_id, "info")
headers = {"Authorization": "Bearer {}".format(self.access_token)}
r = requests.get(url, headers=headers)
r.raise_for_status()
return r.json()
@authenticated
def get_consumption(self, service_location_id, start, end, aggregation, raw=False):
"""
Request Elektricity consumption and Solar production
for a given service location.
Parameters
----------
service_location_id : int
start : int | dt.datetime | pd.Timestamp
end : int | dt.datetime | pd.Timestamp
start and end support epoch (in milliseconds),
datetime and Pandas Timestamp
aggregation : int
1 = 5 min values (only available for the last 14 days)
2 = hourly values
3 = daily values
4 = monthly values
5 = quarterly values
raw : bool
default False
if True: Return the data "as is" from the server
if False: convert the 'alwaysOn' value to Wh.
(the server returns this value as the sum of the power,
measured in 5 minute blocks. This means that it is 12 times
higher than the consumption in Wh.
See https://github.com/EnergieID/smappy/issues/24)
Returns
-------
dict
"""
url = urljoin(URLS['servicelocation'], service_location_id,
"consumption")
d = self._get_consumption(url=url, start=start, end=end,
aggregation=aggregation)
if not raw:
for block in d['consumptions']:
if 'alwaysOn' not in block.keys():
break
block.update({'alwaysOn': block['alwaysOn'] / 12})
return d
@authenticated
def get_sensor_consumption(self, service_location_id, sensor_id, start,
end, aggregation):
"""
Request consumption for a given sensor in a given service location
Parameters
----------
service_location_id : int
sensor_id : int
start : int | dt.datetime | pd.Timestamp
end : int | dt.datetime | pd.Timestamp
start and end support epoch (in milliseconds),
datetime and Pandas Timestamp
timezone-naive datetimes are assumed to be in UTC
aggregation : int
1 = 5 min values (only available for the last 14 days)
2 = hourly values
3 = daily values
4 = monthly values
5 = quarterly values
Returns
-------
dict
"""
url = urljoin(URLS['servicelocation'], service_location_id, "sensor",
sensor_id, "consumption")
return self._get_consumption(url=url, start=start, end=end,
aggregation=aggregation)
def _get_consumption(self, url, start, end, aggregation):
"""
Request for both the get_consumption and
get_sensor_consumption methods.
Parameters
----------
url : str
start : dt.datetime
end : dt.datetime
aggregation : int
Returns
-------
dict
"""
start = self._to_milliseconds(start)
end = self._to_milliseconds(end)
headers = {"Authorization": "Bearer {}".format(self.access_token)}
params = {
"aggregation": aggregation,
"from": start,
"to": end
}
r = requests.get(url, headers=headers, params=params)
r.raise_for_status()
return r.json()
@authenticated
def get_events(self, service_location_id, appliance_id, start, end,
max_number=None):
"""
Request events for a given appliance
Parameters
----------
service_location_id : int
appliance_id : int
start : int | dt.datetime | pd.Timestamp
end : int | dt.datetime | pd.Timestamp
start and end support epoch (in milliseconds),
datetime and Pandas Timestamp
timezone-naive datetimes are assumed to be in UTC
max_number : int, optional
The maximum number of events that should be returned by this query
Default returns all events in the selected period
Returns
-------
dict
"""
start = self._to_milliseconds(start)
end = self._to_milliseconds(end)
url = urljoin(URLS['servicelocation'], service_location_id, "events")
headers = {"Authorization": "Bearer {}".format(self.access_token)}
params = {
"from": start,
"to": end,
"applianceId": appliance_id,
"maxNumber": max_number
}
r = requests.get(url, headers=headers, params=params)
r.raise_for_status()
return r.json()
@authenticated
def actuator_on(self, service_location_id, actuator_id, duration=None):
"""
Turn actuator on
Parameters
----------
service_location_id : int
actuator_id : int
duration : int, optional
300,900,1800 or 3600 , specifying the time in seconds the actuator
should be turned on. Any other value results in turning on for an
undetermined period of time.
Returns
-------
requests.Response
"""
return self._actuator_on_off(
on_off='on', service_location_id=service_location_id,
actuator_id=actuator_id, duration=duration)
@authenticated
def _actuator_on_off(self, on_off, service_location_id, actuator_id,
duration=None):
"""
Turn actuator on or off
Parameters
----------
on_off : str
'on' or 'off'
service_location_id : int
actuator_id : int
duration : int, optional
300,900,1800 or 3600 , specifying the time in seconds the actuator
should be turned on. Any other value results in turning on for an
undetermined period of time.
Returns
-------
requests.Response
"""
url = urljoin(URLS['servicelocation'], service_location_id,
"actuator", actuator_id, on_off)
headers = {"Authorization": "Bearer {}".format(self.access_token)}
if duration is not None:
data = {"duration": duration}
else:
data = {}
r = requests.post(url, headers=headers, json=data)
r.raise_for_status()
return r
def get_consumption_dataframe(self, service_location_id, start, end,
aggregation, sensor_id=None, localize=False,
raw=False):
"""
Extends get_consumption() AND get_sensor_consumption(),
parses the results in a Pandas DataFrame
Parameters
----------
service_location_id : int
start : dt.datetime | int
end : dt.datetime | int
timezone-naive datetimes are assumed to be in UTC
epoch timestamps need to be in milliseconds
aggregation : int
sensor_id : int, optional
If a sensor id is passed, api method get_sensor_consumption will
be used otherwise (by default),
the get_consumption method will be used: this returns Electricity
and Solar consumption and production.
localize : bool
default False
default returns timestamps in UTC
if True, timezone is fetched from service location info and
Data Frame is localized
raw : bool
default False
if True: Return the data "as is" from the server
if False: convert the 'alwaysOn' value to Wh.
(the server returns this value as the sum of the power,
measured in 5 minute blocks. This means that it is 12 times
higher than the consumption in Wh.
See https://github.com/EnergieID/smappy/issues/24)
Returns
-------
pd.DataFrame
"""
import pandas as pd
if sensor_id is None:
data = self.get_consumption(
service_location_id=service_location_id, start=start,
end=end, aggregation=aggregation, raw=raw)
consumptions = data['consumptions']
else:
data = self.get_sensor_consumption(
service_location_id=service_location_id, sensor_id=sensor_id,
start=start, end=end, aggregation=aggregation)
# yeah please someone explain me why they had to name this
# differently...
consumptions = data['records']
df = pd.DataFrame.from_dict(consumptions)
if not df.empty:
df.set_index('timestamp', inplace=True)
df.index = pd.to_datetime(df.index, unit='ms', utc=True)
if localize:
info = self.get_service_location_info(
service_location_id=service_location_id)
timezone = info['timezone']
df = df.tz_convert(timezone)
return df
def _to_milliseconds(self, time):
"""
Converts a datetime-like object to epoch, in milliseconds
Timezone-naive datetime objects are assumed to be in UTC
Parameters
----------
time : dt.datetime | pd.Timestamp | int
Returns
-------
int
epoch milliseconds
"""
if isinstance(time, dt.datetime):
if time.tzinfo is None:
time = time.replace(tzinfo=pytz.UTC)
return int(time.timestamp() * 1e3)
elif isinstance(time, numbers.Number):
return time
else:
raise NotImplementedError("Time format not supported. Use milliseconds since epoch,\
Datetime or Pandas Datetime")
|
EnergieID/smappy | smappy/smappy.py | Smappee._actuator_on_off | python | def _actuator_on_off(self, on_off, service_location_id, actuator_id,
duration=None):
url = urljoin(URLS['servicelocation'], service_location_id,
"actuator", actuator_id, on_off)
headers = {"Authorization": "Bearer {}".format(self.access_token)}
if duration is not None:
data = {"duration": duration}
else:
data = {}
r = requests.post(url, headers=headers, json=data)
r.raise_for_status()
return r | Turn actuator on or off
Parameters
----------
on_off : str
'on' or 'off'
service_location_id : int
actuator_id : int
duration : int, optional
300,900,1800 or 3600 , specifying the time in seconds the actuator
should be turned on. Any other value results in turning on for an
undetermined period of time.
Returns
-------
requests.Response | train | https://github.com/EnergieID/smappy/blob/1ada3abc9a51c76205c072369258f6f4f4e8fd0f/smappy/smappy.py#L357-L386 | [
"def urljoin(*parts):\n \"\"\"\n Join terms together with forward slashes\n\n Parameters\n ----------\n parts\n\n Returns\n -------\n str\n \"\"\"\n # first strip extra forward slashes (except http:// and the likes) and\n # create list\n part_list = []\n for part in parts:\n ... | class Smappee(object):
"""
Object containing Smappee's API-methods.
See https://smappee.atlassian.net/wiki/display/DEVAPI/API+Methods
"""
def __init__(self, client_id=None, client_secret=None):
"""
To receive a client id and secret,
you need to request via the Smappee support
Parameters
----------
client_id : str, optional
client_secret : str, optional
If None, you won't be able to do any authorisation,
so it requires that you already have an access token somewhere.
In that case, the SimpleSmappee class is something for you.
"""
self.client_id = client_id
self.client_secret = client_secret
self.access_token = None
self.refresh_token = None
self.token_expiration_time = None
def authenticate(self, username, password):
"""
Uses a Smappee username and password to request an access token,
refresh token and expiry date.
Parameters
----------
username : str
password : str
Returns
-------
requests.Response
access token is saved in self.access_token
refresh token is saved in self.refresh_token
expiration time is set in self.token_expiration_time as
datetime.datetime
"""
url = URLS['token']
data = {
"grant_type": "password",
"client_id": self.client_id,
"client_secret": self.client_secret,
"username": username,
"password": password
}
r = requests.post(url, data=data)
r.raise_for_status()
j = r.json()
self.access_token = j['access_token']
self.refresh_token = j['refresh_token']
self._set_token_expiration_time(expires_in=j['expires_in'])
return r
def _set_token_expiration_time(self, expires_in):
"""
Saves the token expiration time by adding the 'expires in' parameter
to the current datetime (in utc).
Parameters
----------
expires_in : int
number of seconds from the time of the request until expiration
Returns
-------
nothing
saves expiration time in self.token_expiration_time as
datetime.datetime
"""
self.token_expiration_time = dt.datetime.utcnow() + \
dt.timedelta(0, expires_in) # timedelta(days, seconds)
def re_authenticate(self):
"""
Uses the refresh token to request a new access token, refresh token and
expiration date.
Returns
-------
requests.Response
access token is saved in self.access_token
refresh token is saved in self.refresh_token
expiration time is set in self.token_expiration_time as
datetime.datetime
"""
url = URLS['token']
data = {
"grant_type": "refresh_token",
"refresh_token": self.refresh_token,
"client_id": self.client_id,
"client_secret": self.client_secret
}
r = requests.post(url, data=data)
r.raise_for_status()
j = r.json()
self.access_token = j['access_token']
self.refresh_token = j['refresh_token']
self._set_token_expiration_time(expires_in=j['expires_in'])
return r
@authenticated
def get_service_locations(self):
"""
Request service locations
Returns
-------
dict
"""
url = URLS['servicelocation']
headers = {"Authorization": "Bearer {}".format(self.access_token)}
r = requests.get(url, headers=headers)
r.raise_for_status()
return r.json()
@authenticated
def get_service_location_info(self, service_location_id):
"""
Request service location info
Parameters
----------
service_location_id : int
Returns
-------
dict
"""
url = urljoin(URLS['servicelocation'], service_location_id, "info")
headers = {"Authorization": "Bearer {}".format(self.access_token)}
r = requests.get(url, headers=headers)
r.raise_for_status()
return r.json()
@authenticated
def get_consumption(self, service_location_id, start, end, aggregation, raw=False):
"""
Request Elektricity consumption and Solar production
for a given service location.
Parameters
----------
service_location_id : int
start : int | dt.datetime | pd.Timestamp
end : int | dt.datetime | pd.Timestamp
start and end support epoch (in milliseconds),
datetime and Pandas Timestamp
aggregation : int
1 = 5 min values (only available for the last 14 days)
2 = hourly values
3 = daily values
4 = monthly values
5 = quarterly values
raw : bool
default False
if True: Return the data "as is" from the server
if False: convert the 'alwaysOn' value to Wh.
(the server returns this value as the sum of the power,
measured in 5 minute blocks. This means that it is 12 times
higher than the consumption in Wh.
See https://github.com/EnergieID/smappy/issues/24)
Returns
-------
dict
"""
url = urljoin(URLS['servicelocation'], service_location_id,
"consumption")
d = self._get_consumption(url=url, start=start, end=end,
aggregation=aggregation)
if not raw:
for block in d['consumptions']:
if 'alwaysOn' not in block.keys():
break
block.update({'alwaysOn': block['alwaysOn'] / 12})
return d
@authenticated
def get_sensor_consumption(self, service_location_id, sensor_id, start,
end, aggregation):
"""
Request consumption for a given sensor in a given service location
Parameters
----------
service_location_id : int
sensor_id : int
start : int | dt.datetime | pd.Timestamp
end : int | dt.datetime | pd.Timestamp
start and end support epoch (in milliseconds),
datetime and Pandas Timestamp
timezone-naive datetimes are assumed to be in UTC
aggregation : int
1 = 5 min values (only available for the last 14 days)
2 = hourly values
3 = daily values
4 = monthly values
5 = quarterly values
Returns
-------
dict
"""
url = urljoin(URLS['servicelocation'], service_location_id, "sensor",
sensor_id, "consumption")
return self._get_consumption(url=url, start=start, end=end,
aggregation=aggregation)
def _get_consumption(self, url, start, end, aggregation):
"""
Request for both the get_consumption and
get_sensor_consumption methods.
Parameters
----------
url : str
start : dt.datetime
end : dt.datetime
aggregation : int
Returns
-------
dict
"""
start = self._to_milliseconds(start)
end = self._to_milliseconds(end)
headers = {"Authorization": "Bearer {}".format(self.access_token)}
params = {
"aggregation": aggregation,
"from": start,
"to": end
}
r = requests.get(url, headers=headers, params=params)
r.raise_for_status()
return r.json()
@authenticated
def get_events(self, service_location_id, appliance_id, start, end,
max_number=None):
"""
Request events for a given appliance
Parameters
----------
service_location_id : int
appliance_id : int
start : int | dt.datetime | pd.Timestamp
end : int | dt.datetime | pd.Timestamp
start and end support epoch (in milliseconds),
datetime and Pandas Timestamp
timezone-naive datetimes are assumed to be in UTC
max_number : int, optional
The maximum number of events that should be returned by this query
Default returns all events in the selected period
Returns
-------
dict
"""
start = self._to_milliseconds(start)
end = self._to_milliseconds(end)
url = urljoin(URLS['servicelocation'], service_location_id, "events")
headers = {"Authorization": "Bearer {}".format(self.access_token)}
params = {
"from": start,
"to": end,
"applianceId": appliance_id,
"maxNumber": max_number
}
r = requests.get(url, headers=headers, params=params)
r.raise_for_status()
return r.json()
@authenticated
def actuator_on(self, service_location_id, actuator_id, duration=None):
"""
Turn actuator on
Parameters
----------
service_location_id : int
actuator_id : int
duration : int, optional
300,900,1800 or 3600 , specifying the time in seconds the actuator
should be turned on. Any other value results in turning on for an
undetermined period of time.
Returns
-------
requests.Response
"""
return self._actuator_on_off(
on_off='on', service_location_id=service_location_id,
actuator_id=actuator_id, duration=duration)
@authenticated
def actuator_off(self, service_location_id, actuator_id, duration=None):
"""
Turn actuator off
Parameters
----------
service_location_id : int
actuator_id : int
duration : int, optional
300,900,1800 or 3600 , specifying the time in seconds the actuator
should be turned on. Any other value results in turning on for an
undetermined period of time.
Returns
-------
requests.Response
"""
return self._actuator_on_off(
on_off='off', service_location_id=service_location_id,
actuator_id=actuator_id, duration=duration)
def get_consumption_dataframe(self, service_location_id, start, end,
aggregation, sensor_id=None, localize=False,
raw=False):
"""
Extends get_consumption() AND get_sensor_consumption(),
parses the results in a Pandas DataFrame
Parameters
----------
service_location_id : int
start : dt.datetime | int
end : dt.datetime | int
timezone-naive datetimes are assumed to be in UTC
epoch timestamps need to be in milliseconds
aggregation : int
sensor_id : int, optional
If a sensor id is passed, api method get_sensor_consumption will
be used otherwise (by default),
the get_consumption method will be used: this returns Electricity
and Solar consumption and production.
localize : bool
default False
default returns timestamps in UTC
if True, timezone is fetched from service location info and
Data Frame is localized
raw : bool
default False
if True: Return the data "as is" from the server
if False: convert the 'alwaysOn' value to Wh.
(the server returns this value as the sum of the power,
measured in 5 minute blocks. This means that it is 12 times
higher than the consumption in Wh.
See https://github.com/EnergieID/smappy/issues/24)
Returns
-------
pd.DataFrame
"""
import pandas as pd
if sensor_id is None:
data = self.get_consumption(
service_location_id=service_location_id, start=start,
end=end, aggregation=aggregation, raw=raw)
consumptions = data['consumptions']
else:
data = self.get_sensor_consumption(
service_location_id=service_location_id, sensor_id=sensor_id,
start=start, end=end, aggregation=aggregation)
# yeah please someone explain me why they had to name this
# differently...
consumptions = data['records']
df = pd.DataFrame.from_dict(consumptions)
if not df.empty:
df.set_index('timestamp', inplace=True)
df.index = pd.to_datetime(df.index, unit='ms', utc=True)
if localize:
info = self.get_service_location_info(
service_location_id=service_location_id)
timezone = info['timezone']
df = df.tz_convert(timezone)
return df
def _to_milliseconds(self, time):
"""
Converts a datetime-like object to epoch, in milliseconds
Timezone-naive datetime objects are assumed to be in UTC
Parameters
----------
time : dt.datetime | pd.Timestamp | int
Returns
-------
int
epoch milliseconds
"""
if isinstance(time, dt.datetime):
if time.tzinfo is None:
time = time.replace(tzinfo=pytz.UTC)
return int(time.timestamp() * 1e3)
elif isinstance(time, numbers.Number):
return time
else:
raise NotImplementedError("Time format not supported. Use milliseconds since epoch,\
Datetime or Pandas Datetime")
|
EnergieID/smappy | smappy/smappy.py | Smappee.get_consumption_dataframe | python | def get_consumption_dataframe(self, service_location_id, start, end,
aggregation, sensor_id=None, localize=False,
raw=False):
import pandas as pd
if sensor_id is None:
data = self.get_consumption(
service_location_id=service_location_id, start=start,
end=end, aggregation=aggregation, raw=raw)
consumptions = data['consumptions']
else:
data = self.get_sensor_consumption(
service_location_id=service_location_id, sensor_id=sensor_id,
start=start, end=end, aggregation=aggregation)
# yeah please someone explain me why they had to name this
# differently...
consumptions = data['records']
df = pd.DataFrame.from_dict(consumptions)
if not df.empty:
df.set_index('timestamp', inplace=True)
df.index = pd.to_datetime(df.index, unit='ms', utc=True)
if localize:
info = self.get_service_location_info(
service_location_id=service_location_id)
timezone = info['timezone']
df = df.tz_convert(timezone)
return df | Extends get_consumption() AND get_sensor_consumption(),
parses the results in a Pandas DataFrame
Parameters
----------
service_location_id : int
start : dt.datetime | int
end : dt.datetime | int
timezone-naive datetimes are assumed to be in UTC
epoch timestamps need to be in milliseconds
aggregation : int
sensor_id : int, optional
If a sensor id is passed, api method get_sensor_consumption will
be used otherwise (by default),
the get_consumption method will be used: this returns Electricity
and Solar consumption and production.
localize : bool
default False
default returns timestamps in UTC
if True, timezone is fetched from service location info and
Data Frame is localized
raw : bool
default False
if True: Return the data "as is" from the server
if False: convert the 'alwaysOn' value to Wh.
(the server returns this value as the sum of the power,
measured in 5 minute blocks. This means that it is 12 times
higher than the consumption in Wh.
See https://github.com/EnergieID/smappy/issues/24)
Returns
-------
pd.DataFrame | train | https://github.com/EnergieID/smappy/blob/1ada3abc9a51c76205c072369258f6f4f4e8fd0f/smappy/smappy.py#L388-L450 | null | class Smappee(object):
"""
Object containing Smappee's API-methods.
See https://smappee.atlassian.net/wiki/display/DEVAPI/API+Methods
"""
def __init__(self, client_id=None, client_secret=None):
"""
To receive a client id and secret,
you need to request via the Smappee support
Parameters
----------
client_id : str, optional
client_secret : str, optional
If None, you won't be able to do any authorisation,
so it requires that you already have an access token somewhere.
In that case, the SimpleSmappee class is something for you.
"""
self.client_id = client_id
self.client_secret = client_secret
self.access_token = None
self.refresh_token = None
self.token_expiration_time = None
def authenticate(self, username, password):
"""
Uses a Smappee username and password to request an access token,
refresh token and expiry date.
Parameters
----------
username : str
password : str
Returns
-------
requests.Response
access token is saved in self.access_token
refresh token is saved in self.refresh_token
expiration time is set in self.token_expiration_time as
datetime.datetime
"""
url = URLS['token']
data = {
"grant_type": "password",
"client_id": self.client_id,
"client_secret": self.client_secret,
"username": username,
"password": password
}
r = requests.post(url, data=data)
r.raise_for_status()
j = r.json()
self.access_token = j['access_token']
self.refresh_token = j['refresh_token']
self._set_token_expiration_time(expires_in=j['expires_in'])
return r
def _set_token_expiration_time(self, expires_in):
"""
Saves the token expiration time by adding the 'expires in' parameter
to the current datetime (in utc).
Parameters
----------
expires_in : int
number of seconds from the time of the request until expiration
Returns
-------
nothing
saves expiration time in self.token_expiration_time as
datetime.datetime
"""
self.token_expiration_time = dt.datetime.utcnow() + \
dt.timedelta(0, expires_in) # timedelta(days, seconds)
def re_authenticate(self):
"""
Uses the refresh token to request a new access token, refresh token and
expiration date.
Returns
-------
requests.Response
access token is saved in self.access_token
refresh token is saved in self.refresh_token
expiration time is set in self.token_expiration_time as
datetime.datetime
"""
url = URLS['token']
data = {
"grant_type": "refresh_token",
"refresh_token": self.refresh_token,
"client_id": self.client_id,
"client_secret": self.client_secret
}
r = requests.post(url, data=data)
r.raise_for_status()
j = r.json()
self.access_token = j['access_token']
self.refresh_token = j['refresh_token']
self._set_token_expiration_time(expires_in=j['expires_in'])
return r
@authenticated
def get_service_locations(self):
"""
Request service locations
Returns
-------
dict
"""
url = URLS['servicelocation']
headers = {"Authorization": "Bearer {}".format(self.access_token)}
r = requests.get(url, headers=headers)
r.raise_for_status()
return r.json()
@authenticated
def get_service_location_info(self, service_location_id):
"""
Request service location info
Parameters
----------
service_location_id : int
Returns
-------
dict
"""
url = urljoin(URLS['servicelocation'], service_location_id, "info")
headers = {"Authorization": "Bearer {}".format(self.access_token)}
r = requests.get(url, headers=headers)
r.raise_for_status()
return r.json()
@authenticated
def get_consumption(self, service_location_id, start, end, aggregation, raw=False):
"""
Request Elektricity consumption and Solar production
for a given service location.
Parameters
----------
service_location_id : int
start : int | dt.datetime | pd.Timestamp
end : int | dt.datetime | pd.Timestamp
start and end support epoch (in milliseconds),
datetime and Pandas Timestamp
aggregation : int
1 = 5 min values (only available for the last 14 days)
2 = hourly values
3 = daily values
4 = monthly values
5 = quarterly values
raw : bool
default False
if True: Return the data "as is" from the server
if False: convert the 'alwaysOn' value to Wh.
(the server returns this value as the sum of the power,
measured in 5 minute blocks. This means that it is 12 times
higher than the consumption in Wh.
See https://github.com/EnergieID/smappy/issues/24)
Returns
-------
dict
"""
url = urljoin(URLS['servicelocation'], service_location_id,
"consumption")
d = self._get_consumption(url=url, start=start, end=end,
aggregation=aggregation)
if not raw:
for block in d['consumptions']:
if 'alwaysOn' not in block.keys():
break
block.update({'alwaysOn': block['alwaysOn'] / 12})
return d
@authenticated
def get_sensor_consumption(self, service_location_id, sensor_id, start,
end, aggregation):
"""
Request consumption for a given sensor in a given service location
Parameters
----------
service_location_id : int
sensor_id : int
start : int | dt.datetime | pd.Timestamp
end : int | dt.datetime | pd.Timestamp
start and end support epoch (in milliseconds),
datetime and Pandas Timestamp
timezone-naive datetimes are assumed to be in UTC
aggregation : int
1 = 5 min values (only available for the last 14 days)
2 = hourly values
3 = daily values
4 = monthly values
5 = quarterly values
Returns
-------
dict
"""
url = urljoin(URLS['servicelocation'], service_location_id, "sensor",
sensor_id, "consumption")
return self._get_consumption(url=url, start=start, end=end,
aggregation=aggregation)
def _get_consumption(self, url, start, end, aggregation):
"""
Request for both the get_consumption and
get_sensor_consumption methods.
Parameters
----------
url : str
start : dt.datetime
end : dt.datetime
aggregation : int
Returns
-------
dict
"""
start = self._to_milliseconds(start)
end = self._to_milliseconds(end)
headers = {"Authorization": "Bearer {}".format(self.access_token)}
params = {
"aggregation": aggregation,
"from": start,
"to": end
}
r = requests.get(url, headers=headers, params=params)
r.raise_for_status()
return r.json()
@authenticated
def get_events(self, service_location_id, appliance_id, start, end,
max_number=None):
"""
Request events for a given appliance
Parameters
----------
service_location_id : int
appliance_id : int
start : int | dt.datetime | pd.Timestamp
end : int | dt.datetime | pd.Timestamp
start and end support epoch (in milliseconds),
datetime and Pandas Timestamp
timezone-naive datetimes are assumed to be in UTC
max_number : int, optional
The maximum number of events that should be returned by this query
Default returns all events in the selected period
Returns
-------
dict
"""
start = self._to_milliseconds(start)
end = self._to_milliseconds(end)
url = urljoin(URLS['servicelocation'], service_location_id, "events")
headers = {"Authorization": "Bearer {}".format(self.access_token)}
params = {
"from": start,
"to": end,
"applianceId": appliance_id,
"maxNumber": max_number
}
r = requests.get(url, headers=headers, params=params)
r.raise_for_status()
return r.json()
@authenticated
def actuator_on(self, service_location_id, actuator_id, duration=None):
"""
Turn actuator on
Parameters
----------
service_location_id : int
actuator_id : int
duration : int, optional
300,900,1800 or 3600 , specifying the time in seconds the actuator
should be turned on. Any other value results in turning on for an
undetermined period of time.
Returns
-------
requests.Response
"""
return self._actuator_on_off(
on_off='on', service_location_id=service_location_id,
actuator_id=actuator_id, duration=duration)
@authenticated
def actuator_off(self, service_location_id, actuator_id, duration=None):
"""
Turn actuator off
Parameters
----------
service_location_id : int
actuator_id : int
duration : int, optional
300,900,1800 or 3600 , specifying the time in seconds the actuator
should be turned on. Any other value results in turning on for an
undetermined period of time.
Returns
-------
requests.Response
"""
return self._actuator_on_off(
on_off='off', service_location_id=service_location_id,
actuator_id=actuator_id, duration=duration)
def _actuator_on_off(self, on_off, service_location_id, actuator_id,
duration=None):
"""
Turn actuator on or off
Parameters
----------
on_off : str
'on' or 'off'
service_location_id : int
actuator_id : int
duration : int, optional
300,900,1800 or 3600 , specifying the time in seconds the actuator
should be turned on. Any other value results in turning on for an
undetermined period of time.
Returns
-------
requests.Response
"""
url = urljoin(URLS['servicelocation'], service_location_id,
"actuator", actuator_id, on_off)
headers = {"Authorization": "Bearer {}".format(self.access_token)}
if duration is not None:
data = {"duration": duration}
else:
data = {}
r = requests.post(url, headers=headers, json=data)
r.raise_for_status()
return r
def _to_milliseconds(self, time):
"""
Converts a datetime-like object to epoch, in milliseconds
Timezone-naive datetime objects are assumed to be in UTC
Parameters
----------
time : dt.datetime | pd.Timestamp | int
Returns
-------
int
epoch milliseconds
"""
if isinstance(time, dt.datetime):
if time.tzinfo is None:
time = time.replace(tzinfo=pytz.UTC)
return int(time.timestamp() * 1e3)
elif isinstance(time, numbers.Number):
return time
else:
raise NotImplementedError("Time format not supported. Use milliseconds since epoch,\
Datetime or Pandas Datetime")
|
EnergieID/smappy | smappy/smappy.py | Smappee._to_milliseconds | python | def _to_milliseconds(self, time):
if isinstance(time, dt.datetime):
if time.tzinfo is None:
time = time.replace(tzinfo=pytz.UTC)
return int(time.timestamp() * 1e3)
elif isinstance(time, numbers.Number):
return time
else:
raise NotImplementedError("Time format not supported. Use milliseconds since epoch,\
Datetime or Pandas Datetime") | Converts a datetime-like object to epoch, in milliseconds
Timezone-naive datetime objects are assumed to be in UTC
Parameters
----------
time : dt.datetime | pd.Timestamp | int
Returns
-------
int
epoch milliseconds | train | https://github.com/EnergieID/smappy/blob/1ada3abc9a51c76205c072369258f6f4f4e8fd0f/smappy/smappy.py#L452-L474 | null | class Smappee(object):
"""
Object containing Smappee's API-methods.
See https://smappee.atlassian.net/wiki/display/DEVAPI/API+Methods
"""
def __init__(self, client_id=None, client_secret=None):
"""
To receive a client id and secret,
you need to request via the Smappee support
Parameters
----------
client_id : str, optional
client_secret : str, optional
If None, you won't be able to do any authorisation,
so it requires that you already have an access token somewhere.
In that case, the SimpleSmappee class is something for you.
"""
self.client_id = client_id
self.client_secret = client_secret
self.access_token = None
self.refresh_token = None
self.token_expiration_time = None
def authenticate(self, username, password):
"""
Uses a Smappee username and password to request an access token,
refresh token and expiry date.
Parameters
----------
username : str
password : str
Returns
-------
requests.Response
access token is saved in self.access_token
refresh token is saved in self.refresh_token
expiration time is set in self.token_expiration_time as
datetime.datetime
"""
url = URLS['token']
data = {
"grant_type": "password",
"client_id": self.client_id,
"client_secret": self.client_secret,
"username": username,
"password": password
}
r = requests.post(url, data=data)
r.raise_for_status()
j = r.json()
self.access_token = j['access_token']
self.refresh_token = j['refresh_token']
self._set_token_expiration_time(expires_in=j['expires_in'])
return r
def _set_token_expiration_time(self, expires_in):
"""
Saves the token expiration time by adding the 'expires in' parameter
to the current datetime (in utc).
Parameters
----------
expires_in : int
number of seconds from the time of the request until expiration
Returns
-------
nothing
saves expiration time in self.token_expiration_time as
datetime.datetime
"""
self.token_expiration_time = dt.datetime.utcnow() + \
dt.timedelta(0, expires_in) # timedelta(days, seconds)
def re_authenticate(self):
"""
Uses the refresh token to request a new access token, refresh token and
expiration date.
Returns
-------
requests.Response
access token is saved in self.access_token
refresh token is saved in self.refresh_token
expiration time is set in self.token_expiration_time as
datetime.datetime
"""
url = URLS['token']
data = {
"grant_type": "refresh_token",
"refresh_token": self.refresh_token,
"client_id": self.client_id,
"client_secret": self.client_secret
}
r = requests.post(url, data=data)
r.raise_for_status()
j = r.json()
self.access_token = j['access_token']
self.refresh_token = j['refresh_token']
self._set_token_expiration_time(expires_in=j['expires_in'])
return r
@authenticated
def get_service_locations(self):
"""
Request service locations
Returns
-------
dict
"""
url = URLS['servicelocation']
headers = {"Authorization": "Bearer {}".format(self.access_token)}
r = requests.get(url, headers=headers)
r.raise_for_status()
return r.json()
@authenticated
def get_service_location_info(self, service_location_id):
"""
Request service location info
Parameters
----------
service_location_id : int
Returns
-------
dict
"""
url = urljoin(URLS['servicelocation'], service_location_id, "info")
headers = {"Authorization": "Bearer {}".format(self.access_token)}
r = requests.get(url, headers=headers)
r.raise_for_status()
return r.json()
@authenticated
def get_consumption(self, service_location_id, start, end, aggregation, raw=False):
"""
Request Elektricity consumption and Solar production
for a given service location.
Parameters
----------
service_location_id : int
start : int | dt.datetime | pd.Timestamp
end : int | dt.datetime | pd.Timestamp
start and end support epoch (in milliseconds),
datetime and Pandas Timestamp
aggregation : int
1 = 5 min values (only available for the last 14 days)
2 = hourly values
3 = daily values
4 = monthly values
5 = quarterly values
raw : bool
default False
if True: Return the data "as is" from the server
if False: convert the 'alwaysOn' value to Wh.
(the server returns this value as the sum of the power,
measured in 5 minute blocks. This means that it is 12 times
higher than the consumption in Wh.
See https://github.com/EnergieID/smappy/issues/24)
Returns
-------
dict
"""
url = urljoin(URLS['servicelocation'], service_location_id,
"consumption")
d = self._get_consumption(url=url, start=start, end=end,
aggregation=aggregation)
if not raw:
for block in d['consumptions']:
if 'alwaysOn' not in block.keys():
break
block.update({'alwaysOn': block['alwaysOn'] / 12})
return d
@authenticated
def get_sensor_consumption(self, service_location_id, sensor_id, start,
end, aggregation):
"""
Request consumption for a given sensor in a given service location
Parameters
----------
service_location_id : int
sensor_id : int
start : int | dt.datetime | pd.Timestamp
end : int | dt.datetime | pd.Timestamp
start and end support epoch (in milliseconds),
datetime and Pandas Timestamp
timezone-naive datetimes are assumed to be in UTC
aggregation : int
1 = 5 min values (only available for the last 14 days)
2 = hourly values
3 = daily values
4 = monthly values
5 = quarterly values
Returns
-------
dict
"""
url = urljoin(URLS['servicelocation'], service_location_id, "sensor",
sensor_id, "consumption")
return self._get_consumption(url=url, start=start, end=end,
aggregation=aggregation)
def _get_consumption(self, url, start, end, aggregation):
"""
Request for both the get_consumption and
get_sensor_consumption methods.
Parameters
----------
url : str
start : dt.datetime
end : dt.datetime
aggregation : int
Returns
-------
dict
"""
start = self._to_milliseconds(start)
end = self._to_milliseconds(end)
headers = {"Authorization": "Bearer {}".format(self.access_token)}
params = {
"aggregation": aggregation,
"from": start,
"to": end
}
r = requests.get(url, headers=headers, params=params)
r.raise_for_status()
return r.json()
@authenticated
def get_events(self, service_location_id, appliance_id, start, end,
max_number=None):
"""
Request events for a given appliance
Parameters
----------
service_location_id : int
appliance_id : int
start : int | dt.datetime | pd.Timestamp
end : int | dt.datetime | pd.Timestamp
start and end support epoch (in milliseconds),
datetime and Pandas Timestamp
timezone-naive datetimes are assumed to be in UTC
max_number : int, optional
The maximum number of events that should be returned by this query
Default returns all events in the selected period
Returns
-------
dict
"""
start = self._to_milliseconds(start)
end = self._to_milliseconds(end)
url = urljoin(URLS['servicelocation'], service_location_id, "events")
headers = {"Authorization": "Bearer {}".format(self.access_token)}
params = {
"from": start,
"to": end,
"applianceId": appliance_id,
"maxNumber": max_number
}
r = requests.get(url, headers=headers, params=params)
r.raise_for_status()
return r.json()
@authenticated
def actuator_on(self, service_location_id, actuator_id, duration=None):
"""
Turn actuator on
Parameters
----------
service_location_id : int
actuator_id : int
duration : int, optional
300,900,1800 or 3600 , specifying the time in seconds the actuator
should be turned on. Any other value results in turning on for an
undetermined period of time.
Returns
-------
requests.Response
"""
return self._actuator_on_off(
on_off='on', service_location_id=service_location_id,
actuator_id=actuator_id, duration=duration)
@authenticated
def actuator_off(self, service_location_id, actuator_id, duration=None):
"""
Turn actuator off
Parameters
----------
service_location_id : int
actuator_id : int
duration : int, optional
300,900,1800 or 3600 , specifying the time in seconds the actuator
should be turned on. Any other value results in turning on for an
undetermined period of time.
Returns
-------
requests.Response
"""
return self._actuator_on_off(
on_off='off', service_location_id=service_location_id,
actuator_id=actuator_id, duration=duration)
def _actuator_on_off(self, on_off, service_location_id, actuator_id,
duration=None):
"""
Turn actuator on or off
Parameters
----------
on_off : str
'on' or 'off'
service_location_id : int
actuator_id : int
duration : int, optional
300,900,1800 or 3600 , specifying the time in seconds the actuator
should be turned on. Any other value results in turning on for an
undetermined period of time.
Returns
-------
requests.Response
"""
url = urljoin(URLS['servicelocation'], service_location_id,
"actuator", actuator_id, on_off)
headers = {"Authorization": "Bearer {}".format(self.access_token)}
if duration is not None:
data = {"duration": duration}
else:
data = {}
r = requests.post(url, headers=headers, json=data)
r.raise_for_status()
return r
def get_consumption_dataframe(self, service_location_id, start, end,
aggregation, sensor_id=None, localize=False,
raw=False):
"""
Extends get_consumption() AND get_sensor_consumption(),
parses the results in a Pandas DataFrame
Parameters
----------
service_location_id : int
start : dt.datetime | int
end : dt.datetime | int
timezone-naive datetimes are assumed to be in UTC
epoch timestamps need to be in milliseconds
aggregation : int
sensor_id : int, optional
If a sensor id is passed, api method get_sensor_consumption will
be used otherwise (by default),
the get_consumption method will be used: this returns Electricity
and Solar consumption and production.
localize : bool
default False
default returns timestamps in UTC
if True, timezone is fetched from service location info and
Data Frame is localized
raw : bool
default False
if True: Return the data "as is" from the server
if False: convert the 'alwaysOn' value to Wh.
(the server returns this value as the sum of the power,
measured in 5 minute blocks. This means that it is 12 times
higher than the consumption in Wh.
See https://github.com/EnergieID/smappy/issues/24)
Returns
-------
pd.DataFrame
"""
import pandas as pd
if sensor_id is None:
data = self.get_consumption(
service_location_id=service_location_id, start=start,
end=end, aggregation=aggregation, raw=raw)
consumptions = data['consumptions']
else:
data = self.get_sensor_consumption(
service_location_id=service_location_id, sensor_id=sensor_id,
start=start, end=end, aggregation=aggregation)
# yeah please someone explain me why they had to name this
# differently...
consumptions = data['records']
df = pd.DataFrame.from_dict(consumptions)
if not df.empty:
df.set_index('timestamp', inplace=True)
df.index = pd.to_datetime(df.index, unit='ms', utc=True)
if localize:
info = self.get_service_location_info(
service_location_id=service_location_id)
timezone = info['timezone']
df = df.tz_convert(timezone)
return df
|
EnergieID/smappy | smappy/smappy.py | LocalSmappee._basic_post | python | def _basic_post(self, url, data=None):
_url = urljoin(self.base_url, url)
r = self.session.post(_url, data=data, headers=self.headers, timeout=5)
r.raise_for_status()
return r | Because basically every post request is the same
Parameters
----------
url : str
data : str, optional
Returns
-------
requests.Response | train | https://github.com/EnergieID/smappy/blob/1ada3abc9a51c76205c072369258f6f4f4e8fd0f/smappy/smappy.py#L516-L532 | [
"def urljoin(*parts):\n \"\"\"\n Join terms together with forward slashes\n\n Parameters\n ----------\n parts\n\n Returns\n -------\n str\n \"\"\"\n # first strip extra forward slashes (except http:// and the likes) and\n # create list\n part_list = []\n for part in parts:\n ... | class LocalSmappee(object):
"""
Access a Smappee in your local network
"""
def __init__(self, ip):
"""
Parameters
----------
ip : str
local IP-address of your Smappee
"""
self.ip = ip
self.headers = {'Content-Type': 'application/json;charset=UTF-8'}
self.session = requests.Session()
@property
def base_url(self):
url = urljoin('http://', self.ip, 'gateway', 'apipublic')
return url
def _basic_get(self, url, params=None):
_url = urljoin(self.base_url, url)
r = self.session.get(_url, params=params, headers=self.headers,
timeout=5)
r.raise_for_status()
return r
def logon(self, password='admin'):
"""
Parameters
----------
password : str
default 'admin'
Returns
-------
dict
"""
r = self._basic_post(url='logon', data=password)
return r.json()
def report_instantaneous_values(self):
"""
Returns
-------
dict
"""
r = self._basic_get(url='reportInstantaneousValues')
return r.json()
def load_instantaneous(self):
"""
Returns
-------
dict
"""
r = self._basic_post(url='instantaneous', data="loadInstantaneous")
return r.json()
def active_power(self):
"""
Takes the sum of all instantaneous active power values
Returns them in kWh
Returns
-------
float
"""
inst = self.load_instantaneous()
values = [float(i['value']) for i in inst if i['key'].endswith('ActivePower')]
return sum(values) / 1000
def active_cosfi(self):
"""
Takes the average of all instantaneous cosfi values
Returns
-------
float
"""
inst = self.load_instantaneous()
values = [float(i['value']) for i in inst if i['key'].endswith('Cosfi')]
return sum(values) / len(values)
def restart(self):
"""
Returns
-------
requests.Response
"""
return self._basic_get(url='restartSmappee?action=2')
def reset_active_power_peaks(self):
"""
Returns
-------
requests.Response
"""
return self._basic_post(url='resetActivePowerPeaks')
def reset_ip_scan_cache(self):
"""
Returns
-------
requests.Response
"""
return self._basic_post(url='resetIPScanCache')
def reset_sensor_cache(self):
"""
Returns
-------
requests.Response
"""
return self._basic_post(url='resetSensorCache')
def reset_data(self):
"""
Returns
-------
requests.Response
"""
return self._basic_post(url='clearData')
def clear_appliances(self):
"""
Returns
-------
requests.Response
"""
return self._basic_post(url='clearAppliances')
def load_advanced_config(self):
"""
Returns
-------
dict
"""
r = self._basic_post(url='advancedConfigPublic', data='load')
return r.json()
def load_config(self):
"""
Returns
-------
dict
"""
r = self._basic_post(url='configPublic', data='load')
return r.json()
def save_config(self, *args, **kwargs):
"""
Parameters
----------
args
kwargs
Raises
------
NotImplementedError
"""
raise NotImplementedError("JavaScript Code can be found on "
"https://github.com/EnergyID/smappy/issues/16"
", feel free to implement it, or create an "
"issue if you have need for this function")
def load_command_control_config(self):
"""
Returns
-------
dict
"""
r = self._basic_post(url='commandControlPublic', data='load')
return r.json()
def send_group(self):
"""
Returns
-------
requests.Response
"""
return self._basic_post(url='commandControlPublic', data='controlGroup')
def on_command_control(self, val_id):
"""
Parameters
----------
val_id : str
Returns
-------
requests.Response
"""
data = "control,controlId=1|" + val_id
return self._basic_post(url='commandControlPublic', data=data)
def off_command_control(self, val_id):
"""
Parameters
----------
val_id : str
Returns
-------
requests.Response
"""
data = "control,controlId=0|" + val_id
return self._basic_post(url='commandControlPublic', data=data)
def add_command_control(self, *args, **kwargs):
"""
Parameters
----------
args
kwargs
Raises
-------
NotImplementedError
"""
raise NotImplementedError("JavaScript Code can be found on "
"https://github.com/EnergyID/smappy/issues/16"
", feel free to implement it, or create an "
"issue if you have need for this function")
def delete_command_control(self, val_id):
"""
Parameters
----------
val_id : str
Returns
-------
requests.Response
"""
data = "delete,controlId=" + val_id
return self._basic_post(url='commandControlPublic', data=data)
def delete_command_control_timers(self, val_id):
"""
Parameters
----------
val_id : str
Returns
-------
requests.Response
"""
data = "deleteTimers,controlId=" + val_id
return self._basic_post(url='commandControlPublic', data=data)
def add_command_control_timed(self, *args, **kwargs):
"""
Parameters
----------
args
kwargs
Raises
-------
NotImplementedError
"""
raise NotImplementedError("JavaScript Code can be found on "
"https://github.com/EnergyID/smappy/issues/16"
", feel free to implement it, or create an "
"issue if you have need for this function")
def load_logfiles(self):
"""
Returns
-------
dict
"""
r = self._basic_post(url='logBrowser', data='logFileList')
return r.json()
def select_logfile(self, logfile):
"""
Parameters
----------
logfile : str
Returns
-------
dict
"""
data = 'logFileSelect,' + logfile
r = self._basic_post(url='logBrowser', data=data)
return r.json()
|
EnergieID/smappy | smappy/smappy.py | LocalSmappee.logon | python | def logon(self, password='admin'):
r = self._basic_post(url='logon', data=password)
return r.json() | Parameters
----------
password : str
default 'admin'
Returns
-------
dict | train | https://github.com/EnergieID/smappy/blob/1ada3abc9a51c76205c072369258f6f4f4e8fd0f/smappy/smappy.py#L541-L553 | [
"def _basic_post(self, url, data=None):\n \"\"\"\n Because basically every post request is the same\n\n Parameters\n ----------\n url : str\n data : str, optional\n\n Returns\n -------\n requests.Response\n \"\"\"\n _url = urljoin(self.base_url, url)\n r = self.session.post(_url,... | class LocalSmappee(object):
"""
Access a Smappee in your local network
"""
def __init__(self, ip):
"""
Parameters
----------
ip : str
local IP-address of your Smappee
"""
self.ip = ip
self.headers = {'Content-Type': 'application/json;charset=UTF-8'}
self.session = requests.Session()
@property
def base_url(self):
url = urljoin('http://', self.ip, 'gateway', 'apipublic')
return url
def _basic_post(self, url, data=None):
"""
Because basically every post request is the same
Parameters
----------
url : str
data : str, optional
Returns
-------
requests.Response
"""
_url = urljoin(self.base_url, url)
r = self.session.post(_url, data=data, headers=self.headers, timeout=5)
r.raise_for_status()
return r
def _basic_get(self, url, params=None):
_url = urljoin(self.base_url, url)
r = self.session.get(_url, params=params, headers=self.headers,
timeout=5)
r.raise_for_status()
return r
def report_instantaneous_values(self):
"""
Returns
-------
dict
"""
r = self._basic_get(url='reportInstantaneousValues')
return r.json()
def load_instantaneous(self):
"""
Returns
-------
dict
"""
r = self._basic_post(url='instantaneous', data="loadInstantaneous")
return r.json()
def active_power(self):
"""
Takes the sum of all instantaneous active power values
Returns them in kWh
Returns
-------
float
"""
inst = self.load_instantaneous()
values = [float(i['value']) for i in inst if i['key'].endswith('ActivePower')]
return sum(values) / 1000
def active_cosfi(self):
"""
Takes the average of all instantaneous cosfi values
Returns
-------
float
"""
inst = self.load_instantaneous()
values = [float(i['value']) for i in inst if i['key'].endswith('Cosfi')]
return sum(values) / len(values)
def restart(self):
"""
Returns
-------
requests.Response
"""
return self._basic_get(url='restartSmappee?action=2')
def reset_active_power_peaks(self):
"""
Returns
-------
requests.Response
"""
return self._basic_post(url='resetActivePowerPeaks')
def reset_ip_scan_cache(self):
"""
Returns
-------
requests.Response
"""
return self._basic_post(url='resetIPScanCache')
def reset_sensor_cache(self):
"""
Returns
-------
requests.Response
"""
return self._basic_post(url='resetSensorCache')
def reset_data(self):
"""
Returns
-------
requests.Response
"""
return self._basic_post(url='clearData')
def clear_appliances(self):
"""
Returns
-------
requests.Response
"""
return self._basic_post(url='clearAppliances')
def load_advanced_config(self):
"""
Returns
-------
dict
"""
r = self._basic_post(url='advancedConfigPublic', data='load')
return r.json()
def load_config(self):
"""
Returns
-------
dict
"""
r = self._basic_post(url='configPublic', data='load')
return r.json()
def save_config(self, *args, **kwargs):
"""
Parameters
----------
args
kwargs
Raises
------
NotImplementedError
"""
raise NotImplementedError("JavaScript Code can be found on "
"https://github.com/EnergyID/smappy/issues/16"
", feel free to implement it, or create an "
"issue if you have need for this function")
def load_command_control_config(self):
"""
Returns
-------
dict
"""
r = self._basic_post(url='commandControlPublic', data='load')
return r.json()
def send_group(self):
"""
Returns
-------
requests.Response
"""
return self._basic_post(url='commandControlPublic', data='controlGroup')
def on_command_control(self, val_id):
"""
Parameters
----------
val_id : str
Returns
-------
requests.Response
"""
data = "control,controlId=1|" + val_id
return self._basic_post(url='commandControlPublic', data=data)
def off_command_control(self, val_id):
"""
Parameters
----------
val_id : str
Returns
-------
requests.Response
"""
data = "control,controlId=0|" + val_id
return self._basic_post(url='commandControlPublic', data=data)
def add_command_control(self, *args, **kwargs):
"""
Parameters
----------
args
kwargs
Raises
-------
NotImplementedError
"""
raise NotImplementedError("JavaScript Code can be found on "
"https://github.com/EnergyID/smappy/issues/16"
", feel free to implement it, or create an "
"issue if you have need for this function")
def delete_command_control(self, val_id):
"""
Parameters
----------
val_id : str
Returns
-------
requests.Response
"""
data = "delete,controlId=" + val_id
return self._basic_post(url='commandControlPublic', data=data)
def delete_command_control_timers(self, val_id):
"""
Parameters
----------
val_id : str
Returns
-------
requests.Response
"""
data = "deleteTimers,controlId=" + val_id
return self._basic_post(url='commandControlPublic', data=data)
def add_command_control_timed(self, *args, **kwargs):
"""
Parameters
----------
args
kwargs
Raises
-------
NotImplementedError
"""
raise NotImplementedError("JavaScript Code can be found on "
"https://github.com/EnergyID/smappy/issues/16"
", feel free to implement it, or create an "
"issue if you have need for this function")
def load_logfiles(self):
"""
Returns
-------
dict
"""
r = self._basic_post(url='logBrowser', data='logFileList')
return r.json()
def select_logfile(self, logfile):
"""
Parameters
----------
logfile : str
Returns
-------
dict
"""
data = 'logFileSelect,' + logfile
r = self._basic_post(url='logBrowser', data=data)
return r.json()
|
EnergieID/smappy | smappy/smappy.py | LocalSmappee.active_power | python | def active_power(self):
inst = self.load_instantaneous()
values = [float(i['value']) for i in inst if i['key'].endswith('ActivePower')]
return sum(values) / 1000 | Takes the sum of all instantaneous active power values
Returns them in kWh
Returns
-------
float | train | https://github.com/EnergieID/smappy/blob/1ada3abc9a51c76205c072369258f6f4f4e8fd0f/smappy/smappy.py#L573-L584 | [
"def load_instantaneous(self):\n \"\"\"\n Returns\n -------\n dict\n \"\"\"\n r = self._basic_post(url='instantaneous', data=\"loadInstantaneous\")\n return r.json()\n"
] | class LocalSmappee(object):
"""
Access a Smappee in your local network
"""
def __init__(self, ip):
"""
Parameters
----------
ip : str
local IP-address of your Smappee
"""
self.ip = ip
self.headers = {'Content-Type': 'application/json;charset=UTF-8'}
self.session = requests.Session()
@property
def base_url(self):
url = urljoin('http://', self.ip, 'gateway', 'apipublic')
return url
def _basic_post(self, url, data=None):
"""
Because basically every post request is the same
Parameters
----------
url : str
data : str, optional
Returns
-------
requests.Response
"""
_url = urljoin(self.base_url, url)
r = self.session.post(_url, data=data, headers=self.headers, timeout=5)
r.raise_for_status()
return r
def _basic_get(self, url, params=None):
_url = urljoin(self.base_url, url)
r = self.session.get(_url, params=params, headers=self.headers,
timeout=5)
r.raise_for_status()
return r
def logon(self, password='admin'):
"""
Parameters
----------
password : str
default 'admin'
Returns
-------
dict
"""
r = self._basic_post(url='logon', data=password)
return r.json()
def report_instantaneous_values(self):
"""
Returns
-------
dict
"""
r = self._basic_get(url='reportInstantaneousValues')
return r.json()
def load_instantaneous(self):
"""
Returns
-------
dict
"""
r = self._basic_post(url='instantaneous', data="loadInstantaneous")
return r.json()
def active_cosfi(self):
"""
Takes the average of all instantaneous cosfi values
Returns
-------
float
"""
inst = self.load_instantaneous()
values = [float(i['value']) for i in inst if i['key'].endswith('Cosfi')]
return sum(values) / len(values)
def restart(self):
"""
Returns
-------
requests.Response
"""
return self._basic_get(url='restartSmappee?action=2')
def reset_active_power_peaks(self):
"""
Returns
-------
requests.Response
"""
return self._basic_post(url='resetActivePowerPeaks')
def reset_ip_scan_cache(self):
"""
Returns
-------
requests.Response
"""
return self._basic_post(url='resetIPScanCache')
def reset_sensor_cache(self):
"""
Returns
-------
requests.Response
"""
return self._basic_post(url='resetSensorCache')
def reset_data(self):
"""
Returns
-------
requests.Response
"""
return self._basic_post(url='clearData')
def clear_appliances(self):
"""
Returns
-------
requests.Response
"""
return self._basic_post(url='clearAppliances')
def load_advanced_config(self):
"""
Returns
-------
dict
"""
r = self._basic_post(url='advancedConfigPublic', data='load')
return r.json()
def load_config(self):
"""
Returns
-------
dict
"""
r = self._basic_post(url='configPublic', data='load')
return r.json()
def save_config(self, *args, **kwargs):
"""
Parameters
----------
args
kwargs
Raises
------
NotImplementedError
"""
raise NotImplementedError("JavaScript Code can be found on "
"https://github.com/EnergyID/smappy/issues/16"
", feel free to implement it, or create an "
"issue if you have need for this function")
def load_command_control_config(self):
"""
Returns
-------
dict
"""
r = self._basic_post(url='commandControlPublic', data='load')
return r.json()
def send_group(self):
"""
Returns
-------
requests.Response
"""
return self._basic_post(url='commandControlPublic', data='controlGroup')
def on_command_control(self, val_id):
"""
Parameters
----------
val_id : str
Returns
-------
requests.Response
"""
data = "control,controlId=1|" + val_id
return self._basic_post(url='commandControlPublic', data=data)
def off_command_control(self, val_id):
"""
Parameters
----------
val_id : str
Returns
-------
requests.Response
"""
data = "control,controlId=0|" + val_id
return self._basic_post(url='commandControlPublic', data=data)
def add_command_control(self, *args, **kwargs):
"""
Parameters
----------
args
kwargs
Raises
-------
NotImplementedError
"""
raise NotImplementedError("JavaScript Code can be found on "
"https://github.com/EnergyID/smappy/issues/16"
", feel free to implement it, or create an "
"issue if you have need for this function")
def delete_command_control(self, val_id):
"""
Parameters
----------
val_id : str
Returns
-------
requests.Response
"""
data = "delete,controlId=" + val_id
return self._basic_post(url='commandControlPublic', data=data)
def delete_command_control_timers(self, val_id):
"""
Parameters
----------
val_id : str
Returns
-------
requests.Response
"""
data = "deleteTimers,controlId=" + val_id
return self._basic_post(url='commandControlPublic', data=data)
def add_command_control_timed(self, *args, **kwargs):
"""
Parameters
----------
args
kwargs
Raises
-------
NotImplementedError
"""
raise NotImplementedError("JavaScript Code can be found on "
"https://github.com/EnergyID/smappy/issues/16"
", feel free to implement it, or create an "
"issue if you have need for this function")
def load_logfiles(self):
"""
Returns
-------
dict
"""
r = self._basic_post(url='logBrowser', data='logFileList')
return r.json()
def select_logfile(self, logfile):
"""
Parameters
----------
logfile : str
Returns
-------
dict
"""
data = 'logFileSelect,' + logfile
r = self._basic_post(url='logBrowser', data=data)
return r.json()
|
EnergieID/smappy | smappy/smappy.py | LocalSmappee.active_cosfi | python | def active_cosfi(self):
inst = self.load_instantaneous()
values = [float(i['value']) for i in inst if i['key'].endswith('Cosfi')]
return sum(values) / len(values) | Takes the average of all instantaneous cosfi values
Returns
-------
float | train | https://github.com/EnergieID/smappy/blob/1ada3abc9a51c76205c072369258f6f4f4e8fd0f/smappy/smappy.py#L586-L596 | [
"def load_instantaneous(self):\n \"\"\"\n Returns\n -------\n dict\n \"\"\"\n r = self._basic_post(url='instantaneous', data=\"loadInstantaneous\")\n return r.json()\n"
] | class LocalSmappee(object):
"""
Access a Smappee in your local network
"""
def __init__(self, ip):
"""
Parameters
----------
ip : str
local IP-address of your Smappee
"""
self.ip = ip
self.headers = {'Content-Type': 'application/json;charset=UTF-8'}
self.session = requests.Session()
@property
def base_url(self):
url = urljoin('http://', self.ip, 'gateway', 'apipublic')
return url
def _basic_post(self, url, data=None):
"""
Because basically every post request is the same
Parameters
----------
url : str
data : str, optional
Returns
-------
requests.Response
"""
_url = urljoin(self.base_url, url)
r = self.session.post(_url, data=data, headers=self.headers, timeout=5)
r.raise_for_status()
return r
def _basic_get(self, url, params=None):
_url = urljoin(self.base_url, url)
r = self.session.get(_url, params=params, headers=self.headers,
timeout=5)
r.raise_for_status()
return r
def logon(self, password='admin'):
"""
Parameters
----------
password : str
default 'admin'
Returns
-------
dict
"""
r = self._basic_post(url='logon', data=password)
return r.json()
def report_instantaneous_values(self):
"""
Returns
-------
dict
"""
r = self._basic_get(url='reportInstantaneousValues')
return r.json()
def load_instantaneous(self):
"""
Returns
-------
dict
"""
r = self._basic_post(url='instantaneous', data="loadInstantaneous")
return r.json()
def active_power(self):
"""
Takes the sum of all instantaneous active power values
Returns them in kWh
Returns
-------
float
"""
inst = self.load_instantaneous()
values = [float(i['value']) for i in inst if i['key'].endswith('ActivePower')]
return sum(values) / 1000
def restart(self):
"""
Returns
-------
requests.Response
"""
return self._basic_get(url='restartSmappee?action=2')
def reset_active_power_peaks(self):
"""
Returns
-------
requests.Response
"""
return self._basic_post(url='resetActivePowerPeaks')
def reset_ip_scan_cache(self):
"""
Returns
-------
requests.Response
"""
return self._basic_post(url='resetIPScanCache')
def reset_sensor_cache(self):
"""
Returns
-------
requests.Response
"""
return self._basic_post(url='resetSensorCache')
def reset_data(self):
"""
Returns
-------
requests.Response
"""
return self._basic_post(url='clearData')
def clear_appliances(self):
"""
Returns
-------
requests.Response
"""
return self._basic_post(url='clearAppliances')
def load_advanced_config(self):
"""
Returns
-------
dict
"""
r = self._basic_post(url='advancedConfigPublic', data='load')
return r.json()
def load_config(self):
"""
Returns
-------
dict
"""
r = self._basic_post(url='configPublic', data='load')
return r.json()
def save_config(self, *args, **kwargs):
"""
Parameters
----------
args
kwargs
Raises
------
NotImplementedError
"""
raise NotImplementedError("JavaScript Code can be found on "
"https://github.com/EnergyID/smappy/issues/16"
", feel free to implement it, or create an "
"issue if you have need for this function")
def load_command_control_config(self):
"""
Returns
-------
dict
"""
r = self._basic_post(url='commandControlPublic', data='load')
return r.json()
def send_group(self):
"""
Returns
-------
requests.Response
"""
return self._basic_post(url='commandControlPublic', data='controlGroup')
def on_command_control(self, val_id):
"""
Parameters
----------
val_id : str
Returns
-------
requests.Response
"""
data = "control,controlId=1|" + val_id
return self._basic_post(url='commandControlPublic', data=data)
def off_command_control(self, val_id):
"""
Parameters
----------
val_id : str
Returns
-------
requests.Response
"""
data = "control,controlId=0|" + val_id
return self._basic_post(url='commandControlPublic', data=data)
def add_command_control(self, *args, **kwargs):
"""
Parameters
----------
args
kwargs
Raises
-------
NotImplementedError
"""
raise NotImplementedError("JavaScript Code can be found on "
"https://github.com/EnergyID/smappy/issues/16"
", feel free to implement it, or create an "
"issue if you have need for this function")
def delete_command_control(self, val_id):
"""
Parameters
----------
val_id : str
Returns
-------
requests.Response
"""
data = "delete,controlId=" + val_id
return self._basic_post(url='commandControlPublic', data=data)
def delete_command_control_timers(self, val_id):
"""
Parameters
----------
val_id : str
Returns
-------
requests.Response
"""
data = "deleteTimers,controlId=" + val_id
return self._basic_post(url='commandControlPublic', data=data)
def add_command_control_timed(self, *args, **kwargs):
"""
Parameters
----------
args
kwargs
Raises
-------
NotImplementedError
"""
raise NotImplementedError("JavaScript Code can be found on "
"https://github.com/EnergyID/smappy/issues/16"
", feel free to implement it, or create an "
"issue if you have need for this function")
def load_logfiles(self):
"""
Returns
-------
dict
"""
r = self._basic_post(url='logBrowser', data='logFileList')
return r.json()
def select_logfile(self, logfile):
"""
Parameters
----------
logfile : str
Returns
-------
dict
"""
data = 'logFileSelect,' + logfile
r = self._basic_post(url='logBrowser', data=data)
return r.json()
|
EnergieID/smappy | smappy/smappy.py | LocalSmappee.on_command_control | python | def on_command_control(self, val_id):
data = "control,controlId=1|" + val_id
return self._basic_post(url='commandControlPublic', data=data) | Parameters
----------
val_id : str
Returns
-------
requests.Response | train | https://github.com/EnergieID/smappy/blob/1ada3abc9a51c76205c072369258f6f4f4e8fd0f/smappy/smappy.py#L697-L708 | [
"def _basic_post(self, url, data=None):\n \"\"\"\n Because basically every post request is the same\n\n Parameters\n ----------\n url : str\n data : str, optional\n\n Returns\n -------\n requests.Response\n \"\"\"\n _url = urljoin(self.base_url, url)\n r = self.session.post(_url,... | class LocalSmappee(object):
"""
Access a Smappee in your local network
"""
def __init__(self, ip):
"""
Parameters
----------
ip : str
local IP-address of your Smappee
"""
self.ip = ip
self.headers = {'Content-Type': 'application/json;charset=UTF-8'}
self.session = requests.Session()
@property
def base_url(self):
url = urljoin('http://', self.ip, 'gateway', 'apipublic')
return url
def _basic_post(self, url, data=None):
"""
Because basically every post request is the same
Parameters
----------
url : str
data : str, optional
Returns
-------
requests.Response
"""
_url = urljoin(self.base_url, url)
r = self.session.post(_url, data=data, headers=self.headers, timeout=5)
r.raise_for_status()
return r
def _basic_get(self, url, params=None):
_url = urljoin(self.base_url, url)
r = self.session.get(_url, params=params, headers=self.headers,
timeout=5)
r.raise_for_status()
return r
def logon(self, password='admin'):
"""
Parameters
----------
password : str
default 'admin'
Returns
-------
dict
"""
r = self._basic_post(url='logon', data=password)
return r.json()
def report_instantaneous_values(self):
"""
Returns
-------
dict
"""
r = self._basic_get(url='reportInstantaneousValues')
return r.json()
def load_instantaneous(self):
"""
Returns
-------
dict
"""
r = self._basic_post(url='instantaneous', data="loadInstantaneous")
return r.json()
def active_power(self):
"""
Takes the sum of all instantaneous active power values
Returns them in kWh
Returns
-------
float
"""
inst = self.load_instantaneous()
values = [float(i['value']) for i in inst if i['key'].endswith('ActivePower')]
return sum(values) / 1000
def active_cosfi(self):
"""
Takes the average of all instantaneous cosfi values
Returns
-------
float
"""
inst = self.load_instantaneous()
values = [float(i['value']) for i in inst if i['key'].endswith('Cosfi')]
return sum(values) / len(values)
def restart(self):
"""
Returns
-------
requests.Response
"""
return self._basic_get(url='restartSmappee?action=2')
def reset_active_power_peaks(self):
"""
Returns
-------
requests.Response
"""
return self._basic_post(url='resetActivePowerPeaks')
def reset_ip_scan_cache(self):
"""
Returns
-------
requests.Response
"""
return self._basic_post(url='resetIPScanCache')
def reset_sensor_cache(self):
"""
Returns
-------
requests.Response
"""
return self._basic_post(url='resetSensorCache')
def reset_data(self):
"""
Returns
-------
requests.Response
"""
return self._basic_post(url='clearData')
def clear_appliances(self):
"""
Returns
-------
requests.Response
"""
return self._basic_post(url='clearAppliances')
def load_advanced_config(self):
"""
Returns
-------
dict
"""
r = self._basic_post(url='advancedConfigPublic', data='load')
return r.json()
def load_config(self):
"""
Returns
-------
dict
"""
r = self._basic_post(url='configPublic', data='load')
return r.json()
def save_config(self, *args, **kwargs):
"""
Parameters
----------
args
kwargs
Raises
------
NotImplementedError
"""
raise NotImplementedError("JavaScript Code can be found on "
"https://github.com/EnergyID/smappy/issues/16"
", feel free to implement it, or create an "
"issue if you have need for this function")
def load_command_control_config(self):
"""
Returns
-------
dict
"""
r = self._basic_post(url='commandControlPublic', data='load')
return r.json()
def send_group(self):
"""
Returns
-------
requests.Response
"""
return self._basic_post(url='commandControlPublic', data='controlGroup')
def off_command_control(self, val_id):
"""
Parameters
----------
val_id : str
Returns
-------
requests.Response
"""
data = "control,controlId=0|" + val_id
return self._basic_post(url='commandControlPublic', data=data)
def add_command_control(self, *args, **kwargs):
"""
Parameters
----------
args
kwargs
Raises
-------
NotImplementedError
"""
raise NotImplementedError("JavaScript Code can be found on "
"https://github.com/EnergyID/smappy/issues/16"
", feel free to implement it, or create an "
"issue if you have need for this function")
def delete_command_control(self, val_id):
"""
Parameters
----------
val_id : str
Returns
-------
requests.Response
"""
data = "delete,controlId=" + val_id
return self._basic_post(url='commandControlPublic', data=data)
def delete_command_control_timers(self, val_id):
"""
Parameters
----------
val_id : str
Returns
-------
requests.Response
"""
data = "deleteTimers,controlId=" + val_id
return self._basic_post(url='commandControlPublic', data=data)
def add_command_control_timed(self, *args, **kwargs):
"""
Parameters
----------
args
kwargs
Raises
-------
NotImplementedError
"""
raise NotImplementedError("JavaScript Code can be found on "
"https://github.com/EnergyID/smappy/issues/16"
", feel free to implement it, or create an "
"issue if you have need for this function")
def load_logfiles(self):
"""
Returns
-------
dict
"""
r = self._basic_post(url='logBrowser', data='logFileList')
return r.json()
def select_logfile(self, logfile):
"""
Parameters
----------
logfile : str
Returns
-------
dict
"""
data = 'logFileSelect,' + logfile
r = self._basic_post(url='logBrowser', data=data)
return r.json()
|
EnergieID/smappy | smappy/smappy.py | LocalSmappee.off_command_control | python | def off_command_control(self, val_id):
data = "control,controlId=0|" + val_id
return self._basic_post(url='commandControlPublic', data=data) | Parameters
----------
val_id : str
Returns
-------
requests.Response | train | https://github.com/EnergieID/smappy/blob/1ada3abc9a51c76205c072369258f6f4f4e8fd0f/smappy/smappy.py#L710-L721 | [
"def _basic_post(self, url, data=None):\n \"\"\"\n Because basically every post request is the same\n\n Parameters\n ----------\n url : str\n data : str, optional\n\n Returns\n -------\n requests.Response\n \"\"\"\n _url = urljoin(self.base_url, url)\n r = self.session.post(_url,... | class LocalSmappee(object):
"""
Access a Smappee in your local network
"""
def __init__(self, ip):
"""
Parameters
----------
ip : str
local IP-address of your Smappee
"""
self.ip = ip
self.headers = {'Content-Type': 'application/json;charset=UTF-8'}
self.session = requests.Session()
@property
def base_url(self):
url = urljoin('http://', self.ip, 'gateway', 'apipublic')
return url
def _basic_post(self, url, data=None):
"""
Because basically every post request is the same
Parameters
----------
url : str
data : str, optional
Returns
-------
requests.Response
"""
_url = urljoin(self.base_url, url)
r = self.session.post(_url, data=data, headers=self.headers, timeout=5)
r.raise_for_status()
return r
def _basic_get(self, url, params=None):
_url = urljoin(self.base_url, url)
r = self.session.get(_url, params=params, headers=self.headers,
timeout=5)
r.raise_for_status()
return r
def logon(self, password='admin'):
"""
Parameters
----------
password : str
default 'admin'
Returns
-------
dict
"""
r = self._basic_post(url='logon', data=password)
return r.json()
def report_instantaneous_values(self):
"""
Returns
-------
dict
"""
r = self._basic_get(url='reportInstantaneousValues')
return r.json()
def load_instantaneous(self):
"""
Returns
-------
dict
"""
r = self._basic_post(url='instantaneous', data="loadInstantaneous")
return r.json()
def active_power(self):
"""
Takes the sum of all instantaneous active power values
Returns them in kWh
Returns
-------
float
"""
inst = self.load_instantaneous()
values = [float(i['value']) for i in inst if i['key'].endswith('ActivePower')]
return sum(values) / 1000
def active_cosfi(self):
"""
Takes the average of all instantaneous cosfi values
Returns
-------
float
"""
inst = self.load_instantaneous()
values = [float(i['value']) for i in inst if i['key'].endswith('Cosfi')]
return sum(values) / len(values)
def restart(self):
"""
Returns
-------
requests.Response
"""
return self._basic_get(url='restartSmappee?action=2')
def reset_active_power_peaks(self):
"""
Returns
-------
requests.Response
"""
return self._basic_post(url='resetActivePowerPeaks')
def reset_ip_scan_cache(self):
"""
Returns
-------
requests.Response
"""
return self._basic_post(url='resetIPScanCache')
def reset_sensor_cache(self):
"""
Returns
-------
requests.Response
"""
return self._basic_post(url='resetSensorCache')
def reset_data(self):
"""
Returns
-------
requests.Response
"""
return self._basic_post(url='clearData')
def clear_appliances(self):
"""
Returns
-------
requests.Response
"""
return self._basic_post(url='clearAppliances')
def load_advanced_config(self):
"""
Returns
-------
dict
"""
r = self._basic_post(url='advancedConfigPublic', data='load')
return r.json()
def load_config(self):
"""
Returns
-------
dict
"""
r = self._basic_post(url='configPublic', data='load')
return r.json()
def save_config(self, *args, **kwargs):
"""
Parameters
----------
args
kwargs
Raises
------
NotImplementedError
"""
raise NotImplementedError("JavaScript Code can be found on "
"https://github.com/EnergyID/smappy/issues/16"
", feel free to implement it, or create an "
"issue if you have need for this function")
def load_command_control_config(self):
"""
Returns
-------
dict
"""
r = self._basic_post(url='commandControlPublic', data='load')
return r.json()
def send_group(self):
"""
Returns
-------
requests.Response
"""
return self._basic_post(url='commandControlPublic', data='controlGroup')
def on_command_control(self, val_id):
"""
Parameters
----------
val_id : str
Returns
-------
requests.Response
"""
data = "control,controlId=1|" + val_id
return self._basic_post(url='commandControlPublic', data=data)
def add_command_control(self, *args, **kwargs):
"""
Parameters
----------
args
kwargs
Raises
-------
NotImplementedError
"""
raise NotImplementedError("JavaScript Code can be found on "
"https://github.com/EnergyID/smappy/issues/16"
", feel free to implement it, or create an "
"issue if you have need for this function")
def delete_command_control(self, val_id):
"""
Parameters
----------
val_id : str
Returns
-------
requests.Response
"""
data = "delete,controlId=" + val_id
return self._basic_post(url='commandControlPublic', data=data)
def delete_command_control_timers(self, val_id):
"""
Parameters
----------
val_id : str
Returns
-------
requests.Response
"""
data = "deleteTimers,controlId=" + val_id
return self._basic_post(url='commandControlPublic', data=data)
def add_command_control_timed(self, *args, **kwargs):
"""
Parameters
----------
args
kwargs
Raises
-------
NotImplementedError
"""
raise NotImplementedError("JavaScript Code can be found on "
"https://github.com/EnergyID/smappy/issues/16"
", feel free to implement it, or create an "
"issue if you have need for this function")
def load_logfiles(self):
"""
Returns
-------
dict
"""
r = self._basic_post(url='logBrowser', data='logFileList')
return r.json()
def select_logfile(self, logfile):
"""
Parameters
----------
logfile : str
Returns
-------
dict
"""
data = 'logFileSelect,' + logfile
r = self._basic_post(url='logBrowser', data=data)
return r.json()
|
EnergieID/smappy | smappy/smappy.py | LocalSmappee.delete_command_control | python | def delete_command_control(self, val_id):
data = "delete,controlId=" + val_id
return self._basic_post(url='commandControlPublic', data=data) | Parameters
----------
val_id : str
Returns
-------
requests.Response | train | https://github.com/EnergieID/smappy/blob/1ada3abc9a51c76205c072369258f6f4f4e8fd0f/smappy/smappy.py#L739-L751 | [
"def _basic_post(self, url, data=None):\n \"\"\"\n Because basically every post request is the same\n\n Parameters\n ----------\n url : str\n data : str, optional\n\n Returns\n -------\n requests.Response\n \"\"\"\n _url = urljoin(self.base_url, url)\n r = self.session.post(_url,... | class LocalSmappee(object):
"""
Access a Smappee in your local network
"""
def __init__(self, ip):
"""
Parameters
----------
ip : str
local IP-address of your Smappee
"""
self.ip = ip
self.headers = {'Content-Type': 'application/json;charset=UTF-8'}
self.session = requests.Session()
@property
def base_url(self):
url = urljoin('http://', self.ip, 'gateway', 'apipublic')
return url
def _basic_post(self, url, data=None):
"""
Because basically every post request is the same
Parameters
----------
url : str
data : str, optional
Returns
-------
requests.Response
"""
_url = urljoin(self.base_url, url)
r = self.session.post(_url, data=data, headers=self.headers, timeout=5)
r.raise_for_status()
return r
def _basic_get(self, url, params=None):
_url = urljoin(self.base_url, url)
r = self.session.get(_url, params=params, headers=self.headers,
timeout=5)
r.raise_for_status()
return r
def logon(self, password='admin'):
"""
Parameters
----------
password : str
default 'admin'
Returns
-------
dict
"""
r = self._basic_post(url='logon', data=password)
return r.json()
def report_instantaneous_values(self):
"""
Returns
-------
dict
"""
r = self._basic_get(url='reportInstantaneousValues')
return r.json()
def load_instantaneous(self):
"""
Returns
-------
dict
"""
r = self._basic_post(url='instantaneous', data="loadInstantaneous")
return r.json()
def active_power(self):
"""
Takes the sum of all instantaneous active power values
Returns them in kWh
Returns
-------
float
"""
inst = self.load_instantaneous()
values = [float(i['value']) for i in inst if i['key'].endswith('ActivePower')]
return sum(values) / 1000
def active_cosfi(self):
"""
Takes the average of all instantaneous cosfi values
Returns
-------
float
"""
inst = self.load_instantaneous()
values = [float(i['value']) for i in inst if i['key'].endswith('Cosfi')]
return sum(values) / len(values)
def restart(self):
"""
Returns
-------
requests.Response
"""
return self._basic_get(url='restartSmappee?action=2')
def reset_active_power_peaks(self):
"""
Returns
-------
requests.Response
"""
return self._basic_post(url='resetActivePowerPeaks')
def reset_ip_scan_cache(self):
"""
Returns
-------
requests.Response
"""
return self._basic_post(url='resetIPScanCache')
def reset_sensor_cache(self):
"""
Returns
-------
requests.Response
"""
return self._basic_post(url='resetSensorCache')
def reset_data(self):
"""
Returns
-------
requests.Response
"""
return self._basic_post(url='clearData')
def clear_appliances(self):
"""
Returns
-------
requests.Response
"""
return self._basic_post(url='clearAppliances')
def load_advanced_config(self):
"""
Returns
-------
dict
"""
r = self._basic_post(url='advancedConfigPublic', data='load')
return r.json()
def load_config(self):
"""
Returns
-------
dict
"""
r = self._basic_post(url='configPublic', data='load')
return r.json()
def save_config(self, *args, **kwargs):
"""
Parameters
----------
args
kwargs
Raises
------
NotImplementedError
"""
raise NotImplementedError("JavaScript Code can be found on "
"https://github.com/EnergyID/smappy/issues/16"
", feel free to implement it, or create an "
"issue if you have need for this function")
def load_command_control_config(self):
"""
Returns
-------
dict
"""
r = self._basic_post(url='commandControlPublic', data='load')
return r.json()
def send_group(self):
"""
Returns
-------
requests.Response
"""
return self._basic_post(url='commandControlPublic', data='controlGroup')
def on_command_control(self, val_id):
"""
Parameters
----------
val_id : str
Returns
-------
requests.Response
"""
data = "control,controlId=1|" + val_id
return self._basic_post(url='commandControlPublic', data=data)
def off_command_control(self, val_id):
"""
Parameters
----------
val_id : str
Returns
-------
requests.Response
"""
data = "control,controlId=0|" + val_id
return self._basic_post(url='commandControlPublic', data=data)
def add_command_control(self, *args, **kwargs):
"""
Parameters
----------
args
kwargs
Raises
-------
NotImplementedError
"""
raise NotImplementedError("JavaScript Code can be found on "
"https://github.com/EnergyID/smappy/issues/16"
", feel free to implement it, or create an "
"issue if you have need for this function")
def delete_command_control_timers(self, val_id):
"""
Parameters
----------
val_id : str
Returns
-------
requests.Response
"""
data = "deleteTimers,controlId=" + val_id
return self._basic_post(url='commandControlPublic', data=data)
def add_command_control_timed(self, *args, **kwargs):
"""
Parameters
----------
args
kwargs
Raises
-------
NotImplementedError
"""
raise NotImplementedError("JavaScript Code can be found on "
"https://github.com/EnergyID/smappy/issues/16"
", feel free to implement it, or create an "
"issue if you have need for this function")
def load_logfiles(self):
"""
Returns
-------
dict
"""
r = self._basic_post(url='logBrowser', data='logFileList')
return r.json()
def select_logfile(self, logfile):
"""
Parameters
----------
logfile : str
Returns
-------
dict
"""
data = 'logFileSelect,' + logfile
r = self._basic_post(url='logBrowser', data=data)
return r.json()
|
EnergieID/smappy | smappy/smappy.py | LocalSmappee.delete_command_control_timers | python | def delete_command_control_timers(self, val_id):
data = "deleteTimers,controlId=" + val_id
return self._basic_post(url='commandControlPublic', data=data) | Parameters
----------
val_id : str
Returns
-------
requests.Response | train | https://github.com/EnergieID/smappy/blob/1ada3abc9a51c76205c072369258f6f4f4e8fd0f/smappy/smappy.py#L753-L764 | [
"def _basic_post(self, url, data=None):\n \"\"\"\n Because basically every post request is the same\n\n Parameters\n ----------\n url : str\n data : str, optional\n\n Returns\n -------\n requests.Response\n \"\"\"\n _url = urljoin(self.base_url, url)\n r = self.session.post(_url,... | class LocalSmappee(object):
"""
Access a Smappee in your local network
"""
def __init__(self, ip):
"""
Parameters
----------
ip : str
local IP-address of your Smappee
"""
self.ip = ip
self.headers = {'Content-Type': 'application/json;charset=UTF-8'}
self.session = requests.Session()
@property
def base_url(self):
url = urljoin('http://', self.ip, 'gateway', 'apipublic')
return url
def _basic_post(self, url, data=None):
"""
Because basically every post request is the same
Parameters
----------
url : str
data : str, optional
Returns
-------
requests.Response
"""
_url = urljoin(self.base_url, url)
r = self.session.post(_url, data=data, headers=self.headers, timeout=5)
r.raise_for_status()
return r
def _basic_get(self, url, params=None):
_url = urljoin(self.base_url, url)
r = self.session.get(_url, params=params, headers=self.headers,
timeout=5)
r.raise_for_status()
return r
def logon(self, password='admin'):
"""
Parameters
----------
password : str
default 'admin'
Returns
-------
dict
"""
r = self._basic_post(url='logon', data=password)
return r.json()
def report_instantaneous_values(self):
"""
Returns
-------
dict
"""
r = self._basic_get(url='reportInstantaneousValues')
return r.json()
def load_instantaneous(self):
"""
Returns
-------
dict
"""
r = self._basic_post(url='instantaneous', data="loadInstantaneous")
return r.json()
def active_power(self):
"""
Takes the sum of all instantaneous active power values
Returns them in kWh
Returns
-------
float
"""
inst = self.load_instantaneous()
values = [float(i['value']) for i in inst if i['key'].endswith('ActivePower')]
return sum(values) / 1000
def active_cosfi(self):
"""
Takes the average of all instantaneous cosfi values
Returns
-------
float
"""
inst = self.load_instantaneous()
values = [float(i['value']) for i in inst if i['key'].endswith('Cosfi')]
return sum(values) / len(values)
def restart(self):
"""
Returns
-------
requests.Response
"""
return self._basic_get(url='restartSmappee?action=2')
def reset_active_power_peaks(self):
"""
Returns
-------
requests.Response
"""
return self._basic_post(url='resetActivePowerPeaks')
def reset_ip_scan_cache(self):
"""
Returns
-------
requests.Response
"""
return self._basic_post(url='resetIPScanCache')
def reset_sensor_cache(self):
"""
Returns
-------
requests.Response
"""
return self._basic_post(url='resetSensorCache')
def reset_data(self):
"""
Returns
-------
requests.Response
"""
return self._basic_post(url='clearData')
def clear_appliances(self):
"""
Returns
-------
requests.Response
"""
return self._basic_post(url='clearAppliances')
def load_advanced_config(self):
"""
Returns
-------
dict
"""
r = self._basic_post(url='advancedConfigPublic', data='load')
return r.json()
def load_config(self):
"""
Returns
-------
dict
"""
r = self._basic_post(url='configPublic', data='load')
return r.json()
def save_config(self, *args, **kwargs):
"""
Parameters
----------
args
kwargs
Raises
------
NotImplementedError
"""
raise NotImplementedError("JavaScript Code can be found on "
"https://github.com/EnergyID/smappy/issues/16"
", feel free to implement it, or create an "
"issue if you have need for this function")
def load_command_control_config(self):
"""
Returns
-------
dict
"""
r = self._basic_post(url='commandControlPublic', data='load')
return r.json()
def send_group(self):
"""
Returns
-------
requests.Response
"""
return self._basic_post(url='commandControlPublic', data='controlGroup')
def on_command_control(self, val_id):
"""
Parameters
----------
val_id : str
Returns
-------
requests.Response
"""
data = "control,controlId=1|" + val_id
return self._basic_post(url='commandControlPublic', data=data)
def off_command_control(self, val_id):
"""
Parameters
----------
val_id : str
Returns
-------
requests.Response
"""
data = "control,controlId=0|" + val_id
return self._basic_post(url='commandControlPublic', data=data)
def add_command_control(self, *args, **kwargs):
"""
Parameters
----------
args
kwargs
Raises
-------
NotImplementedError
"""
raise NotImplementedError("JavaScript Code can be found on "
"https://github.com/EnergyID/smappy/issues/16"
", feel free to implement it, or create an "
"issue if you have need for this function")
def delete_command_control(self, val_id):
"""
Parameters
----------
val_id : str
Returns
-------
requests.Response
"""
data = "delete,controlId=" + val_id
return self._basic_post(url='commandControlPublic', data=data)
def add_command_control_timed(self, *args, **kwargs):
"""
Parameters
----------
args
kwargs
Raises
-------
NotImplementedError
"""
raise NotImplementedError("JavaScript Code can be found on "
"https://github.com/EnergyID/smappy/issues/16"
", feel free to implement it, or create an "
"issue if you have need for this function")
def load_logfiles(self):
"""
Returns
-------
dict
"""
r = self._basic_post(url='logBrowser', data='logFileList')
return r.json()
def select_logfile(self, logfile):
"""
Parameters
----------
logfile : str
Returns
-------
dict
"""
data = 'logFileSelect,' + logfile
r = self._basic_post(url='logBrowser', data=data)
return r.json()
|
EnergieID/smappy | smappy/smappy.py | LocalSmappee.select_logfile | python | def select_logfile(self, logfile):
data = 'logFileSelect,' + logfile
r = self._basic_post(url='logBrowser', data=data)
return r.json() | Parameters
----------
logfile : str
Returns
-------
dict | train | https://github.com/EnergieID/smappy/blob/1ada3abc9a51c76205c072369258f6f4f4e8fd0f/smappy/smappy.py#L791-L803 | [
"def _basic_post(self, url, data=None):\n \"\"\"\n Because basically every post request is the same\n\n Parameters\n ----------\n url : str\n data : str, optional\n\n Returns\n -------\n requests.Response\n \"\"\"\n _url = urljoin(self.base_url, url)\n r = self.session.post(_url,... | class LocalSmappee(object):
"""
Access a Smappee in your local network
"""
def __init__(self, ip):
"""
Parameters
----------
ip : str
local IP-address of your Smappee
"""
self.ip = ip
self.headers = {'Content-Type': 'application/json;charset=UTF-8'}
self.session = requests.Session()
@property
def base_url(self):
url = urljoin('http://', self.ip, 'gateway', 'apipublic')
return url
def _basic_post(self, url, data=None):
"""
Because basically every post request is the same
Parameters
----------
url : str
data : str, optional
Returns
-------
requests.Response
"""
_url = urljoin(self.base_url, url)
r = self.session.post(_url, data=data, headers=self.headers, timeout=5)
r.raise_for_status()
return r
def _basic_get(self, url, params=None):
_url = urljoin(self.base_url, url)
r = self.session.get(_url, params=params, headers=self.headers,
timeout=5)
r.raise_for_status()
return r
def logon(self, password='admin'):
"""
Parameters
----------
password : str
default 'admin'
Returns
-------
dict
"""
r = self._basic_post(url='logon', data=password)
return r.json()
def report_instantaneous_values(self):
"""
Returns
-------
dict
"""
r = self._basic_get(url='reportInstantaneousValues')
return r.json()
def load_instantaneous(self):
"""
Returns
-------
dict
"""
r = self._basic_post(url='instantaneous', data="loadInstantaneous")
return r.json()
def active_power(self):
"""
Takes the sum of all instantaneous active power values
Returns them in kWh
Returns
-------
float
"""
inst = self.load_instantaneous()
values = [float(i['value']) for i in inst if i['key'].endswith('ActivePower')]
return sum(values) / 1000
def active_cosfi(self):
"""
Takes the average of all instantaneous cosfi values
Returns
-------
float
"""
inst = self.load_instantaneous()
values = [float(i['value']) for i in inst if i['key'].endswith('Cosfi')]
return sum(values) / len(values)
def restart(self):
"""
Returns
-------
requests.Response
"""
return self._basic_get(url='restartSmappee?action=2')
def reset_active_power_peaks(self):
"""
Returns
-------
requests.Response
"""
return self._basic_post(url='resetActivePowerPeaks')
def reset_ip_scan_cache(self):
"""
Returns
-------
requests.Response
"""
return self._basic_post(url='resetIPScanCache')
def reset_sensor_cache(self):
"""
Returns
-------
requests.Response
"""
return self._basic_post(url='resetSensorCache')
def reset_data(self):
"""
Returns
-------
requests.Response
"""
return self._basic_post(url='clearData')
def clear_appliances(self):
"""
Returns
-------
requests.Response
"""
return self._basic_post(url='clearAppliances')
def load_advanced_config(self):
"""
Returns
-------
dict
"""
r = self._basic_post(url='advancedConfigPublic', data='load')
return r.json()
def load_config(self):
"""
Returns
-------
dict
"""
r = self._basic_post(url='configPublic', data='load')
return r.json()
def save_config(self, *args, **kwargs):
"""
Parameters
----------
args
kwargs
Raises
------
NotImplementedError
"""
raise NotImplementedError("JavaScript Code can be found on "
"https://github.com/EnergyID/smappy/issues/16"
", feel free to implement it, or create an "
"issue if you have need for this function")
def load_command_control_config(self):
"""
Returns
-------
dict
"""
r = self._basic_post(url='commandControlPublic', data='load')
return r.json()
def send_group(self):
"""
Returns
-------
requests.Response
"""
return self._basic_post(url='commandControlPublic', data='controlGroup')
def on_command_control(self, val_id):
"""
Parameters
----------
val_id : str
Returns
-------
requests.Response
"""
data = "control,controlId=1|" + val_id
return self._basic_post(url='commandControlPublic', data=data)
def off_command_control(self, val_id):
"""
Parameters
----------
val_id : str
Returns
-------
requests.Response
"""
data = "control,controlId=0|" + val_id
return self._basic_post(url='commandControlPublic', data=data)
def add_command_control(self, *args, **kwargs):
"""
Parameters
----------
args
kwargs
Raises
-------
NotImplementedError
"""
raise NotImplementedError("JavaScript Code can be found on "
"https://github.com/EnergyID/smappy/issues/16"
", feel free to implement it, or create an "
"issue if you have need for this function")
def delete_command_control(self, val_id):
"""
Parameters
----------
val_id : str
Returns
-------
requests.Response
"""
data = "delete,controlId=" + val_id
return self._basic_post(url='commandControlPublic', data=data)
def delete_command_control_timers(self, val_id):
"""
Parameters
----------
val_id : str
Returns
-------
requests.Response
"""
data = "deleteTimers,controlId=" + val_id
return self._basic_post(url='commandControlPublic', data=data)
def add_command_control_timed(self, *args, **kwargs):
"""
Parameters
----------
args
kwargs
Raises
-------
NotImplementedError
"""
raise NotImplementedError("JavaScript Code can be found on "
"https://github.com/EnergyID/smappy/issues/16"
", feel free to implement it, or create an "
"issue if you have need for this function")
def load_logfiles(self):
"""
Returns
-------
dict
"""
r = self._basic_post(url='logBrowser', data='logFileList')
return r.json()
|
pycontribs/python-crowd | crowd.py | CrowdServer._get | python | def _get(self, *args, **kwargs):
if 'timeout' not in kwargs:
kwargs['timeout'] = self.timeout
req = self.session.get(*args, **kwargs)
return req | Wrapper around Requests for GET requests
Returns:
Response:
A Requests Response object | train | https://github.com/pycontribs/python-crowd/blob/a075e45774dd5baecf0217843cda747084268e32/crowd.py#L70-L82 | null | class CrowdServer(object):
"""Crowd server authentication object.
This is a Crowd authentication class to be configured for a
particular application (app_name) to authenticate users
against a Crowd server (crowd_url).
This module uses the Crowd JSON API for talking to Crowd.
An application account must be configured in the Crowd server
and permitted to authenticate users against one or more user
directories prior to using this module.
Please see the Crowd documentation for information about
configuring additional applications to talk to Crowd.
The ``ssl_verify`` parameter controls how and if certificates are verified.
If ``True``, the SSL certificate will be verified.
A CA_BUNDLE path can also be provided.
The ``client_cert`` tuple (cert,key) specifies a SSL client certificate and key files.
"""
def __init__(self, crowd_url, app_name, app_pass, ssl_verify=True,
timeout=None, client_cert=None):
self.crowd_url = crowd_url
self.app_name = app_name
self.app_pass = app_pass
self.rest_url = crowd_url.rstrip("/") + "/rest/usermanagement/1"
self.ssl_verify = ssl_verify
self.client_cert = client_cert
self.timeout = timeout
self.session = self._build_session(content_type='json')
self.session_xml = self._build_session(content_type='xml')
def __str__(self):
return "Crowd Server at %s" % self.crowd_url
def __repr__(self):
return "<CrowdServer('%s', '%s', '%s')>" % \
(self.crowd_url, self.app_name, self.app_pass)
def _build_session(self, content_type='json'):
headers = {
'Content-Type': 'application/{}'.format(content_type),
'Accept': 'application/{}'.format(content_type),
}
session = requests.Session()
session.verify = self.ssl_verify
session.cert = self.client_cert
session.auth = requests.auth.HTTPBasicAuth(self.app_name, self.app_pass)
session.headers.update(headers)
return session
def _get_xml(self, *args, **kwargs):
"""Wrapper around Requests for GET XML requests
Returns:
Response:
A Requests Response object
"""
req = self.session_xml.get(*args, **kwargs)
return req
def _post(self, *args, **kwargs):
"""Wrapper around Requests for POST requests
Returns:
Response:
A Requests Response object
"""
if 'timeout' not in kwargs:
kwargs['timeout'] = self.timeout
req = self.session.post(*args, **kwargs)
return req
def _post_xml(self, *args, **kwargs):
"""Wrapper around Requests for POST requests
Returns:
Response:
A Requests Response object
"""
if 'timeout' not in kwargs:
kwargs['timeout'] = self.timeout
req = self.session_xml.post(*args, **kwargs)
return req
def _put(self, *args, **kwargs):
"""Wrapper around Requests for PUT requests
Returns:
Response:
A Requests Response object
"""
if 'timeout' not in kwargs:
kwargs['timeout'] = self.timeout
req = self.session.put(*args, **kwargs)
return req
def _delete(self, *args, **kwargs):
"""Wrapper around Requests for DELETE requests
Returns:
Response:
A Requests Response object
"""
if 'timeout' not in kwargs:
kwargs['timeout'] = self.timeout
req = self.session.delete(*args, **kwargs)
return req
def auth_ping(self):
"""Test that application can authenticate to Crowd.
Attempts to authenticate the application user against
the Crowd server. In order for user authentication to
work, an application must be able to authenticate.
Returns:
bool:
True if the application authentication succeeded.
"""
url = self.rest_url + "/non-existent/location"
response = self._get(url)
if response.status_code == 401:
return False
elif response.status_code == 404:
return True
else:
# An error encountered - problem with the Crowd server?
return False
def auth_user(self, username, password):
"""Authenticate a user account against the Crowd server.
Attempts to authenticate the user against the Crowd server.
Args:
username: The account username.
password: The account password.
Returns:
dict:
A dict mapping of user attributes if the application
authentication was successful. See the Crowd documentation
for the authoritative list of attributes.
None: If authentication failed.
"""
response = self._post(self.rest_url + "/authentication",
data=json.dumps({"value": password}),
params={"username": username})
# If authentication failed for any reason return None
if not response.ok:
return None
# ...otherwise return a dictionary of user attributes
return response.json()
def get_session(self, username, password, remote="127.0.0.1", proxy=None):
"""Create a session for a user.
Attempts to create a user session on the Crowd server.
Args:
username: The account username.
password: The account password.
remote:
The remote address of the user. This can be used
to create multiple concurrent sessions for a user.
The host you run this program on may need to be configured
in Crowd as a trusted proxy for this to work.
proxy: Value of X-Forwarded-For server header.
Returns:
dict:
A dict mapping of user attributes if the application
authentication was successful. See the Crowd
documentation for the authoritative list of attributes.
None: If authentication failed.
"""
params = {
"username": username,
"password": password,
"validation-factors": {
"validationFactors": [
{"name": "remote_address", "value": remote, },
]
}
}
if proxy:
params["validation-factors"]["validationFactors"].append({"name": "X-Forwarded-For", "value": proxy, })
response = self._post(self.rest_url + "/session",
data=json.dumps(params),
params={"expand": "user"})
# If authentication failed for any reason return None
if not response.ok:
return None
# Otherwise return the user object
return response.json()
def validate_session(self, token, remote="127.0.0.1", proxy=None):
"""Validate a session token.
Validate a previously acquired session token against the
Crowd server. This may be a token provided by a user from
a http cookie or by some other means.
Args:
token: The session token.
remote: The remote address of the user.
proxy: Value of X-Forwarded-For server header
Returns:
dict:
A dict mapping of user attributes if the application
authentication was successful. See the Crowd
documentation for the authoritative list of attributes.
None: If authentication failed.
"""
params = {
"validationFactors": [
{"name": "remote_address", "value": remote, },
]
}
if proxy:
params["validation-factors"]["validationFactors"].append({"name": "X-Forwarded-For", "value": proxy, })
url = self.rest_url + "/session/%s" % token
response = self._post(url, data=json.dumps(params), params={"expand": "user"})
# For consistency between methods use None rather than False
# If token validation failed for any reason return None
if not response.ok:
return None
# Otherwise return the user object
return response.json()
def terminate_session(self, token):
"""Terminates the session token, effectively logging out the user
from all crowd-enabled services.
Args:
token: The session token.
Returns:
True: If session terminated
None: If session termination failed
"""
url = self.rest_url + "/session/%s" % token
response = self._delete(url)
# For consistency between methods use None rather than False
# If token validation failed for any reason return None
if not response.ok:
return None
# Otherwise return True
return True
def add_user(self, username, raise_on_error=False, **kwargs):
"""Add a user to the directory
Args:
username: The account username
raise_on_error: optional (default: False)
**kwargs: key-value pairs:
password: mandatory
email: mandatory
first_name: optional
last_name: optional
display_name: optional
active: optional (default True)
Returns:
True: Succeeded
False: If unsuccessful
"""
# Check that mandatory elements have been provided
if 'password' not in kwargs:
raise ValueError("missing password")
if 'email' not in kwargs:
raise ValueError("missing email")
# Populate data with default and mandatory values.
# A KeyError means a mandatory value was not provided,
# so raise a ValueError indicating bad args.
try:
data = {
"name": username,
"first-name": username,
"last-name": username,
"display-name": username,
"email": kwargs["email"],
"password": {"value": kwargs["password"]},
"active": True
}
except KeyError:
return ValueError
# Remove special case 'password'
del(kwargs["password"])
# Put values from kwargs into data
for k, v in kwargs.items():
new_k = k.replace("_", "-")
if new_k not in data:
raise ValueError("invalid argument %s" % k)
data[new_k] = v
response = self._post(self.rest_url + "/user",
data=json.dumps(data))
if response.status_code == 201:
return True
if raise_on_error:
raise RuntimeError(response.json()['message'])
return False
def get_user(self, username):
"""Retrieve information about a user
Returns:
dict: User information
None: If no user or failure occurred
"""
response = self._get(self.rest_url + "/user",
params={"username": username,
"expand": "attributes"})
if not response.ok:
return None
return response.json()
def set_active(self, username, active_state):
"""Set the active state of a user
Args:
username: The account username
active_state: True or False
Returns:
True: If successful
None: If no user or failure occurred
"""
if active_state not in (True, False):
raise ValueError("active_state must be True or False")
user = self.get_user(username)
if user is None:
return None
if user['active'] is active_state:
# Already in desired state
return True
user['active'] = active_state
response = self._put(self.rest_url + "/user",
params={"username": username},
data=json.dumps(user))
if response.status_code == 204:
return True
return None
def set_user_attribute(self, username, attribute, value, raise_on_error=False):
"""Set an attribute on a user
:param username: The username on which to set the attribute
:param attribute: The name of the attribute to set
:param value: The value of the attribute to set
:return: True on success, False on failure.
"""
data = {
'attributes': [
{
'name': attribute,
'values': [
value
]
},
]
}
response = self._post(self.rest_url + "/user/attribute",
params={"username": username,},
data=json.dumps(data))
if response.status_code == 204:
return True
if raise_on_error:
raise RuntimeError(response.json()['message'])
return False
def add_user_to_group(self, username, groupname, raise_on_error=False):
"""Add a user to a group
:param username: The username to assign to the group
:param groupname: The group name into which to assign the user
:return: True on success, False on failure.
"""
data = {
'name': groupname,
}
response = self._post(self.rest_url + "/user/group/direct",
params={"username": username,},
data=json.dumps(data))
if response.status_code == 201:
return True
if raise_on_error:
raise RuntimeError(response.json()['message'])
return False
def remove_user_from_group(self, username, groupname, raise_on_error=False):
"""Remove a user from a group
Attempts to remove a user from a group
Args
username: The username to remove from the group.
groupname: The group name to be removed from the user.
Returns:
True: Succeeded
False: If unsuccessful
"""
response = self._delete(self.rest_url + "/group/user/direct",params={"username": username, "groupname": groupname})
if response.status_code == 204:
return True
if raise_on_error:
raise RuntimeError(response.json()['message'])
return False
def change_password(self, username, newpassword, raise_on_error=False):
"""Change new password for a user
Args:
username: The account username.
newpassword: The account new password.
raise_on_error: optional (default: False)
Returns:
True: Succeeded
False: If unsuccessful
"""
response = self._put(self.rest_url + "/user/password",
data=json.dumps({"value": newpassword}),
params={"username": username})
if response.ok:
return True
if raise_on_error:
raise RuntimeError(response.json()['message'])
return False
def send_password_reset_link(self, username):
"""Sends the user a password reset link (by email)
Args:
username: The account username.
Returns:
True: Succeeded
False: If unsuccessful
"""
response = self._post(self.rest_url + "/user/mail/password",
params={"username": username})
if response.ok:
return True
return False
def get_groups(self, username):
"""Retrieves a list of group names that have <username> as a direct member.
Returns:
list:
A list of strings of group names.
"""
response = self._get(self.rest_url + "/user/group/direct",
params={"username": username})
if not response.ok:
return None
return [g['name'] for g in response.json()['groups']]
def get_nested_groups(self, username):
"""Retrieve a list of all group names that have <username> as a direct or indirect member.
Args:
username: The account username.
Returns:
list:
A list of strings of group names.
"""
response = self._get(self.rest_url + "/user/group/nested",
params={"username": username})
if not response.ok:
return None
return [g['name'] for g in response.json()['groups']]
def get_nested_group_users(self, groupname):
"""Retrieves a list of all users that directly or indirectly belong to the given groupname.
Args:
groupname: The group name.
Returns:
list:
A list of strings of user names.
"""
response = self._get(self.rest_url + "/group/user/nested",
params={"groupname": groupname,
"start-index": 0,
"max-results": 99999})
if not response.ok:
return None
return [u['name'] for u in response.json()['users']]
def user_exists(self, username):
"""Determines if the user exists.
Args:
username: The user name.
Returns:
bool:
True if the user exists in the Crowd application.
"""
response = self._get(self.rest_url + "/user",
params={"username": username})
if not response.ok:
return None
return True
def get_memberships(self):
"""Fetches all group memberships.
Returns:
dict:
key: group name
value: (array of users, array of groups)
"""
response = self._get_xml(self.rest_url + "/group/membership")
if not response.ok:
return None
xmltree = etree.fromstring(response.content)
memberships = {}
for mg in xmltree.findall('membership'):
# coerce values to unicode in a python 2 and 3 compatible way
group = u'{}'.format(mg.get('group'))
users = [u'{}'.format(u.get('name')) for u in mg.find('users').findall('user')]
groups = [u'{}'.format(g.get('name')) for g in mg.find('groups').findall('group')]
memberships[group] = {u'users': users, u'groups': groups}
return memberships
def search(self, entity_type, property_name, search_string, start_index=0, max_results=99999):
"""Performs a user search using the Crowd search API.
https://developer.atlassian.com/display/CROWDDEV/Crowd+REST+Resources#CrowdRESTResources-SearchResource
Args:
entity_type: 'user' or 'group'
property_name: eg. 'email', 'name'
search_string: the string to search for.
start_index: starting index of the results (default: 0)
max_results: maximum number of results returned (default: 99999)
Returns:
json results:
Returns search results.
"""
params = {
"entity-type": entity_type,
"expand": entity_type,
"property-search-restriction": {
"property": {"name": property_name, "type": "STRING"},
"match-mode": "CONTAINS",
"value": search_string,
}
}
params = {
'entity-type': entity_type,
'expand': entity_type,
'start-index': start_index,
'max-results': max_results
}
# Construct XML payload of the form:
# <property-search-restriction>
# <property>
# <name>email</name>
# <type>STRING</type>
# </property>
# <match-mode>EXACTLY_MATCHES</match-mode>
# <value>bob@example.net</value>
# </property-search-restriction>
root = etree.Element('property-search-restriction')
property_ = etree.Element('property')
prop_name = etree.Element('name')
prop_name.text = property_name
property_.append(prop_name)
prop_type = etree.Element('type')
prop_type.text = 'STRING'
property_.append(prop_type)
root.append(property_)
match_mode = etree.Element('match-mode')
match_mode.text = 'CONTAINS'
root.append(match_mode)
value = etree.Element('value')
value.text = search_string
root.append(value)
# Construct the XML payload expected by search API
payload = '<?xml version="1.0" encoding="UTF-8"?>\n' + etree.tostring(root).decode('utf-8')
# We're sending XML but would like a JSON response
session = self._build_session(content_type='xml')
session.headers.update({'Accept': 'application/json'})
response = session.post(self.rest_url + "/search", params=params, data=payload, timeout=self.timeout)
if not response.ok:
return None
return response.json()
|
pycontribs/python-crowd | crowd.py | CrowdServer._get_xml | python | def _get_xml(self, *args, **kwargs):
req = self.session_xml.get(*args, **kwargs)
return req | Wrapper around Requests for GET XML requests
Returns:
Response:
A Requests Response object | train | https://github.com/pycontribs/python-crowd/blob/a075e45774dd5baecf0217843cda747084268e32/crowd.py#L84-L92 | null | class CrowdServer(object):
"""Crowd server authentication object.
This is a Crowd authentication class to be configured for a
particular application (app_name) to authenticate users
against a Crowd server (crowd_url).
This module uses the Crowd JSON API for talking to Crowd.
An application account must be configured in the Crowd server
and permitted to authenticate users against one or more user
directories prior to using this module.
Please see the Crowd documentation for information about
configuring additional applications to talk to Crowd.
The ``ssl_verify`` parameter controls how and if certificates are verified.
If ``True``, the SSL certificate will be verified.
A CA_BUNDLE path can also be provided.
The ``client_cert`` tuple (cert,key) specifies a SSL client certificate and key files.
"""
def __init__(self, crowd_url, app_name, app_pass, ssl_verify=True,
timeout=None, client_cert=None):
self.crowd_url = crowd_url
self.app_name = app_name
self.app_pass = app_pass
self.rest_url = crowd_url.rstrip("/") + "/rest/usermanagement/1"
self.ssl_verify = ssl_verify
self.client_cert = client_cert
self.timeout = timeout
self.session = self._build_session(content_type='json')
self.session_xml = self._build_session(content_type='xml')
def __str__(self):
return "Crowd Server at %s" % self.crowd_url
def __repr__(self):
return "<CrowdServer('%s', '%s', '%s')>" % \
(self.crowd_url, self.app_name, self.app_pass)
def _build_session(self, content_type='json'):
headers = {
'Content-Type': 'application/{}'.format(content_type),
'Accept': 'application/{}'.format(content_type),
}
session = requests.Session()
session.verify = self.ssl_verify
session.cert = self.client_cert
session.auth = requests.auth.HTTPBasicAuth(self.app_name, self.app_pass)
session.headers.update(headers)
return session
def _get(self, *args, **kwargs):
"""Wrapper around Requests for GET requests
Returns:
Response:
A Requests Response object
"""
if 'timeout' not in kwargs:
kwargs['timeout'] = self.timeout
req = self.session.get(*args, **kwargs)
return req
def _post(self, *args, **kwargs):
"""Wrapper around Requests for POST requests
Returns:
Response:
A Requests Response object
"""
if 'timeout' not in kwargs:
kwargs['timeout'] = self.timeout
req = self.session.post(*args, **kwargs)
return req
def _post_xml(self, *args, **kwargs):
"""Wrapper around Requests for POST requests
Returns:
Response:
A Requests Response object
"""
if 'timeout' not in kwargs:
kwargs['timeout'] = self.timeout
req = self.session_xml.post(*args, **kwargs)
return req
def _put(self, *args, **kwargs):
"""Wrapper around Requests for PUT requests
Returns:
Response:
A Requests Response object
"""
if 'timeout' not in kwargs:
kwargs['timeout'] = self.timeout
req = self.session.put(*args, **kwargs)
return req
def _delete(self, *args, **kwargs):
"""Wrapper around Requests for DELETE requests
Returns:
Response:
A Requests Response object
"""
if 'timeout' not in kwargs:
kwargs['timeout'] = self.timeout
req = self.session.delete(*args, **kwargs)
return req
def auth_ping(self):
"""Test that application can authenticate to Crowd.
Attempts to authenticate the application user against
the Crowd server. In order for user authentication to
work, an application must be able to authenticate.
Returns:
bool:
True if the application authentication succeeded.
"""
url = self.rest_url + "/non-existent/location"
response = self._get(url)
if response.status_code == 401:
return False
elif response.status_code == 404:
return True
else:
# An error encountered - problem with the Crowd server?
return False
def auth_user(self, username, password):
"""Authenticate a user account against the Crowd server.
Attempts to authenticate the user against the Crowd server.
Args:
username: The account username.
password: The account password.
Returns:
dict:
A dict mapping of user attributes if the application
authentication was successful. See the Crowd documentation
for the authoritative list of attributes.
None: If authentication failed.
"""
response = self._post(self.rest_url + "/authentication",
data=json.dumps({"value": password}),
params={"username": username})
# If authentication failed for any reason return None
if not response.ok:
return None
# ...otherwise return a dictionary of user attributes
return response.json()
def get_session(self, username, password, remote="127.0.0.1", proxy=None):
"""Create a session for a user.
Attempts to create a user session on the Crowd server.
Args:
username: The account username.
password: The account password.
remote:
The remote address of the user. This can be used
to create multiple concurrent sessions for a user.
The host you run this program on may need to be configured
in Crowd as a trusted proxy for this to work.
proxy: Value of X-Forwarded-For server header.
Returns:
dict:
A dict mapping of user attributes if the application
authentication was successful. See the Crowd
documentation for the authoritative list of attributes.
None: If authentication failed.
"""
params = {
"username": username,
"password": password,
"validation-factors": {
"validationFactors": [
{"name": "remote_address", "value": remote, },
]
}
}
if proxy:
params["validation-factors"]["validationFactors"].append({"name": "X-Forwarded-For", "value": proxy, })
response = self._post(self.rest_url + "/session",
data=json.dumps(params),
params={"expand": "user"})
# If authentication failed for any reason return None
if not response.ok:
return None
# Otherwise return the user object
return response.json()
def validate_session(self, token, remote="127.0.0.1", proxy=None):
"""Validate a session token.
Validate a previously acquired session token against the
Crowd server. This may be a token provided by a user from
a http cookie or by some other means.
Args:
token: The session token.
remote: The remote address of the user.
proxy: Value of X-Forwarded-For server header
Returns:
dict:
A dict mapping of user attributes if the application
authentication was successful. See the Crowd
documentation for the authoritative list of attributes.
None: If authentication failed.
"""
params = {
"validationFactors": [
{"name": "remote_address", "value": remote, },
]
}
if proxy:
params["validation-factors"]["validationFactors"].append({"name": "X-Forwarded-For", "value": proxy, })
url = self.rest_url + "/session/%s" % token
response = self._post(url, data=json.dumps(params), params={"expand": "user"})
# For consistency between methods use None rather than False
# If token validation failed for any reason return None
if not response.ok:
return None
# Otherwise return the user object
return response.json()
def terminate_session(self, token):
"""Terminates the session token, effectively logging out the user
from all crowd-enabled services.
Args:
token: The session token.
Returns:
True: If session terminated
None: If session termination failed
"""
url = self.rest_url + "/session/%s" % token
response = self._delete(url)
# For consistency between methods use None rather than False
# If token validation failed for any reason return None
if not response.ok:
return None
# Otherwise return True
return True
def add_user(self, username, raise_on_error=False, **kwargs):
"""Add a user to the directory
Args:
username: The account username
raise_on_error: optional (default: False)
**kwargs: key-value pairs:
password: mandatory
email: mandatory
first_name: optional
last_name: optional
display_name: optional
active: optional (default True)
Returns:
True: Succeeded
False: If unsuccessful
"""
# Check that mandatory elements have been provided
if 'password' not in kwargs:
raise ValueError("missing password")
if 'email' not in kwargs:
raise ValueError("missing email")
# Populate data with default and mandatory values.
# A KeyError means a mandatory value was not provided,
# so raise a ValueError indicating bad args.
try:
data = {
"name": username,
"first-name": username,
"last-name": username,
"display-name": username,
"email": kwargs["email"],
"password": {"value": kwargs["password"]},
"active": True
}
except KeyError:
return ValueError
# Remove special case 'password'
del(kwargs["password"])
# Put values from kwargs into data
for k, v in kwargs.items():
new_k = k.replace("_", "-")
if new_k not in data:
raise ValueError("invalid argument %s" % k)
data[new_k] = v
response = self._post(self.rest_url + "/user",
data=json.dumps(data))
if response.status_code == 201:
return True
if raise_on_error:
raise RuntimeError(response.json()['message'])
return False
def get_user(self, username):
"""Retrieve information about a user
Returns:
dict: User information
None: If no user or failure occurred
"""
response = self._get(self.rest_url + "/user",
params={"username": username,
"expand": "attributes"})
if not response.ok:
return None
return response.json()
def set_active(self, username, active_state):
"""Set the active state of a user
Args:
username: The account username
active_state: True or False
Returns:
True: If successful
None: If no user or failure occurred
"""
if active_state not in (True, False):
raise ValueError("active_state must be True or False")
user = self.get_user(username)
if user is None:
return None
if user['active'] is active_state:
# Already in desired state
return True
user['active'] = active_state
response = self._put(self.rest_url + "/user",
params={"username": username},
data=json.dumps(user))
if response.status_code == 204:
return True
return None
def set_user_attribute(self, username, attribute, value, raise_on_error=False):
"""Set an attribute on a user
:param username: The username on which to set the attribute
:param attribute: The name of the attribute to set
:param value: The value of the attribute to set
:return: True on success, False on failure.
"""
data = {
'attributes': [
{
'name': attribute,
'values': [
value
]
},
]
}
response = self._post(self.rest_url + "/user/attribute",
params={"username": username,},
data=json.dumps(data))
if response.status_code == 204:
return True
if raise_on_error:
raise RuntimeError(response.json()['message'])
return False
def add_user_to_group(self, username, groupname, raise_on_error=False):
"""Add a user to a group
:param username: The username to assign to the group
:param groupname: The group name into which to assign the user
:return: True on success, False on failure.
"""
data = {
'name': groupname,
}
response = self._post(self.rest_url + "/user/group/direct",
params={"username": username,},
data=json.dumps(data))
if response.status_code == 201:
return True
if raise_on_error:
raise RuntimeError(response.json()['message'])
return False
def remove_user_from_group(self, username, groupname, raise_on_error=False):
"""Remove a user from a group
Attempts to remove a user from a group
Args
username: The username to remove from the group.
groupname: The group name to be removed from the user.
Returns:
True: Succeeded
False: If unsuccessful
"""
response = self._delete(self.rest_url + "/group/user/direct",params={"username": username, "groupname": groupname})
if response.status_code == 204:
return True
if raise_on_error:
raise RuntimeError(response.json()['message'])
return False
def change_password(self, username, newpassword, raise_on_error=False):
"""Change new password for a user
Args:
username: The account username.
newpassword: The account new password.
raise_on_error: optional (default: False)
Returns:
True: Succeeded
False: If unsuccessful
"""
response = self._put(self.rest_url + "/user/password",
data=json.dumps({"value": newpassword}),
params={"username": username})
if response.ok:
return True
if raise_on_error:
raise RuntimeError(response.json()['message'])
return False
def send_password_reset_link(self, username):
"""Sends the user a password reset link (by email)
Args:
username: The account username.
Returns:
True: Succeeded
False: If unsuccessful
"""
response = self._post(self.rest_url + "/user/mail/password",
params={"username": username})
if response.ok:
return True
return False
def get_groups(self, username):
"""Retrieves a list of group names that have <username> as a direct member.
Returns:
list:
A list of strings of group names.
"""
response = self._get(self.rest_url + "/user/group/direct",
params={"username": username})
if not response.ok:
return None
return [g['name'] for g in response.json()['groups']]
def get_nested_groups(self, username):
"""Retrieve a list of all group names that have <username> as a direct or indirect member.
Args:
username: The account username.
Returns:
list:
A list of strings of group names.
"""
response = self._get(self.rest_url + "/user/group/nested",
params={"username": username})
if not response.ok:
return None
return [g['name'] for g in response.json()['groups']]
def get_nested_group_users(self, groupname):
"""Retrieves a list of all users that directly or indirectly belong to the given groupname.
Args:
groupname: The group name.
Returns:
list:
A list of strings of user names.
"""
response = self._get(self.rest_url + "/group/user/nested",
params={"groupname": groupname,
"start-index": 0,
"max-results": 99999})
if not response.ok:
return None
return [u['name'] for u in response.json()['users']]
def user_exists(self, username):
"""Determines if the user exists.
Args:
username: The user name.
Returns:
bool:
True if the user exists in the Crowd application.
"""
response = self._get(self.rest_url + "/user",
params={"username": username})
if not response.ok:
return None
return True
def get_memberships(self):
"""Fetches all group memberships.
Returns:
dict:
key: group name
value: (array of users, array of groups)
"""
response = self._get_xml(self.rest_url + "/group/membership")
if not response.ok:
return None
xmltree = etree.fromstring(response.content)
memberships = {}
for mg in xmltree.findall('membership'):
# coerce values to unicode in a python 2 and 3 compatible way
group = u'{}'.format(mg.get('group'))
users = [u'{}'.format(u.get('name')) for u in mg.find('users').findall('user')]
groups = [u'{}'.format(g.get('name')) for g in mg.find('groups').findall('group')]
memberships[group] = {u'users': users, u'groups': groups}
return memberships
def search(self, entity_type, property_name, search_string, start_index=0, max_results=99999):
"""Performs a user search using the Crowd search API.
https://developer.atlassian.com/display/CROWDDEV/Crowd+REST+Resources#CrowdRESTResources-SearchResource
Args:
entity_type: 'user' or 'group'
property_name: eg. 'email', 'name'
search_string: the string to search for.
start_index: starting index of the results (default: 0)
max_results: maximum number of results returned (default: 99999)
Returns:
json results:
Returns search results.
"""
params = {
"entity-type": entity_type,
"expand": entity_type,
"property-search-restriction": {
"property": {"name": property_name, "type": "STRING"},
"match-mode": "CONTAINS",
"value": search_string,
}
}
params = {
'entity-type': entity_type,
'expand': entity_type,
'start-index': start_index,
'max-results': max_results
}
# Construct XML payload of the form:
# <property-search-restriction>
# <property>
# <name>email</name>
# <type>STRING</type>
# </property>
# <match-mode>EXACTLY_MATCHES</match-mode>
# <value>bob@example.net</value>
# </property-search-restriction>
root = etree.Element('property-search-restriction')
property_ = etree.Element('property')
prop_name = etree.Element('name')
prop_name.text = property_name
property_.append(prop_name)
prop_type = etree.Element('type')
prop_type.text = 'STRING'
property_.append(prop_type)
root.append(property_)
match_mode = etree.Element('match-mode')
match_mode.text = 'CONTAINS'
root.append(match_mode)
value = etree.Element('value')
value.text = search_string
root.append(value)
# Construct the XML payload expected by search API
payload = '<?xml version="1.0" encoding="UTF-8"?>\n' + etree.tostring(root).decode('utf-8')
# We're sending XML but would like a JSON response
session = self._build_session(content_type='xml')
session.headers.update({'Accept': 'application/json'})
response = session.post(self.rest_url + "/search", params=params, data=payload, timeout=self.timeout)
if not response.ok:
return None
return response.json()
|
pycontribs/python-crowd | crowd.py | CrowdServer._post | python | def _post(self, *args, **kwargs):
if 'timeout' not in kwargs:
kwargs['timeout'] = self.timeout
req = self.session.post(*args, **kwargs)
return req | Wrapper around Requests for POST requests
Returns:
Response:
A Requests Response object | train | https://github.com/pycontribs/python-crowd/blob/a075e45774dd5baecf0217843cda747084268e32/crowd.py#L94-L106 | null | class CrowdServer(object):
"""Crowd server authentication object.
This is a Crowd authentication class to be configured for a
particular application (app_name) to authenticate users
against a Crowd server (crowd_url).
This module uses the Crowd JSON API for talking to Crowd.
An application account must be configured in the Crowd server
and permitted to authenticate users against one or more user
directories prior to using this module.
Please see the Crowd documentation for information about
configuring additional applications to talk to Crowd.
The ``ssl_verify`` parameter controls how and if certificates are verified.
If ``True``, the SSL certificate will be verified.
A CA_BUNDLE path can also be provided.
The ``client_cert`` tuple (cert,key) specifies a SSL client certificate and key files.
"""
def __init__(self, crowd_url, app_name, app_pass, ssl_verify=True,
timeout=None, client_cert=None):
self.crowd_url = crowd_url
self.app_name = app_name
self.app_pass = app_pass
self.rest_url = crowd_url.rstrip("/") + "/rest/usermanagement/1"
self.ssl_verify = ssl_verify
self.client_cert = client_cert
self.timeout = timeout
self.session = self._build_session(content_type='json')
self.session_xml = self._build_session(content_type='xml')
def __str__(self):
return "Crowd Server at %s" % self.crowd_url
def __repr__(self):
return "<CrowdServer('%s', '%s', '%s')>" % \
(self.crowd_url, self.app_name, self.app_pass)
def _build_session(self, content_type='json'):
headers = {
'Content-Type': 'application/{}'.format(content_type),
'Accept': 'application/{}'.format(content_type),
}
session = requests.Session()
session.verify = self.ssl_verify
session.cert = self.client_cert
session.auth = requests.auth.HTTPBasicAuth(self.app_name, self.app_pass)
session.headers.update(headers)
return session
def _get(self, *args, **kwargs):
"""Wrapper around Requests for GET requests
Returns:
Response:
A Requests Response object
"""
if 'timeout' not in kwargs:
kwargs['timeout'] = self.timeout
req = self.session.get(*args, **kwargs)
return req
def _get_xml(self, *args, **kwargs):
"""Wrapper around Requests for GET XML requests
Returns:
Response:
A Requests Response object
"""
req = self.session_xml.get(*args, **kwargs)
return req
def _post_xml(self, *args, **kwargs):
"""Wrapper around Requests for POST requests
Returns:
Response:
A Requests Response object
"""
if 'timeout' not in kwargs:
kwargs['timeout'] = self.timeout
req = self.session_xml.post(*args, **kwargs)
return req
def _put(self, *args, **kwargs):
"""Wrapper around Requests for PUT requests
Returns:
Response:
A Requests Response object
"""
if 'timeout' not in kwargs:
kwargs['timeout'] = self.timeout
req = self.session.put(*args, **kwargs)
return req
def _delete(self, *args, **kwargs):
"""Wrapper around Requests for DELETE requests
Returns:
Response:
A Requests Response object
"""
if 'timeout' not in kwargs:
kwargs['timeout'] = self.timeout
req = self.session.delete(*args, **kwargs)
return req
def auth_ping(self):
"""Test that application can authenticate to Crowd.
Attempts to authenticate the application user against
the Crowd server. In order for user authentication to
work, an application must be able to authenticate.
Returns:
bool:
True if the application authentication succeeded.
"""
url = self.rest_url + "/non-existent/location"
response = self._get(url)
if response.status_code == 401:
return False
elif response.status_code == 404:
return True
else:
# An error encountered - problem with the Crowd server?
return False
def auth_user(self, username, password):
"""Authenticate a user account against the Crowd server.
Attempts to authenticate the user against the Crowd server.
Args:
username: The account username.
password: The account password.
Returns:
dict:
A dict mapping of user attributes if the application
authentication was successful. See the Crowd documentation
for the authoritative list of attributes.
None: If authentication failed.
"""
response = self._post(self.rest_url + "/authentication",
data=json.dumps({"value": password}),
params={"username": username})
# If authentication failed for any reason return None
if not response.ok:
return None
# ...otherwise return a dictionary of user attributes
return response.json()
def get_session(self, username, password, remote="127.0.0.1", proxy=None):
"""Create a session for a user.
Attempts to create a user session on the Crowd server.
Args:
username: The account username.
password: The account password.
remote:
The remote address of the user. This can be used
to create multiple concurrent sessions for a user.
The host you run this program on may need to be configured
in Crowd as a trusted proxy for this to work.
proxy: Value of X-Forwarded-For server header.
Returns:
dict:
A dict mapping of user attributes if the application
authentication was successful. See the Crowd
documentation for the authoritative list of attributes.
None: If authentication failed.
"""
params = {
"username": username,
"password": password,
"validation-factors": {
"validationFactors": [
{"name": "remote_address", "value": remote, },
]
}
}
if proxy:
params["validation-factors"]["validationFactors"].append({"name": "X-Forwarded-For", "value": proxy, })
response = self._post(self.rest_url + "/session",
data=json.dumps(params),
params={"expand": "user"})
# If authentication failed for any reason return None
if not response.ok:
return None
# Otherwise return the user object
return response.json()
def validate_session(self, token, remote="127.0.0.1", proxy=None):
"""Validate a session token.
Validate a previously acquired session token against the
Crowd server. This may be a token provided by a user from
a http cookie or by some other means.
Args:
token: The session token.
remote: The remote address of the user.
proxy: Value of X-Forwarded-For server header
Returns:
dict:
A dict mapping of user attributes if the application
authentication was successful. See the Crowd
documentation for the authoritative list of attributes.
None: If authentication failed.
"""
params = {
"validationFactors": [
{"name": "remote_address", "value": remote, },
]
}
if proxy:
params["validation-factors"]["validationFactors"].append({"name": "X-Forwarded-For", "value": proxy, })
url = self.rest_url + "/session/%s" % token
response = self._post(url, data=json.dumps(params), params={"expand": "user"})
# For consistency between methods use None rather than False
# If token validation failed for any reason return None
if not response.ok:
return None
# Otherwise return the user object
return response.json()
def terminate_session(self, token):
"""Terminates the session token, effectively logging out the user
from all crowd-enabled services.
Args:
token: The session token.
Returns:
True: If session terminated
None: If session termination failed
"""
url = self.rest_url + "/session/%s" % token
response = self._delete(url)
# For consistency between methods use None rather than False
# If token validation failed for any reason return None
if not response.ok:
return None
# Otherwise return True
return True
def add_user(self, username, raise_on_error=False, **kwargs):
"""Add a user to the directory
Args:
username: The account username
raise_on_error: optional (default: False)
**kwargs: key-value pairs:
password: mandatory
email: mandatory
first_name: optional
last_name: optional
display_name: optional
active: optional (default True)
Returns:
True: Succeeded
False: If unsuccessful
"""
# Check that mandatory elements have been provided
if 'password' not in kwargs:
raise ValueError("missing password")
if 'email' not in kwargs:
raise ValueError("missing email")
# Populate data with default and mandatory values.
# A KeyError means a mandatory value was not provided,
# so raise a ValueError indicating bad args.
try:
data = {
"name": username,
"first-name": username,
"last-name": username,
"display-name": username,
"email": kwargs["email"],
"password": {"value": kwargs["password"]},
"active": True
}
except KeyError:
return ValueError
# Remove special case 'password'
del(kwargs["password"])
# Put values from kwargs into data
for k, v in kwargs.items():
new_k = k.replace("_", "-")
if new_k not in data:
raise ValueError("invalid argument %s" % k)
data[new_k] = v
response = self._post(self.rest_url + "/user",
data=json.dumps(data))
if response.status_code == 201:
return True
if raise_on_error:
raise RuntimeError(response.json()['message'])
return False
def get_user(self, username):
"""Retrieve information about a user
Returns:
dict: User information
None: If no user or failure occurred
"""
response = self._get(self.rest_url + "/user",
params={"username": username,
"expand": "attributes"})
if not response.ok:
return None
return response.json()
def set_active(self, username, active_state):
"""Set the active state of a user
Args:
username: The account username
active_state: True or False
Returns:
True: If successful
None: If no user or failure occurred
"""
if active_state not in (True, False):
raise ValueError("active_state must be True or False")
user = self.get_user(username)
if user is None:
return None
if user['active'] is active_state:
# Already in desired state
return True
user['active'] = active_state
response = self._put(self.rest_url + "/user",
params={"username": username},
data=json.dumps(user))
if response.status_code == 204:
return True
return None
def set_user_attribute(self, username, attribute, value, raise_on_error=False):
"""Set an attribute on a user
:param username: The username on which to set the attribute
:param attribute: The name of the attribute to set
:param value: The value of the attribute to set
:return: True on success, False on failure.
"""
data = {
'attributes': [
{
'name': attribute,
'values': [
value
]
},
]
}
response = self._post(self.rest_url + "/user/attribute",
params={"username": username,},
data=json.dumps(data))
if response.status_code == 204:
return True
if raise_on_error:
raise RuntimeError(response.json()['message'])
return False
def add_user_to_group(self, username, groupname, raise_on_error=False):
"""Add a user to a group
:param username: The username to assign to the group
:param groupname: The group name into which to assign the user
:return: True on success, False on failure.
"""
data = {
'name': groupname,
}
response = self._post(self.rest_url + "/user/group/direct",
params={"username": username,},
data=json.dumps(data))
if response.status_code == 201:
return True
if raise_on_error:
raise RuntimeError(response.json()['message'])
return False
def remove_user_from_group(self, username, groupname, raise_on_error=False):
"""Remove a user from a group
Attempts to remove a user from a group
Args
username: The username to remove from the group.
groupname: The group name to be removed from the user.
Returns:
True: Succeeded
False: If unsuccessful
"""
response = self._delete(self.rest_url + "/group/user/direct",params={"username": username, "groupname": groupname})
if response.status_code == 204:
return True
if raise_on_error:
raise RuntimeError(response.json()['message'])
return False
def change_password(self, username, newpassword, raise_on_error=False):
"""Change new password for a user
Args:
username: The account username.
newpassword: The account new password.
raise_on_error: optional (default: False)
Returns:
True: Succeeded
False: If unsuccessful
"""
response = self._put(self.rest_url + "/user/password",
data=json.dumps({"value": newpassword}),
params={"username": username})
if response.ok:
return True
if raise_on_error:
raise RuntimeError(response.json()['message'])
return False
def send_password_reset_link(self, username):
"""Sends the user a password reset link (by email)
Args:
username: The account username.
Returns:
True: Succeeded
False: If unsuccessful
"""
response = self._post(self.rest_url + "/user/mail/password",
params={"username": username})
if response.ok:
return True
return False
def get_groups(self, username):
"""Retrieves a list of group names that have <username> as a direct member.
Returns:
list:
A list of strings of group names.
"""
response = self._get(self.rest_url + "/user/group/direct",
params={"username": username})
if not response.ok:
return None
return [g['name'] for g in response.json()['groups']]
def get_nested_groups(self, username):
"""Retrieve a list of all group names that have <username> as a direct or indirect member.
Args:
username: The account username.
Returns:
list:
A list of strings of group names.
"""
response = self._get(self.rest_url + "/user/group/nested",
params={"username": username})
if not response.ok:
return None
return [g['name'] for g in response.json()['groups']]
def get_nested_group_users(self, groupname):
"""Retrieves a list of all users that directly or indirectly belong to the given groupname.
Args:
groupname: The group name.
Returns:
list:
A list of strings of user names.
"""
response = self._get(self.rest_url + "/group/user/nested",
params={"groupname": groupname,
"start-index": 0,
"max-results": 99999})
if not response.ok:
return None
return [u['name'] for u in response.json()['users']]
def user_exists(self, username):
"""Determines if the user exists.
Args:
username: The user name.
Returns:
bool:
True if the user exists in the Crowd application.
"""
response = self._get(self.rest_url + "/user",
params={"username": username})
if not response.ok:
return None
return True
def get_memberships(self):
"""Fetches all group memberships.
Returns:
dict:
key: group name
value: (array of users, array of groups)
"""
response = self._get_xml(self.rest_url + "/group/membership")
if not response.ok:
return None
xmltree = etree.fromstring(response.content)
memberships = {}
for mg in xmltree.findall('membership'):
# coerce values to unicode in a python 2 and 3 compatible way
group = u'{}'.format(mg.get('group'))
users = [u'{}'.format(u.get('name')) for u in mg.find('users').findall('user')]
groups = [u'{}'.format(g.get('name')) for g in mg.find('groups').findall('group')]
memberships[group] = {u'users': users, u'groups': groups}
return memberships
def search(self, entity_type, property_name, search_string, start_index=0, max_results=99999):
"""Performs a user search using the Crowd search API.
https://developer.atlassian.com/display/CROWDDEV/Crowd+REST+Resources#CrowdRESTResources-SearchResource
Args:
entity_type: 'user' or 'group'
property_name: eg. 'email', 'name'
search_string: the string to search for.
start_index: starting index of the results (default: 0)
max_results: maximum number of results returned (default: 99999)
Returns:
json results:
Returns search results.
"""
params = {
"entity-type": entity_type,
"expand": entity_type,
"property-search-restriction": {
"property": {"name": property_name, "type": "STRING"},
"match-mode": "CONTAINS",
"value": search_string,
}
}
params = {
'entity-type': entity_type,
'expand': entity_type,
'start-index': start_index,
'max-results': max_results
}
# Construct XML payload of the form:
# <property-search-restriction>
# <property>
# <name>email</name>
# <type>STRING</type>
# </property>
# <match-mode>EXACTLY_MATCHES</match-mode>
# <value>bob@example.net</value>
# </property-search-restriction>
root = etree.Element('property-search-restriction')
property_ = etree.Element('property')
prop_name = etree.Element('name')
prop_name.text = property_name
property_.append(prop_name)
prop_type = etree.Element('type')
prop_type.text = 'STRING'
property_.append(prop_type)
root.append(property_)
match_mode = etree.Element('match-mode')
match_mode.text = 'CONTAINS'
root.append(match_mode)
value = etree.Element('value')
value.text = search_string
root.append(value)
# Construct the XML payload expected by search API
payload = '<?xml version="1.0" encoding="UTF-8"?>\n' + etree.tostring(root).decode('utf-8')
# We're sending XML but would like a JSON response
session = self._build_session(content_type='xml')
session.headers.update({'Accept': 'application/json'})
response = session.post(self.rest_url + "/search", params=params, data=payload, timeout=self.timeout)
if not response.ok:
return None
return response.json()
|
pycontribs/python-crowd | crowd.py | CrowdServer._post_xml | python | def _post_xml(self, *args, **kwargs):
if 'timeout' not in kwargs:
kwargs['timeout'] = self.timeout
req = self.session_xml.post(*args, **kwargs)
return req | Wrapper around Requests for POST requests
Returns:
Response:
A Requests Response object | train | https://github.com/pycontribs/python-crowd/blob/a075e45774dd5baecf0217843cda747084268e32/crowd.py#L108-L120 | null | class CrowdServer(object):
"""Crowd server authentication object.
This is a Crowd authentication class to be configured for a
particular application (app_name) to authenticate users
against a Crowd server (crowd_url).
This module uses the Crowd JSON API for talking to Crowd.
An application account must be configured in the Crowd server
and permitted to authenticate users against one or more user
directories prior to using this module.
Please see the Crowd documentation for information about
configuring additional applications to talk to Crowd.
The ``ssl_verify`` parameter controls how and if certificates are verified.
If ``True``, the SSL certificate will be verified.
A CA_BUNDLE path can also be provided.
The ``client_cert`` tuple (cert,key) specifies a SSL client certificate and key files.
"""
def __init__(self, crowd_url, app_name, app_pass, ssl_verify=True,
timeout=None, client_cert=None):
self.crowd_url = crowd_url
self.app_name = app_name
self.app_pass = app_pass
self.rest_url = crowd_url.rstrip("/") + "/rest/usermanagement/1"
self.ssl_verify = ssl_verify
self.client_cert = client_cert
self.timeout = timeout
self.session = self._build_session(content_type='json')
self.session_xml = self._build_session(content_type='xml')
def __str__(self):
return "Crowd Server at %s" % self.crowd_url
def __repr__(self):
return "<CrowdServer('%s', '%s', '%s')>" % \
(self.crowd_url, self.app_name, self.app_pass)
def _build_session(self, content_type='json'):
headers = {
'Content-Type': 'application/{}'.format(content_type),
'Accept': 'application/{}'.format(content_type),
}
session = requests.Session()
session.verify = self.ssl_verify
session.cert = self.client_cert
session.auth = requests.auth.HTTPBasicAuth(self.app_name, self.app_pass)
session.headers.update(headers)
return session
def _get(self, *args, **kwargs):
"""Wrapper around Requests for GET requests
Returns:
Response:
A Requests Response object
"""
if 'timeout' not in kwargs:
kwargs['timeout'] = self.timeout
req = self.session.get(*args, **kwargs)
return req
def _get_xml(self, *args, **kwargs):
"""Wrapper around Requests for GET XML requests
Returns:
Response:
A Requests Response object
"""
req = self.session_xml.get(*args, **kwargs)
return req
def _post(self, *args, **kwargs):
"""Wrapper around Requests for POST requests
Returns:
Response:
A Requests Response object
"""
if 'timeout' not in kwargs:
kwargs['timeout'] = self.timeout
req = self.session.post(*args, **kwargs)
return req
def _put(self, *args, **kwargs):
"""Wrapper around Requests for PUT requests
Returns:
Response:
A Requests Response object
"""
if 'timeout' not in kwargs:
kwargs['timeout'] = self.timeout
req = self.session.put(*args, **kwargs)
return req
def _delete(self, *args, **kwargs):
"""Wrapper around Requests for DELETE requests
Returns:
Response:
A Requests Response object
"""
if 'timeout' not in kwargs:
kwargs['timeout'] = self.timeout
req = self.session.delete(*args, **kwargs)
return req
def auth_ping(self):
"""Test that application can authenticate to Crowd.
Attempts to authenticate the application user against
the Crowd server. In order for user authentication to
work, an application must be able to authenticate.
Returns:
bool:
True if the application authentication succeeded.
"""
url = self.rest_url + "/non-existent/location"
response = self._get(url)
if response.status_code == 401:
return False
elif response.status_code == 404:
return True
else:
# An error encountered - problem with the Crowd server?
return False
def auth_user(self, username, password):
"""Authenticate a user account against the Crowd server.
Attempts to authenticate the user against the Crowd server.
Args:
username: The account username.
password: The account password.
Returns:
dict:
A dict mapping of user attributes if the application
authentication was successful. See the Crowd documentation
for the authoritative list of attributes.
None: If authentication failed.
"""
response = self._post(self.rest_url + "/authentication",
data=json.dumps({"value": password}),
params={"username": username})
# If authentication failed for any reason return None
if not response.ok:
return None
# ...otherwise return a dictionary of user attributes
return response.json()
def get_session(self, username, password, remote="127.0.0.1", proxy=None):
"""Create a session for a user.
Attempts to create a user session on the Crowd server.
Args:
username: The account username.
password: The account password.
remote:
The remote address of the user. This can be used
to create multiple concurrent sessions for a user.
The host you run this program on may need to be configured
in Crowd as a trusted proxy for this to work.
proxy: Value of X-Forwarded-For server header.
Returns:
dict:
A dict mapping of user attributes if the application
authentication was successful. See the Crowd
documentation for the authoritative list of attributes.
None: If authentication failed.
"""
params = {
"username": username,
"password": password,
"validation-factors": {
"validationFactors": [
{"name": "remote_address", "value": remote, },
]
}
}
if proxy:
params["validation-factors"]["validationFactors"].append({"name": "X-Forwarded-For", "value": proxy, })
response = self._post(self.rest_url + "/session",
data=json.dumps(params),
params={"expand": "user"})
# If authentication failed for any reason return None
if not response.ok:
return None
# Otherwise return the user object
return response.json()
def validate_session(self, token, remote="127.0.0.1", proxy=None):
"""Validate a session token.
Validate a previously acquired session token against the
Crowd server. This may be a token provided by a user from
a http cookie or by some other means.
Args:
token: The session token.
remote: The remote address of the user.
proxy: Value of X-Forwarded-For server header
Returns:
dict:
A dict mapping of user attributes if the application
authentication was successful. See the Crowd
documentation for the authoritative list of attributes.
None: If authentication failed.
"""
params = {
"validationFactors": [
{"name": "remote_address", "value": remote, },
]
}
if proxy:
params["validation-factors"]["validationFactors"].append({"name": "X-Forwarded-For", "value": proxy, })
url = self.rest_url + "/session/%s" % token
response = self._post(url, data=json.dumps(params), params={"expand": "user"})
# For consistency between methods use None rather than False
# If token validation failed for any reason return None
if not response.ok:
return None
# Otherwise return the user object
return response.json()
def terminate_session(self, token):
"""Terminates the session token, effectively logging out the user
from all crowd-enabled services.
Args:
token: The session token.
Returns:
True: If session terminated
None: If session termination failed
"""
url = self.rest_url + "/session/%s" % token
response = self._delete(url)
# For consistency between methods use None rather than False
# If token validation failed for any reason return None
if not response.ok:
return None
# Otherwise return True
return True
def add_user(self, username, raise_on_error=False, **kwargs):
"""Add a user to the directory
Args:
username: The account username
raise_on_error: optional (default: False)
**kwargs: key-value pairs:
password: mandatory
email: mandatory
first_name: optional
last_name: optional
display_name: optional
active: optional (default True)
Returns:
True: Succeeded
False: If unsuccessful
"""
# Check that mandatory elements have been provided
if 'password' not in kwargs:
raise ValueError("missing password")
if 'email' not in kwargs:
raise ValueError("missing email")
# Populate data with default and mandatory values.
# A KeyError means a mandatory value was not provided,
# so raise a ValueError indicating bad args.
try:
data = {
"name": username,
"first-name": username,
"last-name": username,
"display-name": username,
"email": kwargs["email"],
"password": {"value": kwargs["password"]},
"active": True
}
except KeyError:
return ValueError
# Remove special case 'password'
del(kwargs["password"])
# Put values from kwargs into data
for k, v in kwargs.items():
new_k = k.replace("_", "-")
if new_k not in data:
raise ValueError("invalid argument %s" % k)
data[new_k] = v
response = self._post(self.rest_url + "/user",
data=json.dumps(data))
if response.status_code == 201:
return True
if raise_on_error:
raise RuntimeError(response.json()['message'])
return False
def get_user(self, username):
"""Retrieve information about a user
Returns:
dict: User information
None: If no user or failure occurred
"""
response = self._get(self.rest_url + "/user",
params={"username": username,
"expand": "attributes"})
if not response.ok:
return None
return response.json()
def set_active(self, username, active_state):
"""Set the active state of a user
Args:
username: The account username
active_state: True or False
Returns:
True: If successful
None: If no user or failure occurred
"""
if active_state not in (True, False):
raise ValueError("active_state must be True or False")
user = self.get_user(username)
if user is None:
return None
if user['active'] is active_state:
# Already in desired state
return True
user['active'] = active_state
response = self._put(self.rest_url + "/user",
params={"username": username},
data=json.dumps(user))
if response.status_code == 204:
return True
return None
def set_user_attribute(self, username, attribute, value, raise_on_error=False):
"""Set an attribute on a user
:param username: The username on which to set the attribute
:param attribute: The name of the attribute to set
:param value: The value of the attribute to set
:return: True on success, False on failure.
"""
data = {
'attributes': [
{
'name': attribute,
'values': [
value
]
},
]
}
response = self._post(self.rest_url + "/user/attribute",
params={"username": username,},
data=json.dumps(data))
if response.status_code == 204:
return True
if raise_on_error:
raise RuntimeError(response.json()['message'])
return False
def add_user_to_group(self, username, groupname, raise_on_error=False):
"""Add a user to a group
:param username: The username to assign to the group
:param groupname: The group name into which to assign the user
:return: True on success, False on failure.
"""
data = {
'name': groupname,
}
response = self._post(self.rest_url + "/user/group/direct",
params={"username": username,},
data=json.dumps(data))
if response.status_code == 201:
return True
if raise_on_error:
raise RuntimeError(response.json()['message'])
return False
def remove_user_from_group(self, username, groupname, raise_on_error=False):
"""Remove a user from a group
Attempts to remove a user from a group
Args
username: The username to remove from the group.
groupname: The group name to be removed from the user.
Returns:
True: Succeeded
False: If unsuccessful
"""
response = self._delete(self.rest_url + "/group/user/direct",params={"username": username, "groupname": groupname})
if response.status_code == 204:
return True
if raise_on_error:
raise RuntimeError(response.json()['message'])
return False
def change_password(self, username, newpassword, raise_on_error=False):
"""Change new password for a user
Args:
username: The account username.
newpassword: The account new password.
raise_on_error: optional (default: False)
Returns:
True: Succeeded
False: If unsuccessful
"""
response = self._put(self.rest_url + "/user/password",
data=json.dumps({"value": newpassword}),
params={"username": username})
if response.ok:
return True
if raise_on_error:
raise RuntimeError(response.json()['message'])
return False
def send_password_reset_link(self, username):
"""Sends the user a password reset link (by email)
Args:
username: The account username.
Returns:
True: Succeeded
False: If unsuccessful
"""
response = self._post(self.rest_url + "/user/mail/password",
params={"username": username})
if response.ok:
return True
return False
def get_groups(self, username):
"""Retrieves a list of group names that have <username> as a direct member.
Returns:
list:
A list of strings of group names.
"""
response = self._get(self.rest_url + "/user/group/direct",
params={"username": username})
if not response.ok:
return None
return [g['name'] for g in response.json()['groups']]
def get_nested_groups(self, username):
"""Retrieve a list of all group names that have <username> as a direct or indirect member.
Args:
username: The account username.
Returns:
list:
A list of strings of group names.
"""
response = self._get(self.rest_url + "/user/group/nested",
params={"username": username})
if not response.ok:
return None
return [g['name'] for g in response.json()['groups']]
def get_nested_group_users(self, groupname):
"""Retrieves a list of all users that directly or indirectly belong to the given groupname.
Args:
groupname: The group name.
Returns:
list:
A list of strings of user names.
"""
response = self._get(self.rest_url + "/group/user/nested",
params={"groupname": groupname,
"start-index": 0,
"max-results": 99999})
if not response.ok:
return None
return [u['name'] for u in response.json()['users']]
def user_exists(self, username):
"""Determines if the user exists.
Args:
username: The user name.
Returns:
bool:
True if the user exists in the Crowd application.
"""
response = self._get(self.rest_url + "/user",
params={"username": username})
if not response.ok:
return None
return True
def get_memberships(self):
"""Fetches all group memberships.
Returns:
dict:
key: group name
value: (array of users, array of groups)
"""
response = self._get_xml(self.rest_url + "/group/membership")
if not response.ok:
return None
xmltree = etree.fromstring(response.content)
memberships = {}
for mg in xmltree.findall('membership'):
# coerce values to unicode in a python 2 and 3 compatible way
group = u'{}'.format(mg.get('group'))
users = [u'{}'.format(u.get('name')) for u in mg.find('users').findall('user')]
groups = [u'{}'.format(g.get('name')) for g in mg.find('groups').findall('group')]
memberships[group] = {u'users': users, u'groups': groups}
return memberships
def search(self, entity_type, property_name, search_string, start_index=0, max_results=99999):
"""Performs a user search using the Crowd search API.
https://developer.atlassian.com/display/CROWDDEV/Crowd+REST+Resources#CrowdRESTResources-SearchResource
Args:
entity_type: 'user' or 'group'
property_name: eg. 'email', 'name'
search_string: the string to search for.
start_index: starting index of the results (default: 0)
max_results: maximum number of results returned (default: 99999)
Returns:
json results:
Returns search results.
"""
params = {
"entity-type": entity_type,
"expand": entity_type,
"property-search-restriction": {
"property": {"name": property_name, "type": "STRING"},
"match-mode": "CONTAINS",
"value": search_string,
}
}
params = {
'entity-type': entity_type,
'expand': entity_type,
'start-index': start_index,
'max-results': max_results
}
# Construct XML payload of the form:
# <property-search-restriction>
# <property>
# <name>email</name>
# <type>STRING</type>
# </property>
# <match-mode>EXACTLY_MATCHES</match-mode>
# <value>bob@example.net</value>
# </property-search-restriction>
root = etree.Element('property-search-restriction')
property_ = etree.Element('property')
prop_name = etree.Element('name')
prop_name.text = property_name
property_.append(prop_name)
prop_type = etree.Element('type')
prop_type.text = 'STRING'
property_.append(prop_type)
root.append(property_)
match_mode = etree.Element('match-mode')
match_mode.text = 'CONTAINS'
root.append(match_mode)
value = etree.Element('value')
value.text = search_string
root.append(value)
# Construct the XML payload expected by search API
payload = '<?xml version="1.0" encoding="UTF-8"?>\n' + etree.tostring(root).decode('utf-8')
# We're sending XML but would like a JSON response
session = self._build_session(content_type='xml')
session.headers.update({'Accept': 'application/json'})
response = session.post(self.rest_url + "/search", params=params, data=payload, timeout=self.timeout)
if not response.ok:
return None
return response.json()
|
pycontribs/python-crowd | crowd.py | CrowdServer._put | python | def _put(self, *args, **kwargs):
if 'timeout' not in kwargs:
kwargs['timeout'] = self.timeout
req = self.session.put(*args, **kwargs)
return req | Wrapper around Requests for PUT requests
Returns:
Response:
A Requests Response object | train | https://github.com/pycontribs/python-crowd/blob/a075e45774dd5baecf0217843cda747084268e32/crowd.py#L122-L134 | null | class CrowdServer(object):
"""Crowd server authentication object.
This is a Crowd authentication class to be configured for a
particular application (app_name) to authenticate users
against a Crowd server (crowd_url).
This module uses the Crowd JSON API for talking to Crowd.
An application account must be configured in the Crowd server
and permitted to authenticate users against one or more user
directories prior to using this module.
Please see the Crowd documentation for information about
configuring additional applications to talk to Crowd.
The ``ssl_verify`` parameter controls how and if certificates are verified.
If ``True``, the SSL certificate will be verified.
A CA_BUNDLE path can also be provided.
The ``client_cert`` tuple (cert,key) specifies a SSL client certificate and key files.
"""
def __init__(self, crowd_url, app_name, app_pass, ssl_verify=True,
timeout=None, client_cert=None):
self.crowd_url = crowd_url
self.app_name = app_name
self.app_pass = app_pass
self.rest_url = crowd_url.rstrip("/") + "/rest/usermanagement/1"
self.ssl_verify = ssl_verify
self.client_cert = client_cert
self.timeout = timeout
self.session = self._build_session(content_type='json')
self.session_xml = self._build_session(content_type='xml')
def __str__(self):
return "Crowd Server at %s" % self.crowd_url
def __repr__(self):
return "<CrowdServer('%s', '%s', '%s')>" % \
(self.crowd_url, self.app_name, self.app_pass)
def _build_session(self, content_type='json'):
headers = {
'Content-Type': 'application/{}'.format(content_type),
'Accept': 'application/{}'.format(content_type),
}
session = requests.Session()
session.verify = self.ssl_verify
session.cert = self.client_cert
session.auth = requests.auth.HTTPBasicAuth(self.app_name, self.app_pass)
session.headers.update(headers)
return session
def _get(self, *args, **kwargs):
"""Wrapper around Requests for GET requests
Returns:
Response:
A Requests Response object
"""
if 'timeout' not in kwargs:
kwargs['timeout'] = self.timeout
req = self.session.get(*args, **kwargs)
return req
def _get_xml(self, *args, **kwargs):
"""Wrapper around Requests for GET XML requests
Returns:
Response:
A Requests Response object
"""
req = self.session_xml.get(*args, **kwargs)
return req
def _post(self, *args, **kwargs):
"""Wrapper around Requests for POST requests
Returns:
Response:
A Requests Response object
"""
if 'timeout' not in kwargs:
kwargs['timeout'] = self.timeout
req = self.session.post(*args, **kwargs)
return req
def _post_xml(self, *args, **kwargs):
"""Wrapper around Requests for POST requests
Returns:
Response:
A Requests Response object
"""
if 'timeout' not in kwargs:
kwargs['timeout'] = self.timeout
req = self.session_xml.post(*args, **kwargs)
return req
def _delete(self, *args, **kwargs):
"""Wrapper around Requests for DELETE requests
Returns:
Response:
A Requests Response object
"""
if 'timeout' not in kwargs:
kwargs['timeout'] = self.timeout
req = self.session.delete(*args, **kwargs)
return req
def auth_ping(self):
"""Test that application can authenticate to Crowd.
Attempts to authenticate the application user against
the Crowd server. In order for user authentication to
work, an application must be able to authenticate.
Returns:
bool:
True if the application authentication succeeded.
"""
url = self.rest_url + "/non-existent/location"
response = self._get(url)
if response.status_code == 401:
return False
elif response.status_code == 404:
return True
else:
# An error encountered - problem with the Crowd server?
return False
def auth_user(self, username, password):
"""Authenticate a user account against the Crowd server.
Attempts to authenticate the user against the Crowd server.
Args:
username: The account username.
password: The account password.
Returns:
dict:
A dict mapping of user attributes if the application
authentication was successful. See the Crowd documentation
for the authoritative list of attributes.
None: If authentication failed.
"""
response = self._post(self.rest_url + "/authentication",
data=json.dumps({"value": password}),
params={"username": username})
# If authentication failed for any reason return None
if not response.ok:
return None
# ...otherwise return a dictionary of user attributes
return response.json()
def get_session(self, username, password, remote="127.0.0.1", proxy=None):
"""Create a session for a user.
Attempts to create a user session on the Crowd server.
Args:
username: The account username.
password: The account password.
remote:
The remote address of the user. This can be used
to create multiple concurrent sessions for a user.
The host you run this program on may need to be configured
in Crowd as a trusted proxy for this to work.
proxy: Value of X-Forwarded-For server header.
Returns:
dict:
A dict mapping of user attributes if the application
authentication was successful. See the Crowd
documentation for the authoritative list of attributes.
None: If authentication failed.
"""
params = {
"username": username,
"password": password,
"validation-factors": {
"validationFactors": [
{"name": "remote_address", "value": remote, },
]
}
}
if proxy:
params["validation-factors"]["validationFactors"].append({"name": "X-Forwarded-For", "value": proxy, })
response = self._post(self.rest_url + "/session",
data=json.dumps(params),
params={"expand": "user"})
# If authentication failed for any reason return None
if not response.ok:
return None
# Otherwise return the user object
return response.json()
def validate_session(self, token, remote="127.0.0.1", proxy=None):
"""Validate a session token.
Validate a previously acquired session token against the
Crowd server. This may be a token provided by a user from
a http cookie or by some other means.
Args:
token: The session token.
remote: The remote address of the user.
proxy: Value of X-Forwarded-For server header
Returns:
dict:
A dict mapping of user attributes if the application
authentication was successful. See the Crowd
documentation for the authoritative list of attributes.
None: If authentication failed.
"""
params = {
"validationFactors": [
{"name": "remote_address", "value": remote, },
]
}
if proxy:
params["validation-factors"]["validationFactors"].append({"name": "X-Forwarded-For", "value": proxy, })
url = self.rest_url + "/session/%s" % token
response = self._post(url, data=json.dumps(params), params={"expand": "user"})
# For consistency between methods use None rather than False
# If token validation failed for any reason return None
if not response.ok:
return None
# Otherwise return the user object
return response.json()
def terminate_session(self, token):
"""Terminates the session token, effectively logging out the user
from all crowd-enabled services.
Args:
token: The session token.
Returns:
True: If session terminated
None: If session termination failed
"""
url = self.rest_url + "/session/%s" % token
response = self._delete(url)
# For consistency between methods use None rather than False
# If token validation failed for any reason return None
if not response.ok:
return None
# Otherwise return True
return True
def add_user(self, username, raise_on_error=False, **kwargs):
"""Add a user to the directory
Args:
username: The account username
raise_on_error: optional (default: False)
**kwargs: key-value pairs:
password: mandatory
email: mandatory
first_name: optional
last_name: optional
display_name: optional
active: optional (default True)
Returns:
True: Succeeded
False: If unsuccessful
"""
# Check that mandatory elements have been provided
if 'password' not in kwargs:
raise ValueError("missing password")
if 'email' not in kwargs:
raise ValueError("missing email")
# Populate data with default and mandatory values.
# A KeyError means a mandatory value was not provided,
# so raise a ValueError indicating bad args.
try:
data = {
"name": username,
"first-name": username,
"last-name": username,
"display-name": username,
"email": kwargs["email"],
"password": {"value": kwargs["password"]},
"active": True
}
except KeyError:
return ValueError
# Remove special case 'password'
del(kwargs["password"])
# Put values from kwargs into data
for k, v in kwargs.items():
new_k = k.replace("_", "-")
if new_k not in data:
raise ValueError("invalid argument %s" % k)
data[new_k] = v
response = self._post(self.rest_url + "/user",
data=json.dumps(data))
if response.status_code == 201:
return True
if raise_on_error:
raise RuntimeError(response.json()['message'])
return False
def get_user(self, username):
"""Retrieve information about a user
Returns:
dict: User information
None: If no user or failure occurred
"""
response = self._get(self.rest_url + "/user",
params={"username": username,
"expand": "attributes"})
if not response.ok:
return None
return response.json()
def set_active(self, username, active_state):
"""Set the active state of a user
Args:
username: The account username
active_state: True or False
Returns:
True: If successful
None: If no user or failure occurred
"""
if active_state not in (True, False):
raise ValueError("active_state must be True or False")
user = self.get_user(username)
if user is None:
return None
if user['active'] is active_state:
# Already in desired state
return True
user['active'] = active_state
response = self._put(self.rest_url + "/user",
params={"username": username},
data=json.dumps(user))
if response.status_code == 204:
return True
return None
def set_user_attribute(self, username, attribute, value, raise_on_error=False):
"""Set an attribute on a user
:param username: The username on which to set the attribute
:param attribute: The name of the attribute to set
:param value: The value of the attribute to set
:return: True on success, False on failure.
"""
data = {
'attributes': [
{
'name': attribute,
'values': [
value
]
},
]
}
response = self._post(self.rest_url + "/user/attribute",
params={"username": username,},
data=json.dumps(data))
if response.status_code == 204:
return True
if raise_on_error:
raise RuntimeError(response.json()['message'])
return False
def add_user_to_group(self, username, groupname, raise_on_error=False):
"""Add a user to a group
:param username: The username to assign to the group
:param groupname: The group name into which to assign the user
:return: True on success, False on failure.
"""
data = {
'name': groupname,
}
response = self._post(self.rest_url + "/user/group/direct",
params={"username": username,},
data=json.dumps(data))
if response.status_code == 201:
return True
if raise_on_error:
raise RuntimeError(response.json()['message'])
return False
def remove_user_from_group(self, username, groupname, raise_on_error=False):
"""Remove a user from a group
Attempts to remove a user from a group
Args
username: The username to remove from the group.
groupname: The group name to be removed from the user.
Returns:
True: Succeeded
False: If unsuccessful
"""
response = self._delete(self.rest_url + "/group/user/direct",params={"username": username, "groupname": groupname})
if response.status_code == 204:
return True
if raise_on_error:
raise RuntimeError(response.json()['message'])
return False
def change_password(self, username, newpassword, raise_on_error=False):
"""Change new password for a user
Args:
username: The account username.
newpassword: The account new password.
raise_on_error: optional (default: False)
Returns:
True: Succeeded
False: If unsuccessful
"""
response = self._put(self.rest_url + "/user/password",
data=json.dumps({"value": newpassword}),
params={"username": username})
if response.ok:
return True
if raise_on_error:
raise RuntimeError(response.json()['message'])
return False
def send_password_reset_link(self, username):
"""Sends the user a password reset link (by email)
Args:
username: The account username.
Returns:
True: Succeeded
False: If unsuccessful
"""
response = self._post(self.rest_url + "/user/mail/password",
params={"username": username})
if response.ok:
return True
return False
def get_groups(self, username):
"""Retrieves a list of group names that have <username> as a direct member.
Returns:
list:
A list of strings of group names.
"""
response = self._get(self.rest_url + "/user/group/direct",
params={"username": username})
if not response.ok:
return None
return [g['name'] for g in response.json()['groups']]
def get_nested_groups(self, username):
"""Retrieve a list of all group names that have <username> as a direct or indirect member.
Args:
username: The account username.
Returns:
list:
A list of strings of group names.
"""
response = self._get(self.rest_url + "/user/group/nested",
params={"username": username})
if not response.ok:
return None
return [g['name'] for g in response.json()['groups']]
def get_nested_group_users(self, groupname):
"""Retrieves a list of all users that directly or indirectly belong to the given groupname.
Args:
groupname: The group name.
Returns:
list:
A list of strings of user names.
"""
response = self._get(self.rest_url + "/group/user/nested",
params={"groupname": groupname,
"start-index": 0,
"max-results": 99999})
if not response.ok:
return None
return [u['name'] for u in response.json()['users']]
def user_exists(self, username):
"""Determines if the user exists.
Args:
username: The user name.
Returns:
bool:
True if the user exists in the Crowd application.
"""
response = self._get(self.rest_url + "/user",
params={"username": username})
if not response.ok:
return None
return True
def get_memberships(self):
"""Fetches all group memberships.
Returns:
dict:
key: group name
value: (array of users, array of groups)
"""
response = self._get_xml(self.rest_url + "/group/membership")
if not response.ok:
return None
xmltree = etree.fromstring(response.content)
memberships = {}
for mg in xmltree.findall('membership'):
# coerce values to unicode in a python 2 and 3 compatible way
group = u'{}'.format(mg.get('group'))
users = [u'{}'.format(u.get('name')) for u in mg.find('users').findall('user')]
groups = [u'{}'.format(g.get('name')) for g in mg.find('groups').findall('group')]
memberships[group] = {u'users': users, u'groups': groups}
return memberships
def search(self, entity_type, property_name, search_string, start_index=0, max_results=99999):
"""Performs a user search using the Crowd search API.
https://developer.atlassian.com/display/CROWDDEV/Crowd+REST+Resources#CrowdRESTResources-SearchResource
Args:
entity_type: 'user' or 'group'
property_name: eg. 'email', 'name'
search_string: the string to search for.
start_index: starting index of the results (default: 0)
max_results: maximum number of results returned (default: 99999)
Returns:
json results:
Returns search results.
"""
params = {
"entity-type": entity_type,
"expand": entity_type,
"property-search-restriction": {
"property": {"name": property_name, "type": "STRING"},
"match-mode": "CONTAINS",
"value": search_string,
}
}
params = {
'entity-type': entity_type,
'expand': entity_type,
'start-index': start_index,
'max-results': max_results
}
# Construct XML payload of the form:
# <property-search-restriction>
# <property>
# <name>email</name>
# <type>STRING</type>
# </property>
# <match-mode>EXACTLY_MATCHES</match-mode>
# <value>bob@example.net</value>
# </property-search-restriction>
root = etree.Element('property-search-restriction')
property_ = etree.Element('property')
prop_name = etree.Element('name')
prop_name.text = property_name
property_.append(prop_name)
prop_type = etree.Element('type')
prop_type.text = 'STRING'
property_.append(prop_type)
root.append(property_)
match_mode = etree.Element('match-mode')
match_mode.text = 'CONTAINS'
root.append(match_mode)
value = etree.Element('value')
value.text = search_string
root.append(value)
# Construct the XML payload expected by search API
payload = '<?xml version="1.0" encoding="UTF-8"?>\n' + etree.tostring(root).decode('utf-8')
# We're sending XML but would like a JSON response
session = self._build_session(content_type='xml')
session.headers.update({'Accept': 'application/json'})
response = session.post(self.rest_url + "/search", params=params, data=payload, timeout=self.timeout)
if not response.ok:
return None
return response.json()
|
pycontribs/python-crowd | crowd.py | CrowdServer._delete | python | def _delete(self, *args, **kwargs):
if 'timeout' not in kwargs:
kwargs['timeout'] = self.timeout
req = self.session.delete(*args, **kwargs)
return req | Wrapper around Requests for DELETE requests
Returns:
Response:
A Requests Response object | train | https://github.com/pycontribs/python-crowd/blob/a075e45774dd5baecf0217843cda747084268e32/crowd.py#L136-L148 | null | class CrowdServer(object):
"""Crowd server authentication object.
This is a Crowd authentication class to be configured for a
particular application (app_name) to authenticate users
against a Crowd server (crowd_url).
This module uses the Crowd JSON API for talking to Crowd.
An application account must be configured in the Crowd server
and permitted to authenticate users against one or more user
directories prior to using this module.
Please see the Crowd documentation for information about
configuring additional applications to talk to Crowd.
The ``ssl_verify`` parameter controls how and if certificates are verified.
If ``True``, the SSL certificate will be verified.
A CA_BUNDLE path can also be provided.
The ``client_cert`` tuple (cert,key) specifies a SSL client certificate and key files.
"""
def __init__(self, crowd_url, app_name, app_pass, ssl_verify=True,
timeout=None, client_cert=None):
self.crowd_url = crowd_url
self.app_name = app_name
self.app_pass = app_pass
self.rest_url = crowd_url.rstrip("/") + "/rest/usermanagement/1"
self.ssl_verify = ssl_verify
self.client_cert = client_cert
self.timeout = timeout
self.session = self._build_session(content_type='json')
self.session_xml = self._build_session(content_type='xml')
def __str__(self):
return "Crowd Server at %s" % self.crowd_url
def __repr__(self):
return "<CrowdServer('%s', '%s', '%s')>" % \
(self.crowd_url, self.app_name, self.app_pass)
def _build_session(self, content_type='json'):
headers = {
'Content-Type': 'application/{}'.format(content_type),
'Accept': 'application/{}'.format(content_type),
}
session = requests.Session()
session.verify = self.ssl_verify
session.cert = self.client_cert
session.auth = requests.auth.HTTPBasicAuth(self.app_name, self.app_pass)
session.headers.update(headers)
return session
def _get(self, *args, **kwargs):
"""Wrapper around Requests for GET requests
Returns:
Response:
A Requests Response object
"""
if 'timeout' not in kwargs:
kwargs['timeout'] = self.timeout
req = self.session.get(*args, **kwargs)
return req
def _get_xml(self, *args, **kwargs):
"""Wrapper around Requests for GET XML requests
Returns:
Response:
A Requests Response object
"""
req = self.session_xml.get(*args, **kwargs)
return req
def _post(self, *args, **kwargs):
"""Wrapper around Requests for POST requests
Returns:
Response:
A Requests Response object
"""
if 'timeout' not in kwargs:
kwargs['timeout'] = self.timeout
req = self.session.post(*args, **kwargs)
return req
def _post_xml(self, *args, **kwargs):
"""Wrapper around Requests for POST requests
Returns:
Response:
A Requests Response object
"""
if 'timeout' not in kwargs:
kwargs['timeout'] = self.timeout
req = self.session_xml.post(*args, **kwargs)
return req
def _put(self, *args, **kwargs):
"""Wrapper around Requests for PUT requests
Returns:
Response:
A Requests Response object
"""
if 'timeout' not in kwargs:
kwargs['timeout'] = self.timeout
req = self.session.put(*args, **kwargs)
return req
def auth_ping(self):
"""Test that application can authenticate to Crowd.
Attempts to authenticate the application user against
the Crowd server. In order for user authentication to
work, an application must be able to authenticate.
Returns:
bool:
True if the application authentication succeeded.
"""
url = self.rest_url + "/non-existent/location"
response = self._get(url)
if response.status_code == 401:
return False
elif response.status_code == 404:
return True
else:
# An error encountered - problem with the Crowd server?
return False
def auth_user(self, username, password):
"""Authenticate a user account against the Crowd server.
Attempts to authenticate the user against the Crowd server.
Args:
username: The account username.
password: The account password.
Returns:
dict:
A dict mapping of user attributes if the application
authentication was successful. See the Crowd documentation
for the authoritative list of attributes.
None: If authentication failed.
"""
response = self._post(self.rest_url + "/authentication",
data=json.dumps({"value": password}),
params={"username": username})
# If authentication failed for any reason return None
if not response.ok:
return None
# ...otherwise return a dictionary of user attributes
return response.json()
def get_session(self, username, password, remote="127.0.0.1", proxy=None):
"""Create a session for a user.
Attempts to create a user session on the Crowd server.
Args:
username: The account username.
password: The account password.
remote:
The remote address of the user. This can be used
to create multiple concurrent sessions for a user.
The host you run this program on may need to be configured
in Crowd as a trusted proxy for this to work.
proxy: Value of X-Forwarded-For server header.
Returns:
dict:
A dict mapping of user attributes if the application
authentication was successful. See the Crowd
documentation for the authoritative list of attributes.
None: If authentication failed.
"""
params = {
"username": username,
"password": password,
"validation-factors": {
"validationFactors": [
{"name": "remote_address", "value": remote, },
]
}
}
if proxy:
params["validation-factors"]["validationFactors"].append({"name": "X-Forwarded-For", "value": proxy, })
response = self._post(self.rest_url + "/session",
data=json.dumps(params),
params={"expand": "user"})
# If authentication failed for any reason return None
if not response.ok:
return None
# Otherwise return the user object
return response.json()
def validate_session(self, token, remote="127.0.0.1", proxy=None):
"""Validate a session token.
Validate a previously acquired session token against the
Crowd server. This may be a token provided by a user from
a http cookie or by some other means.
Args:
token: The session token.
remote: The remote address of the user.
proxy: Value of X-Forwarded-For server header
Returns:
dict:
A dict mapping of user attributes if the application
authentication was successful. See the Crowd
documentation for the authoritative list of attributes.
None: If authentication failed.
"""
params = {
"validationFactors": [
{"name": "remote_address", "value": remote, },
]
}
if proxy:
params["validation-factors"]["validationFactors"].append({"name": "X-Forwarded-For", "value": proxy, })
url = self.rest_url + "/session/%s" % token
response = self._post(url, data=json.dumps(params), params={"expand": "user"})
# For consistency between methods use None rather than False
# If token validation failed for any reason return None
if not response.ok:
return None
# Otherwise return the user object
return response.json()
def terminate_session(self, token):
"""Terminates the session token, effectively logging out the user
from all crowd-enabled services.
Args:
token: The session token.
Returns:
True: If session terminated
None: If session termination failed
"""
url = self.rest_url + "/session/%s" % token
response = self._delete(url)
# For consistency between methods use None rather than False
# If token validation failed for any reason return None
if not response.ok:
return None
# Otherwise return True
return True
def add_user(self, username, raise_on_error=False, **kwargs):
"""Add a user to the directory
Args:
username: The account username
raise_on_error: optional (default: False)
**kwargs: key-value pairs:
password: mandatory
email: mandatory
first_name: optional
last_name: optional
display_name: optional
active: optional (default True)
Returns:
True: Succeeded
False: If unsuccessful
"""
# Check that mandatory elements have been provided
if 'password' not in kwargs:
raise ValueError("missing password")
if 'email' not in kwargs:
raise ValueError("missing email")
# Populate data with default and mandatory values.
# A KeyError means a mandatory value was not provided,
# so raise a ValueError indicating bad args.
try:
data = {
"name": username,
"first-name": username,
"last-name": username,
"display-name": username,
"email": kwargs["email"],
"password": {"value": kwargs["password"]},
"active": True
}
except KeyError:
return ValueError
# Remove special case 'password'
del(kwargs["password"])
# Put values from kwargs into data
for k, v in kwargs.items():
new_k = k.replace("_", "-")
if new_k not in data:
raise ValueError("invalid argument %s" % k)
data[new_k] = v
response = self._post(self.rest_url + "/user",
data=json.dumps(data))
if response.status_code == 201:
return True
if raise_on_error:
raise RuntimeError(response.json()['message'])
return False
def get_user(self, username):
"""Retrieve information about a user
Returns:
dict: User information
None: If no user or failure occurred
"""
response = self._get(self.rest_url + "/user",
params={"username": username,
"expand": "attributes"})
if not response.ok:
return None
return response.json()
def set_active(self, username, active_state):
"""Set the active state of a user
Args:
username: The account username
active_state: True or False
Returns:
True: If successful
None: If no user or failure occurred
"""
if active_state not in (True, False):
raise ValueError("active_state must be True or False")
user = self.get_user(username)
if user is None:
return None
if user['active'] is active_state:
# Already in desired state
return True
user['active'] = active_state
response = self._put(self.rest_url + "/user",
params={"username": username},
data=json.dumps(user))
if response.status_code == 204:
return True
return None
def set_user_attribute(self, username, attribute, value, raise_on_error=False):
"""Set an attribute on a user
:param username: The username on which to set the attribute
:param attribute: The name of the attribute to set
:param value: The value of the attribute to set
:return: True on success, False on failure.
"""
data = {
'attributes': [
{
'name': attribute,
'values': [
value
]
},
]
}
response = self._post(self.rest_url + "/user/attribute",
params={"username": username,},
data=json.dumps(data))
if response.status_code == 204:
return True
if raise_on_error:
raise RuntimeError(response.json()['message'])
return False
def add_user_to_group(self, username, groupname, raise_on_error=False):
"""Add a user to a group
:param username: The username to assign to the group
:param groupname: The group name into which to assign the user
:return: True on success, False on failure.
"""
data = {
'name': groupname,
}
response = self._post(self.rest_url + "/user/group/direct",
params={"username": username,},
data=json.dumps(data))
if response.status_code == 201:
return True
if raise_on_error:
raise RuntimeError(response.json()['message'])
return False
def remove_user_from_group(self, username, groupname, raise_on_error=False):
"""Remove a user from a group
Attempts to remove a user from a group
Args
username: The username to remove from the group.
groupname: The group name to be removed from the user.
Returns:
True: Succeeded
False: If unsuccessful
"""
response = self._delete(self.rest_url + "/group/user/direct",params={"username": username, "groupname": groupname})
if response.status_code == 204:
return True
if raise_on_error:
raise RuntimeError(response.json()['message'])
return False
def change_password(self, username, newpassword, raise_on_error=False):
"""Change new password for a user
Args:
username: The account username.
newpassword: The account new password.
raise_on_error: optional (default: False)
Returns:
True: Succeeded
False: If unsuccessful
"""
response = self._put(self.rest_url + "/user/password",
data=json.dumps({"value": newpassword}),
params={"username": username})
if response.ok:
return True
if raise_on_error:
raise RuntimeError(response.json()['message'])
return False
def send_password_reset_link(self, username):
"""Sends the user a password reset link (by email)
Args:
username: The account username.
Returns:
True: Succeeded
False: If unsuccessful
"""
response = self._post(self.rest_url + "/user/mail/password",
params={"username": username})
if response.ok:
return True
return False
def get_groups(self, username):
"""Retrieves a list of group names that have <username> as a direct member.
Returns:
list:
A list of strings of group names.
"""
response = self._get(self.rest_url + "/user/group/direct",
params={"username": username})
if not response.ok:
return None
return [g['name'] for g in response.json()['groups']]
def get_nested_groups(self, username):
"""Retrieve a list of all group names that have <username> as a direct or indirect member.
Args:
username: The account username.
Returns:
list:
A list of strings of group names.
"""
response = self._get(self.rest_url + "/user/group/nested",
params={"username": username})
if not response.ok:
return None
return [g['name'] for g in response.json()['groups']]
def get_nested_group_users(self, groupname):
"""Retrieves a list of all users that directly or indirectly belong to the given groupname.
Args:
groupname: The group name.
Returns:
list:
A list of strings of user names.
"""
response = self._get(self.rest_url + "/group/user/nested",
params={"groupname": groupname,
"start-index": 0,
"max-results": 99999})
if not response.ok:
return None
return [u['name'] for u in response.json()['users']]
def user_exists(self, username):
"""Determines if the user exists.
Args:
username: The user name.
Returns:
bool:
True if the user exists in the Crowd application.
"""
response = self._get(self.rest_url + "/user",
params={"username": username})
if not response.ok:
return None
return True
def get_memberships(self):
"""Fetches all group memberships.
Returns:
dict:
key: group name
value: (array of users, array of groups)
"""
response = self._get_xml(self.rest_url + "/group/membership")
if not response.ok:
return None
xmltree = etree.fromstring(response.content)
memberships = {}
for mg in xmltree.findall('membership'):
# coerce values to unicode in a python 2 and 3 compatible way
group = u'{}'.format(mg.get('group'))
users = [u'{}'.format(u.get('name')) for u in mg.find('users').findall('user')]
groups = [u'{}'.format(g.get('name')) for g in mg.find('groups').findall('group')]
memberships[group] = {u'users': users, u'groups': groups}
return memberships
def search(self, entity_type, property_name, search_string, start_index=0, max_results=99999):
"""Performs a user search using the Crowd search API.
https://developer.atlassian.com/display/CROWDDEV/Crowd+REST+Resources#CrowdRESTResources-SearchResource
Args:
entity_type: 'user' or 'group'
property_name: eg. 'email', 'name'
search_string: the string to search for.
start_index: starting index of the results (default: 0)
max_results: maximum number of results returned (default: 99999)
Returns:
json results:
Returns search results.
"""
params = {
"entity-type": entity_type,
"expand": entity_type,
"property-search-restriction": {
"property": {"name": property_name, "type": "STRING"},
"match-mode": "CONTAINS",
"value": search_string,
}
}
params = {
'entity-type': entity_type,
'expand': entity_type,
'start-index': start_index,
'max-results': max_results
}
# Construct XML payload of the form:
# <property-search-restriction>
# <property>
# <name>email</name>
# <type>STRING</type>
# </property>
# <match-mode>EXACTLY_MATCHES</match-mode>
# <value>bob@example.net</value>
# </property-search-restriction>
root = etree.Element('property-search-restriction')
property_ = etree.Element('property')
prop_name = etree.Element('name')
prop_name.text = property_name
property_.append(prop_name)
prop_type = etree.Element('type')
prop_type.text = 'STRING'
property_.append(prop_type)
root.append(property_)
match_mode = etree.Element('match-mode')
match_mode.text = 'CONTAINS'
root.append(match_mode)
value = etree.Element('value')
value.text = search_string
root.append(value)
# Construct the XML payload expected by search API
payload = '<?xml version="1.0" encoding="UTF-8"?>\n' + etree.tostring(root).decode('utf-8')
# We're sending XML but would like a JSON response
session = self._build_session(content_type='xml')
session.headers.update({'Accept': 'application/json'})
response = session.post(self.rest_url + "/search", params=params, data=payload, timeout=self.timeout)
if not response.ok:
return None
return response.json()
|
pycontribs/python-crowd | crowd.py | CrowdServer.auth_ping | python | def auth_ping(self):
url = self.rest_url + "/non-existent/location"
response = self._get(url)
if response.status_code == 401:
return False
elif response.status_code == 404:
return True
else:
# An error encountered - problem with the Crowd server?
return False | Test that application can authenticate to Crowd.
Attempts to authenticate the application user against
the Crowd server. In order for user authentication to
work, an application must be able to authenticate.
Returns:
bool:
True if the application authentication succeeded. | train | https://github.com/pycontribs/python-crowd/blob/a075e45774dd5baecf0217843cda747084268e32/crowd.py#L150-L171 | [
"def _get(self, *args, **kwargs):\n \"\"\"Wrapper around Requests for GET requests\n\n Returns:\n Response:\n A Requests Response object\n \"\"\"\n\n if 'timeout' not in kwargs:\n kwargs['timeout'] = self.timeout\n\n req = self.session.get(*args, **kwargs)\n return req\n"
... | class CrowdServer(object):
"""Crowd server authentication object.
This is a Crowd authentication class to be configured for a
particular application (app_name) to authenticate users
against a Crowd server (crowd_url).
This module uses the Crowd JSON API for talking to Crowd.
An application account must be configured in the Crowd server
and permitted to authenticate users against one or more user
directories prior to using this module.
Please see the Crowd documentation for information about
configuring additional applications to talk to Crowd.
The ``ssl_verify`` parameter controls how and if certificates are verified.
If ``True``, the SSL certificate will be verified.
A CA_BUNDLE path can also be provided.
The ``client_cert`` tuple (cert,key) specifies a SSL client certificate and key files.
"""
def __init__(self, crowd_url, app_name, app_pass, ssl_verify=True,
timeout=None, client_cert=None):
self.crowd_url = crowd_url
self.app_name = app_name
self.app_pass = app_pass
self.rest_url = crowd_url.rstrip("/") + "/rest/usermanagement/1"
self.ssl_verify = ssl_verify
self.client_cert = client_cert
self.timeout = timeout
self.session = self._build_session(content_type='json')
self.session_xml = self._build_session(content_type='xml')
def __str__(self):
return "Crowd Server at %s" % self.crowd_url
def __repr__(self):
return "<CrowdServer('%s', '%s', '%s')>" % \
(self.crowd_url, self.app_name, self.app_pass)
def _build_session(self, content_type='json'):
headers = {
'Content-Type': 'application/{}'.format(content_type),
'Accept': 'application/{}'.format(content_type),
}
session = requests.Session()
session.verify = self.ssl_verify
session.cert = self.client_cert
session.auth = requests.auth.HTTPBasicAuth(self.app_name, self.app_pass)
session.headers.update(headers)
return session
def _get(self, *args, **kwargs):
"""Wrapper around Requests for GET requests
Returns:
Response:
A Requests Response object
"""
if 'timeout' not in kwargs:
kwargs['timeout'] = self.timeout
req = self.session.get(*args, **kwargs)
return req
def _get_xml(self, *args, **kwargs):
"""Wrapper around Requests for GET XML requests
Returns:
Response:
A Requests Response object
"""
req = self.session_xml.get(*args, **kwargs)
return req
def _post(self, *args, **kwargs):
"""Wrapper around Requests for POST requests
Returns:
Response:
A Requests Response object
"""
if 'timeout' not in kwargs:
kwargs['timeout'] = self.timeout
req = self.session.post(*args, **kwargs)
return req
def _post_xml(self, *args, **kwargs):
"""Wrapper around Requests for POST requests
Returns:
Response:
A Requests Response object
"""
if 'timeout' not in kwargs:
kwargs['timeout'] = self.timeout
req = self.session_xml.post(*args, **kwargs)
return req
def _put(self, *args, **kwargs):
"""Wrapper around Requests for PUT requests
Returns:
Response:
A Requests Response object
"""
if 'timeout' not in kwargs:
kwargs['timeout'] = self.timeout
req = self.session.put(*args, **kwargs)
return req
def _delete(self, *args, **kwargs):
"""Wrapper around Requests for DELETE requests
Returns:
Response:
A Requests Response object
"""
if 'timeout' not in kwargs:
kwargs['timeout'] = self.timeout
req = self.session.delete(*args, **kwargs)
return req
def auth_user(self, username, password):
"""Authenticate a user account against the Crowd server.
Attempts to authenticate the user against the Crowd server.
Args:
username: The account username.
password: The account password.
Returns:
dict:
A dict mapping of user attributes if the application
authentication was successful. See the Crowd documentation
for the authoritative list of attributes.
None: If authentication failed.
"""
response = self._post(self.rest_url + "/authentication",
data=json.dumps({"value": password}),
params={"username": username})
# If authentication failed for any reason return None
if not response.ok:
return None
# ...otherwise return a dictionary of user attributes
return response.json()
def get_session(self, username, password, remote="127.0.0.1", proxy=None):
"""Create a session for a user.
Attempts to create a user session on the Crowd server.
Args:
username: The account username.
password: The account password.
remote:
The remote address of the user. This can be used
to create multiple concurrent sessions for a user.
The host you run this program on may need to be configured
in Crowd as a trusted proxy for this to work.
proxy: Value of X-Forwarded-For server header.
Returns:
dict:
A dict mapping of user attributes if the application
authentication was successful. See the Crowd
documentation for the authoritative list of attributes.
None: If authentication failed.
"""
params = {
"username": username,
"password": password,
"validation-factors": {
"validationFactors": [
{"name": "remote_address", "value": remote, },
]
}
}
if proxy:
params["validation-factors"]["validationFactors"].append({"name": "X-Forwarded-For", "value": proxy, })
response = self._post(self.rest_url + "/session",
data=json.dumps(params),
params={"expand": "user"})
# If authentication failed for any reason return None
if not response.ok:
return None
# Otherwise return the user object
return response.json()
def validate_session(self, token, remote="127.0.0.1", proxy=None):
"""Validate a session token.
Validate a previously acquired session token against the
Crowd server. This may be a token provided by a user from
a http cookie or by some other means.
Args:
token: The session token.
remote: The remote address of the user.
proxy: Value of X-Forwarded-For server header
Returns:
dict:
A dict mapping of user attributes if the application
authentication was successful. See the Crowd
documentation for the authoritative list of attributes.
None: If authentication failed.
"""
params = {
"validationFactors": [
{"name": "remote_address", "value": remote, },
]
}
if proxy:
params["validation-factors"]["validationFactors"].append({"name": "X-Forwarded-For", "value": proxy, })
url = self.rest_url + "/session/%s" % token
response = self._post(url, data=json.dumps(params), params={"expand": "user"})
# For consistency between methods use None rather than False
# If token validation failed for any reason return None
if not response.ok:
return None
# Otherwise return the user object
return response.json()
def terminate_session(self, token):
"""Terminates the session token, effectively logging out the user
from all crowd-enabled services.
Args:
token: The session token.
Returns:
True: If session terminated
None: If session termination failed
"""
url = self.rest_url + "/session/%s" % token
response = self._delete(url)
# For consistency between methods use None rather than False
# If token validation failed for any reason return None
if not response.ok:
return None
# Otherwise return True
return True
def add_user(self, username, raise_on_error=False, **kwargs):
"""Add a user to the directory
Args:
username: The account username
raise_on_error: optional (default: False)
**kwargs: key-value pairs:
password: mandatory
email: mandatory
first_name: optional
last_name: optional
display_name: optional
active: optional (default True)
Returns:
True: Succeeded
False: If unsuccessful
"""
# Check that mandatory elements have been provided
if 'password' not in kwargs:
raise ValueError("missing password")
if 'email' not in kwargs:
raise ValueError("missing email")
# Populate data with default and mandatory values.
# A KeyError means a mandatory value was not provided,
# so raise a ValueError indicating bad args.
try:
data = {
"name": username,
"first-name": username,
"last-name": username,
"display-name": username,
"email": kwargs["email"],
"password": {"value": kwargs["password"]},
"active": True
}
except KeyError:
return ValueError
# Remove special case 'password'
del(kwargs["password"])
# Put values from kwargs into data
for k, v in kwargs.items():
new_k = k.replace("_", "-")
if new_k not in data:
raise ValueError("invalid argument %s" % k)
data[new_k] = v
response = self._post(self.rest_url + "/user",
data=json.dumps(data))
if response.status_code == 201:
return True
if raise_on_error:
raise RuntimeError(response.json()['message'])
return False
def get_user(self, username):
"""Retrieve information about a user
Returns:
dict: User information
None: If no user or failure occurred
"""
response = self._get(self.rest_url + "/user",
params={"username": username,
"expand": "attributes"})
if not response.ok:
return None
return response.json()
def set_active(self, username, active_state):
"""Set the active state of a user
Args:
username: The account username
active_state: True or False
Returns:
True: If successful
None: If no user or failure occurred
"""
if active_state not in (True, False):
raise ValueError("active_state must be True or False")
user = self.get_user(username)
if user is None:
return None
if user['active'] is active_state:
# Already in desired state
return True
user['active'] = active_state
response = self._put(self.rest_url + "/user",
params={"username": username},
data=json.dumps(user))
if response.status_code == 204:
return True
return None
def set_user_attribute(self, username, attribute, value, raise_on_error=False):
"""Set an attribute on a user
:param username: The username on which to set the attribute
:param attribute: The name of the attribute to set
:param value: The value of the attribute to set
:return: True on success, False on failure.
"""
data = {
'attributes': [
{
'name': attribute,
'values': [
value
]
},
]
}
response = self._post(self.rest_url + "/user/attribute",
params={"username": username,},
data=json.dumps(data))
if response.status_code == 204:
return True
if raise_on_error:
raise RuntimeError(response.json()['message'])
return False
def add_user_to_group(self, username, groupname, raise_on_error=False):
"""Add a user to a group
:param username: The username to assign to the group
:param groupname: The group name into which to assign the user
:return: True on success, False on failure.
"""
data = {
'name': groupname,
}
response = self._post(self.rest_url + "/user/group/direct",
params={"username": username,},
data=json.dumps(data))
if response.status_code == 201:
return True
if raise_on_error:
raise RuntimeError(response.json()['message'])
return False
def remove_user_from_group(self, username, groupname, raise_on_error=False):
"""Remove a user from a group
Attempts to remove a user from a group
Args
username: The username to remove from the group.
groupname: The group name to be removed from the user.
Returns:
True: Succeeded
False: If unsuccessful
"""
response = self._delete(self.rest_url + "/group/user/direct",params={"username": username, "groupname": groupname})
if response.status_code == 204:
return True
if raise_on_error:
raise RuntimeError(response.json()['message'])
return False
def change_password(self, username, newpassword, raise_on_error=False):
"""Change new password for a user
Args:
username: The account username.
newpassword: The account new password.
raise_on_error: optional (default: False)
Returns:
True: Succeeded
False: If unsuccessful
"""
response = self._put(self.rest_url + "/user/password",
data=json.dumps({"value": newpassword}),
params={"username": username})
if response.ok:
return True
if raise_on_error:
raise RuntimeError(response.json()['message'])
return False
def send_password_reset_link(self, username):
"""Sends the user a password reset link (by email)
Args:
username: The account username.
Returns:
True: Succeeded
False: If unsuccessful
"""
response = self._post(self.rest_url + "/user/mail/password",
params={"username": username})
if response.ok:
return True
return False
def get_groups(self, username):
"""Retrieves a list of group names that have <username> as a direct member.
Returns:
list:
A list of strings of group names.
"""
response = self._get(self.rest_url + "/user/group/direct",
params={"username": username})
if not response.ok:
return None
return [g['name'] for g in response.json()['groups']]
def get_nested_groups(self, username):
"""Retrieve a list of all group names that have <username> as a direct or indirect member.
Args:
username: The account username.
Returns:
list:
A list of strings of group names.
"""
response = self._get(self.rest_url + "/user/group/nested",
params={"username": username})
if not response.ok:
return None
return [g['name'] for g in response.json()['groups']]
def get_nested_group_users(self, groupname):
"""Retrieves a list of all users that directly or indirectly belong to the given groupname.
Args:
groupname: The group name.
Returns:
list:
A list of strings of user names.
"""
response = self._get(self.rest_url + "/group/user/nested",
params={"groupname": groupname,
"start-index": 0,
"max-results": 99999})
if not response.ok:
return None
return [u['name'] for u in response.json()['users']]
def user_exists(self, username):
"""Determines if the user exists.
Args:
username: The user name.
Returns:
bool:
True if the user exists in the Crowd application.
"""
response = self._get(self.rest_url + "/user",
params={"username": username})
if not response.ok:
return None
return True
def get_memberships(self):
"""Fetches all group memberships.
Returns:
dict:
key: group name
value: (array of users, array of groups)
"""
response = self._get_xml(self.rest_url + "/group/membership")
if not response.ok:
return None
xmltree = etree.fromstring(response.content)
memberships = {}
for mg in xmltree.findall('membership'):
# coerce values to unicode in a python 2 and 3 compatible way
group = u'{}'.format(mg.get('group'))
users = [u'{}'.format(u.get('name')) for u in mg.find('users').findall('user')]
groups = [u'{}'.format(g.get('name')) for g in mg.find('groups').findall('group')]
memberships[group] = {u'users': users, u'groups': groups}
return memberships
def search(self, entity_type, property_name, search_string, start_index=0, max_results=99999):
"""Performs a user search using the Crowd search API.
https://developer.atlassian.com/display/CROWDDEV/Crowd+REST+Resources#CrowdRESTResources-SearchResource
Args:
entity_type: 'user' or 'group'
property_name: eg. 'email', 'name'
search_string: the string to search for.
start_index: starting index of the results (default: 0)
max_results: maximum number of results returned (default: 99999)
Returns:
json results:
Returns search results.
"""
params = {
"entity-type": entity_type,
"expand": entity_type,
"property-search-restriction": {
"property": {"name": property_name, "type": "STRING"},
"match-mode": "CONTAINS",
"value": search_string,
}
}
params = {
'entity-type': entity_type,
'expand': entity_type,
'start-index': start_index,
'max-results': max_results
}
# Construct XML payload of the form:
# <property-search-restriction>
# <property>
# <name>email</name>
# <type>STRING</type>
# </property>
# <match-mode>EXACTLY_MATCHES</match-mode>
# <value>bob@example.net</value>
# </property-search-restriction>
root = etree.Element('property-search-restriction')
property_ = etree.Element('property')
prop_name = etree.Element('name')
prop_name.text = property_name
property_.append(prop_name)
prop_type = etree.Element('type')
prop_type.text = 'STRING'
property_.append(prop_type)
root.append(property_)
match_mode = etree.Element('match-mode')
match_mode.text = 'CONTAINS'
root.append(match_mode)
value = etree.Element('value')
value.text = search_string
root.append(value)
# Construct the XML payload expected by search API
payload = '<?xml version="1.0" encoding="UTF-8"?>\n' + etree.tostring(root).decode('utf-8')
# We're sending XML but would like a JSON response
session = self._build_session(content_type='xml')
session.headers.update({'Accept': 'application/json'})
response = session.post(self.rest_url + "/search", params=params, data=payload, timeout=self.timeout)
if not response.ok:
return None
return response.json()
|
pycontribs/python-crowd | crowd.py | CrowdServer.auth_user | python | def auth_user(self, username, password):
response = self._post(self.rest_url + "/authentication",
data=json.dumps({"value": password}),
params={"username": username})
# If authentication failed for any reason return None
if not response.ok:
return None
# ...otherwise return a dictionary of user attributes
return response.json() | Authenticate a user account against the Crowd server.
Attempts to authenticate the user against the Crowd server.
Args:
username: The account username.
password: The account password.
Returns:
dict:
A dict mapping of user attributes if the application
authentication was successful. See the Crowd documentation
for the authoritative list of attributes.
None: If authentication failed. | train | https://github.com/pycontribs/python-crowd/blob/a075e45774dd5baecf0217843cda747084268e32/crowd.py#L173-L201 | [
"def _post(self, *args, **kwargs):\n \"\"\"Wrapper around Requests for POST requests\n\n Returns:\n Response:\n A Requests Response object\n \"\"\"\n\n if 'timeout' not in kwargs:\n kwargs['timeout'] = self.timeout\n\n req = self.session.post(*args, **kwargs)\n return req\... | class CrowdServer(object):
"""Crowd server authentication object.
This is a Crowd authentication class to be configured for a
particular application (app_name) to authenticate users
against a Crowd server (crowd_url).
This module uses the Crowd JSON API for talking to Crowd.
An application account must be configured in the Crowd server
and permitted to authenticate users against one or more user
directories prior to using this module.
Please see the Crowd documentation for information about
configuring additional applications to talk to Crowd.
The ``ssl_verify`` parameter controls how and if certificates are verified.
If ``True``, the SSL certificate will be verified.
A CA_BUNDLE path can also be provided.
The ``client_cert`` tuple (cert,key) specifies a SSL client certificate and key files.
"""
def __init__(self, crowd_url, app_name, app_pass, ssl_verify=True,
timeout=None, client_cert=None):
self.crowd_url = crowd_url
self.app_name = app_name
self.app_pass = app_pass
self.rest_url = crowd_url.rstrip("/") + "/rest/usermanagement/1"
self.ssl_verify = ssl_verify
self.client_cert = client_cert
self.timeout = timeout
self.session = self._build_session(content_type='json')
self.session_xml = self._build_session(content_type='xml')
def __str__(self):
return "Crowd Server at %s" % self.crowd_url
def __repr__(self):
return "<CrowdServer('%s', '%s', '%s')>" % \
(self.crowd_url, self.app_name, self.app_pass)
def _build_session(self, content_type='json'):
headers = {
'Content-Type': 'application/{}'.format(content_type),
'Accept': 'application/{}'.format(content_type),
}
session = requests.Session()
session.verify = self.ssl_verify
session.cert = self.client_cert
session.auth = requests.auth.HTTPBasicAuth(self.app_name, self.app_pass)
session.headers.update(headers)
return session
def _get(self, *args, **kwargs):
"""Wrapper around Requests for GET requests
Returns:
Response:
A Requests Response object
"""
if 'timeout' not in kwargs:
kwargs['timeout'] = self.timeout
req = self.session.get(*args, **kwargs)
return req
def _get_xml(self, *args, **kwargs):
"""Wrapper around Requests for GET XML requests
Returns:
Response:
A Requests Response object
"""
req = self.session_xml.get(*args, **kwargs)
return req
def _post(self, *args, **kwargs):
"""Wrapper around Requests for POST requests
Returns:
Response:
A Requests Response object
"""
if 'timeout' not in kwargs:
kwargs['timeout'] = self.timeout
req = self.session.post(*args, **kwargs)
return req
def _post_xml(self, *args, **kwargs):
"""Wrapper around Requests for POST requests
Returns:
Response:
A Requests Response object
"""
if 'timeout' not in kwargs:
kwargs['timeout'] = self.timeout
req = self.session_xml.post(*args, **kwargs)
return req
def _put(self, *args, **kwargs):
"""Wrapper around Requests for PUT requests
Returns:
Response:
A Requests Response object
"""
if 'timeout' not in kwargs:
kwargs['timeout'] = self.timeout
req = self.session.put(*args, **kwargs)
return req
def _delete(self, *args, **kwargs):
"""Wrapper around Requests for DELETE requests
Returns:
Response:
A Requests Response object
"""
if 'timeout' not in kwargs:
kwargs['timeout'] = self.timeout
req = self.session.delete(*args, **kwargs)
return req
def auth_ping(self):
"""Test that application can authenticate to Crowd.
Attempts to authenticate the application user against
the Crowd server. In order for user authentication to
work, an application must be able to authenticate.
Returns:
bool:
True if the application authentication succeeded.
"""
url = self.rest_url + "/non-existent/location"
response = self._get(url)
if response.status_code == 401:
return False
elif response.status_code == 404:
return True
else:
# An error encountered - problem with the Crowd server?
return False
def get_session(self, username, password, remote="127.0.0.1", proxy=None):
"""Create a session for a user.
Attempts to create a user session on the Crowd server.
Args:
username: The account username.
password: The account password.
remote:
The remote address of the user. This can be used
to create multiple concurrent sessions for a user.
The host you run this program on may need to be configured
in Crowd as a trusted proxy for this to work.
proxy: Value of X-Forwarded-For server header.
Returns:
dict:
A dict mapping of user attributes if the application
authentication was successful. See the Crowd
documentation for the authoritative list of attributes.
None: If authentication failed.
"""
params = {
"username": username,
"password": password,
"validation-factors": {
"validationFactors": [
{"name": "remote_address", "value": remote, },
]
}
}
if proxy:
params["validation-factors"]["validationFactors"].append({"name": "X-Forwarded-For", "value": proxy, })
response = self._post(self.rest_url + "/session",
data=json.dumps(params),
params={"expand": "user"})
# If authentication failed for any reason return None
if not response.ok:
return None
# Otherwise return the user object
return response.json()
def validate_session(self, token, remote="127.0.0.1", proxy=None):
"""Validate a session token.
Validate a previously acquired session token against the
Crowd server. This may be a token provided by a user from
a http cookie or by some other means.
Args:
token: The session token.
remote: The remote address of the user.
proxy: Value of X-Forwarded-For server header
Returns:
dict:
A dict mapping of user attributes if the application
authentication was successful. See the Crowd
documentation for the authoritative list of attributes.
None: If authentication failed.
"""
params = {
"validationFactors": [
{"name": "remote_address", "value": remote, },
]
}
if proxy:
params["validation-factors"]["validationFactors"].append({"name": "X-Forwarded-For", "value": proxy, })
url = self.rest_url + "/session/%s" % token
response = self._post(url, data=json.dumps(params), params={"expand": "user"})
# For consistency between methods use None rather than False
# If token validation failed for any reason return None
if not response.ok:
return None
# Otherwise return the user object
return response.json()
def terminate_session(self, token):
"""Terminates the session token, effectively logging out the user
from all crowd-enabled services.
Args:
token: The session token.
Returns:
True: If session terminated
None: If session termination failed
"""
url = self.rest_url + "/session/%s" % token
response = self._delete(url)
# For consistency between methods use None rather than False
# If token validation failed for any reason return None
if not response.ok:
return None
# Otherwise return True
return True
def add_user(self, username, raise_on_error=False, **kwargs):
"""Add a user to the directory
Args:
username: The account username
raise_on_error: optional (default: False)
**kwargs: key-value pairs:
password: mandatory
email: mandatory
first_name: optional
last_name: optional
display_name: optional
active: optional (default True)
Returns:
True: Succeeded
False: If unsuccessful
"""
# Check that mandatory elements have been provided
if 'password' not in kwargs:
raise ValueError("missing password")
if 'email' not in kwargs:
raise ValueError("missing email")
# Populate data with default and mandatory values.
# A KeyError means a mandatory value was not provided,
# so raise a ValueError indicating bad args.
try:
data = {
"name": username,
"first-name": username,
"last-name": username,
"display-name": username,
"email": kwargs["email"],
"password": {"value": kwargs["password"]},
"active": True
}
except KeyError:
return ValueError
# Remove special case 'password'
del(kwargs["password"])
# Put values from kwargs into data
for k, v in kwargs.items():
new_k = k.replace("_", "-")
if new_k not in data:
raise ValueError("invalid argument %s" % k)
data[new_k] = v
response = self._post(self.rest_url + "/user",
data=json.dumps(data))
if response.status_code == 201:
return True
if raise_on_error:
raise RuntimeError(response.json()['message'])
return False
def get_user(self, username):
"""Retrieve information about a user
Returns:
dict: User information
None: If no user or failure occurred
"""
response = self._get(self.rest_url + "/user",
params={"username": username,
"expand": "attributes"})
if not response.ok:
return None
return response.json()
def set_active(self, username, active_state):
"""Set the active state of a user
Args:
username: The account username
active_state: True or False
Returns:
True: If successful
None: If no user or failure occurred
"""
if active_state not in (True, False):
raise ValueError("active_state must be True or False")
user = self.get_user(username)
if user is None:
return None
if user['active'] is active_state:
# Already in desired state
return True
user['active'] = active_state
response = self._put(self.rest_url + "/user",
params={"username": username},
data=json.dumps(user))
if response.status_code == 204:
return True
return None
def set_user_attribute(self, username, attribute, value, raise_on_error=False):
"""Set an attribute on a user
:param username: The username on which to set the attribute
:param attribute: The name of the attribute to set
:param value: The value of the attribute to set
:return: True on success, False on failure.
"""
data = {
'attributes': [
{
'name': attribute,
'values': [
value
]
},
]
}
response = self._post(self.rest_url + "/user/attribute",
params={"username": username,},
data=json.dumps(data))
if response.status_code == 204:
return True
if raise_on_error:
raise RuntimeError(response.json()['message'])
return False
def add_user_to_group(self, username, groupname, raise_on_error=False):
"""Add a user to a group
:param username: The username to assign to the group
:param groupname: The group name into which to assign the user
:return: True on success, False on failure.
"""
data = {
'name': groupname,
}
response = self._post(self.rest_url + "/user/group/direct",
params={"username": username,},
data=json.dumps(data))
if response.status_code == 201:
return True
if raise_on_error:
raise RuntimeError(response.json()['message'])
return False
def remove_user_from_group(self, username, groupname, raise_on_error=False):
"""Remove a user from a group
Attempts to remove a user from a group
Args
username: The username to remove from the group.
groupname: The group name to be removed from the user.
Returns:
True: Succeeded
False: If unsuccessful
"""
response = self._delete(self.rest_url + "/group/user/direct",params={"username": username, "groupname": groupname})
if response.status_code == 204:
return True
if raise_on_error:
raise RuntimeError(response.json()['message'])
return False
def change_password(self, username, newpassword, raise_on_error=False):
"""Change new password for a user
Args:
username: The account username.
newpassword: The account new password.
raise_on_error: optional (default: False)
Returns:
True: Succeeded
False: If unsuccessful
"""
response = self._put(self.rest_url + "/user/password",
data=json.dumps({"value": newpassword}),
params={"username": username})
if response.ok:
return True
if raise_on_error:
raise RuntimeError(response.json()['message'])
return False
def send_password_reset_link(self, username):
"""Sends the user a password reset link (by email)
Args:
username: The account username.
Returns:
True: Succeeded
False: If unsuccessful
"""
response = self._post(self.rest_url + "/user/mail/password",
params={"username": username})
if response.ok:
return True
return False
def get_groups(self, username):
"""Retrieves a list of group names that have <username> as a direct member.
Returns:
list:
A list of strings of group names.
"""
response = self._get(self.rest_url + "/user/group/direct",
params={"username": username})
if not response.ok:
return None
return [g['name'] for g in response.json()['groups']]
def get_nested_groups(self, username):
"""Retrieve a list of all group names that have <username> as a direct or indirect member.
Args:
username: The account username.
Returns:
list:
A list of strings of group names.
"""
response = self._get(self.rest_url + "/user/group/nested",
params={"username": username})
if not response.ok:
return None
return [g['name'] for g in response.json()['groups']]
def get_nested_group_users(self, groupname):
"""Retrieves a list of all users that directly or indirectly belong to the given groupname.
Args:
groupname: The group name.
Returns:
list:
A list of strings of user names.
"""
response = self._get(self.rest_url + "/group/user/nested",
params={"groupname": groupname,
"start-index": 0,
"max-results": 99999})
if not response.ok:
return None
return [u['name'] for u in response.json()['users']]
def user_exists(self, username):
"""Determines if the user exists.
Args:
username: The user name.
Returns:
bool:
True if the user exists in the Crowd application.
"""
response = self._get(self.rest_url + "/user",
params={"username": username})
if not response.ok:
return None
return True
def get_memberships(self):
"""Fetches all group memberships.
Returns:
dict:
key: group name
value: (array of users, array of groups)
"""
response = self._get_xml(self.rest_url + "/group/membership")
if not response.ok:
return None
xmltree = etree.fromstring(response.content)
memberships = {}
for mg in xmltree.findall('membership'):
# coerce values to unicode in a python 2 and 3 compatible way
group = u'{}'.format(mg.get('group'))
users = [u'{}'.format(u.get('name')) for u in mg.find('users').findall('user')]
groups = [u'{}'.format(g.get('name')) for g in mg.find('groups').findall('group')]
memberships[group] = {u'users': users, u'groups': groups}
return memberships
def search(self, entity_type, property_name, search_string, start_index=0, max_results=99999):
"""Performs a user search using the Crowd search API.
https://developer.atlassian.com/display/CROWDDEV/Crowd+REST+Resources#CrowdRESTResources-SearchResource
Args:
entity_type: 'user' or 'group'
property_name: eg. 'email', 'name'
search_string: the string to search for.
start_index: starting index of the results (default: 0)
max_results: maximum number of results returned (default: 99999)
Returns:
json results:
Returns search results.
"""
params = {
"entity-type": entity_type,
"expand": entity_type,
"property-search-restriction": {
"property": {"name": property_name, "type": "STRING"},
"match-mode": "CONTAINS",
"value": search_string,
}
}
params = {
'entity-type': entity_type,
'expand': entity_type,
'start-index': start_index,
'max-results': max_results
}
# Construct XML payload of the form:
# <property-search-restriction>
# <property>
# <name>email</name>
# <type>STRING</type>
# </property>
# <match-mode>EXACTLY_MATCHES</match-mode>
# <value>bob@example.net</value>
# </property-search-restriction>
root = etree.Element('property-search-restriction')
property_ = etree.Element('property')
prop_name = etree.Element('name')
prop_name.text = property_name
property_.append(prop_name)
prop_type = etree.Element('type')
prop_type.text = 'STRING'
property_.append(prop_type)
root.append(property_)
match_mode = etree.Element('match-mode')
match_mode.text = 'CONTAINS'
root.append(match_mode)
value = etree.Element('value')
value.text = search_string
root.append(value)
# Construct the XML payload expected by search API
payload = '<?xml version="1.0" encoding="UTF-8"?>\n' + etree.tostring(root).decode('utf-8')
# We're sending XML but would like a JSON response
session = self._build_session(content_type='xml')
session.headers.update({'Accept': 'application/json'})
response = session.post(self.rest_url + "/search", params=params, data=payload, timeout=self.timeout)
if not response.ok:
return None
return response.json()
|
pycontribs/python-crowd | crowd.py | CrowdServer.get_session | python | def get_session(self, username, password, remote="127.0.0.1", proxy=None):
params = {
"username": username,
"password": password,
"validation-factors": {
"validationFactors": [
{"name": "remote_address", "value": remote, },
]
}
}
if proxy:
params["validation-factors"]["validationFactors"].append({"name": "X-Forwarded-For", "value": proxy, })
response = self._post(self.rest_url + "/session",
data=json.dumps(params),
params={"expand": "user"})
# If authentication failed for any reason return None
if not response.ok:
return None
# Otherwise return the user object
return response.json() | Create a session for a user.
Attempts to create a user session on the Crowd server.
Args:
username: The account username.
password: The account password.
remote:
The remote address of the user. This can be used
to create multiple concurrent sessions for a user.
The host you run this program on may need to be configured
in Crowd as a trusted proxy for this to work.
proxy: Value of X-Forwarded-For server header.
Returns:
dict:
A dict mapping of user attributes if the application
authentication was successful. See the Crowd
documentation for the authoritative list of attributes.
None: If authentication failed. | train | https://github.com/pycontribs/python-crowd/blob/a075e45774dd5baecf0217843cda747084268e32/crowd.py#L203-L252 | [
"def _post(self, *args, **kwargs):\n \"\"\"Wrapper around Requests for POST requests\n\n Returns:\n Response:\n A Requests Response object\n \"\"\"\n\n if 'timeout' not in kwargs:\n kwargs['timeout'] = self.timeout\n\n req = self.session.post(*args, **kwargs)\n return req\... | class CrowdServer(object):
"""Crowd server authentication object.
This is a Crowd authentication class to be configured for a
particular application (app_name) to authenticate users
against a Crowd server (crowd_url).
This module uses the Crowd JSON API for talking to Crowd.
An application account must be configured in the Crowd server
and permitted to authenticate users against one or more user
directories prior to using this module.
Please see the Crowd documentation for information about
configuring additional applications to talk to Crowd.
The ``ssl_verify`` parameter controls how and if certificates are verified.
If ``True``, the SSL certificate will be verified.
A CA_BUNDLE path can also be provided.
The ``client_cert`` tuple (cert,key) specifies a SSL client certificate and key files.
"""
def __init__(self, crowd_url, app_name, app_pass, ssl_verify=True,
timeout=None, client_cert=None):
self.crowd_url = crowd_url
self.app_name = app_name
self.app_pass = app_pass
self.rest_url = crowd_url.rstrip("/") + "/rest/usermanagement/1"
self.ssl_verify = ssl_verify
self.client_cert = client_cert
self.timeout = timeout
self.session = self._build_session(content_type='json')
self.session_xml = self._build_session(content_type='xml')
def __str__(self):
return "Crowd Server at %s" % self.crowd_url
def __repr__(self):
return "<CrowdServer('%s', '%s', '%s')>" % \
(self.crowd_url, self.app_name, self.app_pass)
def _build_session(self, content_type='json'):
headers = {
'Content-Type': 'application/{}'.format(content_type),
'Accept': 'application/{}'.format(content_type),
}
session = requests.Session()
session.verify = self.ssl_verify
session.cert = self.client_cert
session.auth = requests.auth.HTTPBasicAuth(self.app_name, self.app_pass)
session.headers.update(headers)
return session
def _get(self, *args, **kwargs):
"""Wrapper around Requests for GET requests
Returns:
Response:
A Requests Response object
"""
if 'timeout' not in kwargs:
kwargs['timeout'] = self.timeout
req = self.session.get(*args, **kwargs)
return req
def _get_xml(self, *args, **kwargs):
"""Wrapper around Requests for GET XML requests
Returns:
Response:
A Requests Response object
"""
req = self.session_xml.get(*args, **kwargs)
return req
def _post(self, *args, **kwargs):
"""Wrapper around Requests for POST requests
Returns:
Response:
A Requests Response object
"""
if 'timeout' not in kwargs:
kwargs['timeout'] = self.timeout
req = self.session.post(*args, **kwargs)
return req
def _post_xml(self, *args, **kwargs):
"""Wrapper around Requests for POST requests
Returns:
Response:
A Requests Response object
"""
if 'timeout' not in kwargs:
kwargs['timeout'] = self.timeout
req = self.session_xml.post(*args, **kwargs)
return req
def _put(self, *args, **kwargs):
"""Wrapper around Requests for PUT requests
Returns:
Response:
A Requests Response object
"""
if 'timeout' not in kwargs:
kwargs['timeout'] = self.timeout
req = self.session.put(*args, **kwargs)
return req
def _delete(self, *args, **kwargs):
"""Wrapper around Requests for DELETE requests
Returns:
Response:
A Requests Response object
"""
if 'timeout' not in kwargs:
kwargs['timeout'] = self.timeout
req = self.session.delete(*args, **kwargs)
return req
def auth_ping(self):
"""Test that application can authenticate to Crowd.
Attempts to authenticate the application user against
the Crowd server. In order for user authentication to
work, an application must be able to authenticate.
Returns:
bool:
True if the application authentication succeeded.
"""
url = self.rest_url + "/non-existent/location"
response = self._get(url)
if response.status_code == 401:
return False
elif response.status_code == 404:
return True
else:
# An error encountered - problem with the Crowd server?
return False
def auth_user(self, username, password):
"""Authenticate a user account against the Crowd server.
Attempts to authenticate the user against the Crowd server.
Args:
username: The account username.
password: The account password.
Returns:
dict:
A dict mapping of user attributes if the application
authentication was successful. See the Crowd documentation
for the authoritative list of attributes.
None: If authentication failed.
"""
response = self._post(self.rest_url + "/authentication",
data=json.dumps({"value": password}),
params={"username": username})
# If authentication failed for any reason return None
if not response.ok:
return None
# ...otherwise return a dictionary of user attributes
return response.json()
def validate_session(self, token, remote="127.0.0.1", proxy=None):
"""Validate a session token.
Validate a previously acquired session token against the
Crowd server. This may be a token provided by a user from
a http cookie or by some other means.
Args:
token: The session token.
remote: The remote address of the user.
proxy: Value of X-Forwarded-For server header
Returns:
dict:
A dict mapping of user attributes if the application
authentication was successful. See the Crowd
documentation for the authoritative list of attributes.
None: If authentication failed.
"""
params = {
"validationFactors": [
{"name": "remote_address", "value": remote, },
]
}
if proxy:
params["validation-factors"]["validationFactors"].append({"name": "X-Forwarded-For", "value": proxy, })
url = self.rest_url + "/session/%s" % token
response = self._post(url, data=json.dumps(params), params={"expand": "user"})
# For consistency between methods use None rather than False
# If token validation failed for any reason return None
if not response.ok:
return None
# Otherwise return the user object
return response.json()
def terminate_session(self, token):
"""Terminates the session token, effectively logging out the user
from all crowd-enabled services.
Args:
token: The session token.
Returns:
True: If session terminated
None: If session termination failed
"""
url = self.rest_url + "/session/%s" % token
response = self._delete(url)
# For consistency between methods use None rather than False
# If token validation failed for any reason return None
if not response.ok:
return None
# Otherwise return True
return True
def add_user(self, username, raise_on_error=False, **kwargs):
"""Add a user to the directory
Args:
username: The account username
raise_on_error: optional (default: False)
**kwargs: key-value pairs:
password: mandatory
email: mandatory
first_name: optional
last_name: optional
display_name: optional
active: optional (default True)
Returns:
True: Succeeded
False: If unsuccessful
"""
# Check that mandatory elements have been provided
if 'password' not in kwargs:
raise ValueError("missing password")
if 'email' not in kwargs:
raise ValueError("missing email")
# Populate data with default and mandatory values.
# A KeyError means a mandatory value was not provided,
# so raise a ValueError indicating bad args.
try:
data = {
"name": username,
"first-name": username,
"last-name": username,
"display-name": username,
"email": kwargs["email"],
"password": {"value": kwargs["password"]},
"active": True
}
except KeyError:
return ValueError
# Remove special case 'password'
del(kwargs["password"])
# Put values from kwargs into data
for k, v in kwargs.items():
new_k = k.replace("_", "-")
if new_k not in data:
raise ValueError("invalid argument %s" % k)
data[new_k] = v
response = self._post(self.rest_url + "/user",
data=json.dumps(data))
if response.status_code == 201:
return True
if raise_on_error:
raise RuntimeError(response.json()['message'])
return False
def get_user(self, username):
"""Retrieve information about a user
Returns:
dict: User information
None: If no user or failure occurred
"""
response = self._get(self.rest_url + "/user",
params={"username": username,
"expand": "attributes"})
if not response.ok:
return None
return response.json()
def set_active(self, username, active_state):
"""Set the active state of a user
Args:
username: The account username
active_state: True or False
Returns:
True: If successful
None: If no user or failure occurred
"""
if active_state not in (True, False):
raise ValueError("active_state must be True or False")
user = self.get_user(username)
if user is None:
return None
if user['active'] is active_state:
# Already in desired state
return True
user['active'] = active_state
response = self._put(self.rest_url + "/user",
params={"username": username},
data=json.dumps(user))
if response.status_code == 204:
return True
return None
def set_user_attribute(self, username, attribute, value, raise_on_error=False):
"""Set an attribute on a user
:param username: The username on which to set the attribute
:param attribute: The name of the attribute to set
:param value: The value of the attribute to set
:return: True on success, False on failure.
"""
data = {
'attributes': [
{
'name': attribute,
'values': [
value
]
},
]
}
response = self._post(self.rest_url + "/user/attribute",
params={"username": username,},
data=json.dumps(data))
if response.status_code == 204:
return True
if raise_on_error:
raise RuntimeError(response.json()['message'])
return False
def add_user_to_group(self, username, groupname, raise_on_error=False):
"""Add a user to a group
:param username: The username to assign to the group
:param groupname: The group name into which to assign the user
:return: True on success, False on failure.
"""
data = {
'name': groupname,
}
response = self._post(self.rest_url + "/user/group/direct",
params={"username": username,},
data=json.dumps(data))
if response.status_code == 201:
return True
if raise_on_error:
raise RuntimeError(response.json()['message'])
return False
def remove_user_from_group(self, username, groupname, raise_on_error=False):
"""Remove a user from a group
Attempts to remove a user from a group
Args
username: The username to remove from the group.
groupname: The group name to be removed from the user.
Returns:
True: Succeeded
False: If unsuccessful
"""
response = self._delete(self.rest_url + "/group/user/direct",params={"username": username, "groupname": groupname})
if response.status_code == 204:
return True
if raise_on_error:
raise RuntimeError(response.json()['message'])
return False
def change_password(self, username, newpassword, raise_on_error=False):
"""Change new password for a user
Args:
username: The account username.
newpassword: The account new password.
raise_on_error: optional (default: False)
Returns:
True: Succeeded
False: If unsuccessful
"""
response = self._put(self.rest_url + "/user/password",
data=json.dumps({"value": newpassword}),
params={"username": username})
if response.ok:
return True
if raise_on_error:
raise RuntimeError(response.json()['message'])
return False
def send_password_reset_link(self, username):
"""Sends the user a password reset link (by email)
Args:
username: The account username.
Returns:
True: Succeeded
False: If unsuccessful
"""
response = self._post(self.rest_url + "/user/mail/password",
params={"username": username})
if response.ok:
return True
return False
def get_groups(self, username):
"""Retrieves a list of group names that have <username> as a direct member.
Returns:
list:
A list of strings of group names.
"""
response = self._get(self.rest_url + "/user/group/direct",
params={"username": username})
if not response.ok:
return None
return [g['name'] for g in response.json()['groups']]
def get_nested_groups(self, username):
"""Retrieve a list of all group names that have <username> as a direct or indirect member.
Args:
username: The account username.
Returns:
list:
A list of strings of group names.
"""
response = self._get(self.rest_url + "/user/group/nested",
params={"username": username})
if not response.ok:
return None
return [g['name'] for g in response.json()['groups']]
def get_nested_group_users(self, groupname):
"""Retrieves a list of all users that directly or indirectly belong to the given groupname.
Args:
groupname: The group name.
Returns:
list:
A list of strings of user names.
"""
response = self._get(self.rest_url + "/group/user/nested",
params={"groupname": groupname,
"start-index": 0,
"max-results": 99999})
if not response.ok:
return None
return [u['name'] for u in response.json()['users']]
def user_exists(self, username):
"""Determines if the user exists.
Args:
username: The user name.
Returns:
bool:
True if the user exists in the Crowd application.
"""
response = self._get(self.rest_url + "/user",
params={"username": username})
if not response.ok:
return None
return True
def get_memberships(self):
"""Fetches all group memberships.
Returns:
dict:
key: group name
value: (array of users, array of groups)
"""
response = self._get_xml(self.rest_url + "/group/membership")
if not response.ok:
return None
xmltree = etree.fromstring(response.content)
memberships = {}
for mg in xmltree.findall('membership'):
# coerce values to unicode in a python 2 and 3 compatible way
group = u'{}'.format(mg.get('group'))
users = [u'{}'.format(u.get('name')) for u in mg.find('users').findall('user')]
groups = [u'{}'.format(g.get('name')) for g in mg.find('groups').findall('group')]
memberships[group] = {u'users': users, u'groups': groups}
return memberships
def search(self, entity_type, property_name, search_string, start_index=0, max_results=99999):
"""Performs a user search using the Crowd search API.
https://developer.atlassian.com/display/CROWDDEV/Crowd+REST+Resources#CrowdRESTResources-SearchResource
Args:
entity_type: 'user' or 'group'
property_name: eg. 'email', 'name'
search_string: the string to search for.
start_index: starting index of the results (default: 0)
max_results: maximum number of results returned (default: 99999)
Returns:
json results:
Returns search results.
"""
params = {
"entity-type": entity_type,
"expand": entity_type,
"property-search-restriction": {
"property": {"name": property_name, "type": "STRING"},
"match-mode": "CONTAINS",
"value": search_string,
}
}
params = {
'entity-type': entity_type,
'expand': entity_type,
'start-index': start_index,
'max-results': max_results
}
# Construct XML payload of the form:
# <property-search-restriction>
# <property>
# <name>email</name>
# <type>STRING</type>
# </property>
# <match-mode>EXACTLY_MATCHES</match-mode>
# <value>bob@example.net</value>
# </property-search-restriction>
root = etree.Element('property-search-restriction')
property_ = etree.Element('property')
prop_name = etree.Element('name')
prop_name.text = property_name
property_.append(prop_name)
prop_type = etree.Element('type')
prop_type.text = 'STRING'
property_.append(prop_type)
root.append(property_)
match_mode = etree.Element('match-mode')
match_mode.text = 'CONTAINS'
root.append(match_mode)
value = etree.Element('value')
value.text = search_string
root.append(value)
# Construct the XML payload expected by search API
payload = '<?xml version="1.0" encoding="UTF-8"?>\n' + etree.tostring(root).decode('utf-8')
# We're sending XML but would like a JSON response
session = self._build_session(content_type='xml')
session.headers.update({'Accept': 'application/json'})
response = session.post(self.rest_url + "/search", params=params, data=payload, timeout=self.timeout)
if not response.ok:
return None
return response.json()
|
pycontribs/python-crowd | crowd.py | CrowdServer.validate_session | python | def validate_session(self, token, remote="127.0.0.1", proxy=None):
params = {
"validationFactors": [
{"name": "remote_address", "value": remote, },
]
}
if proxy:
params["validation-factors"]["validationFactors"].append({"name": "X-Forwarded-For", "value": proxy, })
url = self.rest_url + "/session/%s" % token
response = self._post(url, data=json.dumps(params), params={"expand": "user"})
# For consistency between methods use None rather than False
# If token validation failed for any reason return None
if not response.ok:
return None
# Otherwise return the user object
return response.json() | Validate a session token.
Validate a previously acquired session token against the
Crowd server. This may be a token provided by a user from
a http cookie or by some other means.
Args:
token: The session token.
remote: The remote address of the user.
proxy: Value of X-Forwarded-For server header
Returns:
dict:
A dict mapping of user attributes if the application
authentication was successful. See the Crowd
documentation for the authoritative list of attributes.
None: If authentication failed. | train | https://github.com/pycontribs/python-crowd/blob/a075e45774dd5baecf0217843cda747084268e32/crowd.py#L254-L295 | [
"def _post(self, *args, **kwargs):\n \"\"\"Wrapper around Requests for POST requests\n\n Returns:\n Response:\n A Requests Response object\n \"\"\"\n\n if 'timeout' not in kwargs:\n kwargs['timeout'] = self.timeout\n\n req = self.session.post(*args, **kwargs)\n return req\... | class CrowdServer(object):
"""Crowd server authentication object.
This is a Crowd authentication class to be configured for a
particular application (app_name) to authenticate users
against a Crowd server (crowd_url).
This module uses the Crowd JSON API for talking to Crowd.
An application account must be configured in the Crowd server
and permitted to authenticate users against one or more user
directories prior to using this module.
Please see the Crowd documentation for information about
configuring additional applications to talk to Crowd.
The ``ssl_verify`` parameter controls how and if certificates are verified.
If ``True``, the SSL certificate will be verified.
A CA_BUNDLE path can also be provided.
The ``client_cert`` tuple (cert,key) specifies a SSL client certificate and key files.
"""
def __init__(self, crowd_url, app_name, app_pass, ssl_verify=True,
timeout=None, client_cert=None):
self.crowd_url = crowd_url
self.app_name = app_name
self.app_pass = app_pass
self.rest_url = crowd_url.rstrip("/") + "/rest/usermanagement/1"
self.ssl_verify = ssl_verify
self.client_cert = client_cert
self.timeout = timeout
self.session = self._build_session(content_type='json')
self.session_xml = self._build_session(content_type='xml')
def __str__(self):
return "Crowd Server at %s" % self.crowd_url
def __repr__(self):
return "<CrowdServer('%s', '%s', '%s')>" % \
(self.crowd_url, self.app_name, self.app_pass)
def _build_session(self, content_type='json'):
headers = {
'Content-Type': 'application/{}'.format(content_type),
'Accept': 'application/{}'.format(content_type),
}
session = requests.Session()
session.verify = self.ssl_verify
session.cert = self.client_cert
session.auth = requests.auth.HTTPBasicAuth(self.app_name, self.app_pass)
session.headers.update(headers)
return session
def _get(self, *args, **kwargs):
"""Wrapper around Requests for GET requests
Returns:
Response:
A Requests Response object
"""
if 'timeout' not in kwargs:
kwargs['timeout'] = self.timeout
req = self.session.get(*args, **kwargs)
return req
def _get_xml(self, *args, **kwargs):
"""Wrapper around Requests for GET XML requests
Returns:
Response:
A Requests Response object
"""
req = self.session_xml.get(*args, **kwargs)
return req
def _post(self, *args, **kwargs):
"""Wrapper around Requests for POST requests
Returns:
Response:
A Requests Response object
"""
if 'timeout' not in kwargs:
kwargs['timeout'] = self.timeout
req = self.session.post(*args, **kwargs)
return req
def _post_xml(self, *args, **kwargs):
"""Wrapper around Requests for POST requests
Returns:
Response:
A Requests Response object
"""
if 'timeout' not in kwargs:
kwargs['timeout'] = self.timeout
req = self.session_xml.post(*args, **kwargs)
return req
def _put(self, *args, **kwargs):
"""Wrapper around Requests for PUT requests
Returns:
Response:
A Requests Response object
"""
if 'timeout' not in kwargs:
kwargs['timeout'] = self.timeout
req = self.session.put(*args, **kwargs)
return req
def _delete(self, *args, **kwargs):
"""Wrapper around Requests for DELETE requests
Returns:
Response:
A Requests Response object
"""
if 'timeout' not in kwargs:
kwargs['timeout'] = self.timeout
req = self.session.delete(*args, **kwargs)
return req
def auth_ping(self):
"""Test that application can authenticate to Crowd.
Attempts to authenticate the application user against
the Crowd server. In order for user authentication to
work, an application must be able to authenticate.
Returns:
bool:
True if the application authentication succeeded.
"""
url = self.rest_url + "/non-existent/location"
response = self._get(url)
if response.status_code == 401:
return False
elif response.status_code == 404:
return True
else:
# An error encountered - problem with the Crowd server?
return False
def auth_user(self, username, password):
"""Authenticate a user account against the Crowd server.
Attempts to authenticate the user against the Crowd server.
Args:
username: The account username.
password: The account password.
Returns:
dict:
A dict mapping of user attributes if the application
authentication was successful. See the Crowd documentation
for the authoritative list of attributes.
None: If authentication failed.
"""
response = self._post(self.rest_url + "/authentication",
data=json.dumps({"value": password}),
params={"username": username})
# If authentication failed for any reason return None
if not response.ok:
return None
# ...otherwise return a dictionary of user attributes
return response.json()
def get_session(self, username, password, remote="127.0.0.1", proxy=None):
"""Create a session for a user.
Attempts to create a user session on the Crowd server.
Args:
username: The account username.
password: The account password.
remote:
The remote address of the user. This can be used
to create multiple concurrent sessions for a user.
The host you run this program on may need to be configured
in Crowd as a trusted proxy for this to work.
proxy: Value of X-Forwarded-For server header.
Returns:
dict:
A dict mapping of user attributes if the application
authentication was successful. See the Crowd
documentation for the authoritative list of attributes.
None: If authentication failed.
"""
params = {
"username": username,
"password": password,
"validation-factors": {
"validationFactors": [
{"name": "remote_address", "value": remote, },
]
}
}
if proxy:
params["validation-factors"]["validationFactors"].append({"name": "X-Forwarded-For", "value": proxy, })
response = self._post(self.rest_url + "/session",
data=json.dumps(params),
params={"expand": "user"})
# If authentication failed for any reason return None
if not response.ok:
return None
# Otherwise return the user object
return response.json()
def terminate_session(self, token):
"""Terminates the session token, effectively logging out the user
from all crowd-enabled services.
Args:
token: The session token.
Returns:
True: If session terminated
None: If session termination failed
"""
url = self.rest_url + "/session/%s" % token
response = self._delete(url)
# For consistency between methods use None rather than False
# If token validation failed for any reason return None
if not response.ok:
return None
# Otherwise return True
return True
def add_user(self, username, raise_on_error=False, **kwargs):
"""Add a user to the directory
Args:
username: The account username
raise_on_error: optional (default: False)
**kwargs: key-value pairs:
password: mandatory
email: mandatory
first_name: optional
last_name: optional
display_name: optional
active: optional (default True)
Returns:
True: Succeeded
False: If unsuccessful
"""
# Check that mandatory elements have been provided
if 'password' not in kwargs:
raise ValueError("missing password")
if 'email' not in kwargs:
raise ValueError("missing email")
# Populate data with default and mandatory values.
# A KeyError means a mandatory value was not provided,
# so raise a ValueError indicating bad args.
try:
data = {
"name": username,
"first-name": username,
"last-name": username,
"display-name": username,
"email": kwargs["email"],
"password": {"value": kwargs["password"]},
"active": True
}
except KeyError:
return ValueError
# Remove special case 'password'
del(kwargs["password"])
# Put values from kwargs into data
for k, v in kwargs.items():
new_k = k.replace("_", "-")
if new_k not in data:
raise ValueError("invalid argument %s" % k)
data[new_k] = v
response = self._post(self.rest_url + "/user",
data=json.dumps(data))
if response.status_code == 201:
return True
if raise_on_error:
raise RuntimeError(response.json()['message'])
return False
def get_user(self, username):
"""Retrieve information about a user
Returns:
dict: User information
None: If no user or failure occurred
"""
response = self._get(self.rest_url + "/user",
params={"username": username,
"expand": "attributes"})
if not response.ok:
return None
return response.json()
def set_active(self, username, active_state):
"""Set the active state of a user
Args:
username: The account username
active_state: True or False
Returns:
True: If successful
None: If no user or failure occurred
"""
if active_state not in (True, False):
raise ValueError("active_state must be True or False")
user = self.get_user(username)
if user is None:
return None
if user['active'] is active_state:
# Already in desired state
return True
user['active'] = active_state
response = self._put(self.rest_url + "/user",
params={"username": username},
data=json.dumps(user))
if response.status_code == 204:
return True
return None
def set_user_attribute(self, username, attribute, value, raise_on_error=False):
"""Set an attribute on a user
:param username: The username on which to set the attribute
:param attribute: The name of the attribute to set
:param value: The value of the attribute to set
:return: True on success, False on failure.
"""
data = {
'attributes': [
{
'name': attribute,
'values': [
value
]
},
]
}
response = self._post(self.rest_url + "/user/attribute",
params={"username": username,},
data=json.dumps(data))
if response.status_code == 204:
return True
if raise_on_error:
raise RuntimeError(response.json()['message'])
return False
def add_user_to_group(self, username, groupname, raise_on_error=False):
"""Add a user to a group
:param username: The username to assign to the group
:param groupname: The group name into which to assign the user
:return: True on success, False on failure.
"""
data = {
'name': groupname,
}
response = self._post(self.rest_url + "/user/group/direct",
params={"username": username,},
data=json.dumps(data))
if response.status_code == 201:
return True
if raise_on_error:
raise RuntimeError(response.json()['message'])
return False
def remove_user_from_group(self, username, groupname, raise_on_error=False):
"""Remove a user from a group
Attempts to remove a user from a group
Args
username: The username to remove from the group.
groupname: The group name to be removed from the user.
Returns:
True: Succeeded
False: If unsuccessful
"""
response = self._delete(self.rest_url + "/group/user/direct",params={"username": username, "groupname": groupname})
if response.status_code == 204:
return True
if raise_on_error:
raise RuntimeError(response.json()['message'])
return False
def change_password(self, username, newpassword, raise_on_error=False):
"""Change new password for a user
Args:
username: The account username.
newpassword: The account new password.
raise_on_error: optional (default: False)
Returns:
True: Succeeded
False: If unsuccessful
"""
response = self._put(self.rest_url + "/user/password",
data=json.dumps({"value": newpassword}),
params={"username": username})
if response.ok:
return True
if raise_on_error:
raise RuntimeError(response.json()['message'])
return False
def send_password_reset_link(self, username):
"""Sends the user a password reset link (by email)
Args:
username: The account username.
Returns:
True: Succeeded
False: If unsuccessful
"""
response = self._post(self.rest_url + "/user/mail/password",
params={"username": username})
if response.ok:
return True
return False
def get_groups(self, username):
"""Retrieves a list of group names that have <username> as a direct member.
Returns:
list:
A list of strings of group names.
"""
response = self._get(self.rest_url + "/user/group/direct",
params={"username": username})
if not response.ok:
return None
return [g['name'] for g in response.json()['groups']]
def get_nested_groups(self, username):
"""Retrieve a list of all group names that have <username> as a direct or indirect member.
Args:
username: The account username.
Returns:
list:
A list of strings of group names.
"""
response = self._get(self.rest_url + "/user/group/nested",
params={"username": username})
if not response.ok:
return None
return [g['name'] for g in response.json()['groups']]
def get_nested_group_users(self, groupname):
"""Retrieves a list of all users that directly or indirectly belong to the given groupname.
Args:
groupname: The group name.
Returns:
list:
A list of strings of user names.
"""
response = self._get(self.rest_url + "/group/user/nested",
params={"groupname": groupname,
"start-index": 0,
"max-results": 99999})
if not response.ok:
return None
return [u['name'] for u in response.json()['users']]
def user_exists(self, username):
"""Determines if the user exists.
Args:
username: The user name.
Returns:
bool:
True if the user exists in the Crowd application.
"""
response = self._get(self.rest_url + "/user",
params={"username": username})
if not response.ok:
return None
return True
def get_memberships(self):
"""Fetches all group memberships.
Returns:
dict:
key: group name
value: (array of users, array of groups)
"""
response = self._get_xml(self.rest_url + "/group/membership")
if not response.ok:
return None
xmltree = etree.fromstring(response.content)
memberships = {}
for mg in xmltree.findall('membership'):
# coerce values to unicode in a python 2 and 3 compatible way
group = u'{}'.format(mg.get('group'))
users = [u'{}'.format(u.get('name')) for u in mg.find('users').findall('user')]
groups = [u'{}'.format(g.get('name')) for g in mg.find('groups').findall('group')]
memberships[group] = {u'users': users, u'groups': groups}
return memberships
def search(self, entity_type, property_name, search_string, start_index=0, max_results=99999):
"""Performs a user search using the Crowd search API.
https://developer.atlassian.com/display/CROWDDEV/Crowd+REST+Resources#CrowdRESTResources-SearchResource
Args:
entity_type: 'user' or 'group'
property_name: eg. 'email', 'name'
search_string: the string to search for.
start_index: starting index of the results (default: 0)
max_results: maximum number of results returned (default: 99999)
Returns:
json results:
Returns search results.
"""
params = {
"entity-type": entity_type,
"expand": entity_type,
"property-search-restriction": {
"property": {"name": property_name, "type": "STRING"},
"match-mode": "CONTAINS",
"value": search_string,
}
}
params = {
'entity-type': entity_type,
'expand': entity_type,
'start-index': start_index,
'max-results': max_results
}
# Construct XML payload of the form:
# <property-search-restriction>
# <property>
# <name>email</name>
# <type>STRING</type>
# </property>
# <match-mode>EXACTLY_MATCHES</match-mode>
# <value>bob@example.net</value>
# </property-search-restriction>
root = etree.Element('property-search-restriction')
property_ = etree.Element('property')
prop_name = etree.Element('name')
prop_name.text = property_name
property_.append(prop_name)
prop_type = etree.Element('type')
prop_type.text = 'STRING'
property_.append(prop_type)
root.append(property_)
match_mode = etree.Element('match-mode')
match_mode.text = 'CONTAINS'
root.append(match_mode)
value = etree.Element('value')
value.text = search_string
root.append(value)
# Construct the XML payload expected by search API
payload = '<?xml version="1.0" encoding="UTF-8"?>\n' + etree.tostring(root).decode('utf-8')
# We're sending XML but would like a JSON response
session = self._build_session(content_type='xml')
session.headers.update({'Accept': 'application/json'})
response = session.post(self.rest_url + "/search", params=params, data=payload, timeout=self.timeout)
if not response.ok:
return None
return response.json()
|
pycontribs/python-crowd | crowd.py | CrowdServer.terminate_session | python | def terminate_session(self, token):
url = self.rest_url + "/session/%s" % token
response = self._delete(url)
# For consistency between methods use None rather than False
# If token validation failed for any reason return None
if not response.ok:
return None
# Otherwise return True
return True | Terminates the session token, effectively logging out the user
from all crowd-enabled services.
Args:
token: The session token.
Returns:
True: If session terminated
None: If session termination failed | train | https://github.com/pycontribs/python-crowd/blob/a075e45774dd5baecf0217843cda747084268e32/crowd.py#L297-L319 | [
"def _delete(self, *args, **kwargs):\n \"\"\"Wrapper around Requests for DELETE requests\n\n Returns:\n Response:\n A Requests Response object\n \"\"\"\n\n if 'timeout' not in kwargs:\n kwargs['timeout'] = self.timeout\n\n req = self.session.delete(*args, **kwargs)\n retur... | class CrowdServer(object):
"""Crowd server authentication object.
This is a Crowd authentication class to be configured for a
particular application (app_name) to authenticate users
against a Crowd server (crowd_url).
This module uses the Crowd JSON API for talking to Crowd.
An application account must be configured in the Crowd server
and permitted to authenticate users against one or more user
directories prior to using this module.
Please see the Crowd documentation for information about
configuring additional applications to talk to Crowd.
The ``ssl_verify`` parameter controls how and if certificates are verified.
If ``True``, the SSL certificate will be verified.
A CA_BUNDLE path can also be provided.
The ``client_cert`` tuple (cert,key) specifies a SSL client certificate and key files.
"""
def __init__(self, crowd_url, app_name, app_pass, ssl_verify=True,
timeout=None, client_cert=None):
self.crowd_url = crowd_url
self.app_name = app_name
self.app_pass = app_pass
self.rest_url = crowd_url.rstrip("/") + "/rest/usermanagement/1"
self.ssl_verify = ssl_verify
self.client_cert = client_cert
self.timeout = timeout
self.session = self._build_session(content_type='json')
self.session_xml = self._build_session(content_type='xml')
def __str__(self):
return "Crowd Server at %s" % self.crowd_url
def __repr__(self):
return "<CrowdServer('%s', '%s', '%s')>" % \
(self.crowd_url, self.app_name, self.app_pass)
def _build_session(self, content_type='json'):
headers = {
'Content-Type': 'application/{}'.format(content_type),
'Accept': 'application/{}'.format(content_type),
}
session = requests.Session()
session.verify = self.ssl_verify
session.cert = self.client_cert
session.auth = requests.auth.HTTPBasicAuth(self.app_name, self.app_pass)
session.headers.update(headers)
return session
def _get(self, *args, **kwargs):
"""Wrapper around Requests for GET requests
Returns:
Response:
A Requests Response object
"""
if 'timeout' not in kwargs:
kwargs['timeout'] = self.timeout
req = self.session.get(*args, **kwargs)
return req
def _get_xml(self, *args, **kwargs):
"""Wrapper around Requests for GET XML requests
Returns:
Response:
A Requests Response object
"""
req = self.session_xml.get(*args, **kwargs)
return req
def _post(self, *args, **kwargs):
"""Wrapper around Requests for POST requests
Returns:
Response:
A Requests Response object
"""
if 'timeout' not in kwargs:
kwargs['timeout'] = self.timeout
req = self.session.post(*args, **kwargs)
return req
def _post_xml(self, *args, **kwargs):
"""Wrapper around Requests for POST requests
Returns:
Response:
A Requests Response object
"""
if 'timeout' not in kwargs:
kwargs['timeout'] = self.timeout
req = self.session_xml.post(*args, **kwargs)
return req
def _put(self, *args, **kwargs):
"""Wrapper around Requests for PUT requests
Returns:
Response:
A Requests Response object
"""
if 'timeout' not in kwargs:
kwargs['timeout'] = self.timeout
req = self.session.put(*args, **kwargs)
return req
def _delete(self, *args, **kwargs):
"""Wrapper around Requests for DELETE requests
Returns:
Response:
A Requests Response object
"""
if 'timeout' not in kwargs:
kwargs['timeout'] = self.timeout
req = self.session.delete(*args, **kwargs)
return req
def auth_ping(self):
"""Test that application can authenticate to Crowd.
Attempts to authenticate the application user against
the Crowd server. In order for user authentication to
work, an application must be able to authenticate.
Returns:
bool:
True if the application authentication succeeded.
"""
url = self.rest_url + "/non-existent/location"
response = self._get(url)
if response.status_code == 401:
return False
elif response.status_code == 404:
return True
else:
# An error encountered - problem with the Crowd server?
return False
def auth_user(self, username, password):
"""Authenticate a user account against the Crowd server.
Attempts to authenticate the user against the Crowd server.
Args:
username: The account username.
password: The account password.
Returns:
dict:
A dict mapping of user attributes if the application
authentication was successful. See the Crowd documentation
for the authoritative list of attributes.
None: If authentication failed.
"""
response = self._post(self.rest_url + "/authentication",
data=json.dumps({"value": password}),
params={"username": username})
# If authentication failed for any reason return None
if not response.ok:
return None
# ...otherwise return a dictionary of user attributes
return response.json()
def get_session(self, username, password, remote="127.0.0.1", proxy=None):
"""Create a session for a user.
Attempts to create a user session on the Crowd server.
Args:
username: The account username.
password: The account password.
remote:
The remote address of the user. This can be used
to create multiple concurrent sessions for a user.
The host you run this program on may need to be configured
in Crowd as a trusted proxy for this to work.
proxy: Value of X-Forwarded-For server header.
Returns:
dict:
A dict mapping of user attributes if the application
authentication was successful. See the Crowd
documentation for the authoritative list of attributes.
None: If authentication failed.
"""
params = {
"username": username,
"password": password,
"validation-factors": {
"validationFactors": [
{"name": "remote_address", "value": remote, },
]
}
}
if proxy:
params["validation-factors"]["validationFactors"].append({"name": "X-Forwarded-For", "value": proxy, })
response = self._post(self.rest_url + "/session",
data=json.dumps(params),
params={"expand": "user"})
# If authentication failed for any reason return None
if not response.ok:
return None
# Otherwise return the user object
return response.json()
def validate_session(self, token, remote="127.0.0.1", proxy=None):
"""Validate a session token.
Validate a previously acquired session token against the
Crowd server. This may be a token provided by a user from
a http cookie or by some other means.
Args:
token: The session token.
remote: The remote address of the user.
proxy: Value of X-Forwarded-For server header
Returns:
dict:
A dict mapping of user attributes if the application
authentication was successful. See the Crowd
documentation for the authoritative list of attributes.
None: If authentication failed.
"""
params = {
"validationFactors": [
{"name": "remote_address", "value": remote, },
]
}
if proxy:
params["validation-factors"]["validationFactors"].append({"name": "X-Forwarded-For", "value": proxy, })
url = self.rest_url + "/session/%s" % token
response = self._post(url, data=json.dumps(params), params={"expand": "user"})
# For consistency between methods use None rather than False
# If token validation failed for any reason return None
if not response.ok:
return None
# Otherwise return the user object
return response.json()
def add_user(self, username, raise_on_error=False, **kwargs):
"""Add a user to the directory
Args:
username: The account username
raise_on_error: optional (default: False)
**kwargs: key-value pairs:
password: mandatory
email: mandatory
first_name: optional
last_name: optional
display_name: optional
active: optional (default True)
Returns:
True: Succeeded
False: If unsuccessful
"""
# Check that mandatory elements have been provided
if 'password' not in kwargs:
raise ValueError("missing password")
if 'email' not in kwargs:
raise ValueError("missing email")
# Populate data with default and mandatory values.
# A KeyError means a mandatory value was not provided,
# so raise a ValueError indicating bad args.
try:
data = {
"name": username,
"first-name": username,
"last-name": username,
"display-name": username,
"email": kwargs["email"],
"password": {"value": kwargs["password"]},
"active": True
}
except KeyError:
return ValueError
# Remove special case 'password'
del(kwargs["password"])
# Put values from kwargs into data
for k, v in kwargs.items():
new_k = k.replace("_", "-")
if new_k not in data:
raise ValueError("invalid argument %s" % k)
data[new_k] = v
response = self._post(self.rest_url + "/user",
data=json.dumps(data))
if response.status_code == 201:
return True
if raise_on_error:
raise RuntimeError(response.json()['message'])
return False
def get_user(self, username):
"""Retrieve information about a user
Returns:
dict: User information
None: If no user or failure occurred
"""
response = self._get(self.rest_url + "/user",
params={"username": username,
"expand": "attributes"})
if not response.ok:
return None
return response.json()
def set_active(self, username, active_state):
"""Set the active state of a user
Args:
username: The account username
active_state: True or False
Returns:
True: If successful
None: If no user or failure occurred
"""
if active_state not in (True, False):
raise ValueError("active_state must be True or False")
user = self.get_user(username)
if user is None:
return None
if user['active'] is active_state:
# Already in desired state
return True
user['active'] = active_state
response = self._put(self.rest_url + "/user",
params={"username": username},
data=json.dumps(user))
if response.status_code == 204:
return True
return None
def set_user_attribute(self, username, attribute, value, raise_on_error=False):
"""Set an attribute on a user
:param username: The username on which to set the attribute
:param attribute: The name of the attribute to set
:param value: The value of the attribute to set
:return: True on success, False on failure.
"""
data = {
'attributes': [
{
'name': attribute,
'values': [
value
]
},
]
}
response = self._post(self.rest_url + "/user/attribute",
params={"username": username,},
data=json.dumps(data))
if response.status_code == 204:
return True
if raise_on_error:
raise RuntimeError(response.json()['message'])
return False
def add_user_to_group(self, username, groupname, raise_on_error=False):
"""Add a user to a group
:param username: The username to assign to the group
:param groupname: The group name into which to assign the user
:return: True on success, False on failure.
"""
data = {
'name': groupname,
}
response = self._post(self.rest_url + "/user/group/direct",
params={"username": username,},
data=json.dumps(data))
if response.status_code == 201:
return True
if raise_on_error:
raise RuntimeError(response.json()['message'])
return False
def remove_user_from_group(self, username, groupname, raise_on_error=False):
"""Remove a user from a group
Attempts to remove a user from a group
Args
username: The username to remove from the group.
groupname: The group name to be removed from the user.
Returns:
True: Succeeded
False: If unsuccessful
"""
response = self._delete(self.rest_url + "/group/user/direct",params={"username": username, "groupname": groupname})
if response.status_code == 204:
return True
if raise_on_error:
raise RuntimeError(response.json()['message'])
return False
def change_password(self, username, newpassword, raise_on_error=False):
"""Change new password for a user
Args:
username: The account username.
newpassword: The account new password.
raise_on_error: optional (default: False)
Returns:
True: Succeeded
False: If unsuccessful
"""
response = self._put(self.rest_url + "/user/password",
data=json.dumps({"value": newpassword}),
params={"username": username})
if response.ok:
return True
if raise_on_error:
raise RuntimeError(response.json()['message'])
return False
def send_password_reset_link(self, username):
"""Sends the user a password reset link (by email)
Args:
username: The account username.
Returns:
True: Succeeded
False: If unsuccessful
"""
response = self._post(self.rest_url + "/user/mail/password",
params={"username": username})
if response.ok:
return True
return False
def get_groups(self, username):
"""Retrieves a list of group names that have <username> as a direct member.
Returns:
list:
A list of strings of group names.
"""
response = self._get(self.rest_url + "/user/group/direct",
params={"username": username})
if not response.ok:
return None
return [g['name'] for g in response.json()['groups']]
def get_nested_groups(self, username):
"""Retrieve a list of all group names that have <username> as a direct or indirect member.
Args:
username: The account username.
Returns:
list:
A list of strings of group names.
"""
response = self._get(self.rest_url + "/user/group/nested",
params={"username": username})
if not response.ok:
return None
return [g['name'] for g in response.json()['groups']]
def get_nested_group_users(self, groupname):
"""Retrieves a list of all users that directly or indirectly belong to the given groupname.
Args:
groupname: The group name.
Returns:
list:
A list of strings of user names.
"""
response = self._get(self.rest_url + "/group/user/nested",
params={"groupname": groupname,
"start-index": 0,
"max-results": 99999})
if not response.ok:
return None
return [u['name'] for u in response.json()['users']]
def user_exists(self, username):
"""Determines if the user exists.
Args:
username: The user name.
Returns:
bool:
True if the user exists in the Crowd application.
"""
response = self._get(self.rest_url + "/user",
params={"username": username})
if not response.ok:
return None
return True
def get_memberships(self):
"""Fetches all group memberships.
Returns:
dict:
key: group name
value: (array of users, array of groups)
"""
response = self._get_xml(self.rest_url + "/group/membership")
if not response.ok:
return None
xmltree = etree.fromstring(response.content)
memberships = {}
for mg in xmltree.findall('membership'):
# coerce values to unicode in a python 2 and 3 compatible way
group = u'{}'.format(mg.get('group'))
users = [u'{}'.format(u.get('name')) for u in mg.find('users').findall('user')]
groups = [u'{}'.format(g.get('name')) for g in mg.find('groups').findall('group')]
memberships[group] = {u'users': users, u'groups': groups}
return memberships
def search(self, entity_type, property_name, search_string, start_index=0, max_results=99999):
"""Performs a user search using the Crowd search API.
https://developer.atlassian.com/display/CROWDDEV/Crowd+REST+Resources#CrowdRESTResources-SearchResource
Args:
entity_type: 'user' or 'group'
property_name: eg. 'email', 'name'
search_string: the string to search for.
start_index: starting index of the results (default: 0)
max_results: maximum number of results returned (default: 99999)
Returns:
json results:
Returns search results.
"""
params = {
"entity-type": entity_type,
"expand": entity_type,
"property-search-restriction": {
"property": {"name": property_name, "type": "STRING"},
"match-mode": "CONTAINS",
"value": search_string,
}
}
params = {
'entity-type': entity_type,
'expand': entity_type,
'start-index': start_index,
'max-results': max_results
}
# Construct XML payload of the form:
# <property-search-restriction>
# <property>
# <name>email</name>
# <type>STRING</type>
# </property>
# <match-mode>EXACTLY_MATCHES</match-mode>
# <value>bob@example.net</value>
# </property-search-restriction>
root = etree.Element('property-search-restriction')
property_ = etree.Element('property')
prop_name = etree.Element('name')
prop_name.text = property_name
property_.append(prop_name)
prop_type = etree.Element('type')
prop_type.text = 'STRING'
property_.append(prop_type)
root.append(property_)
match_mode = etree.Element('match-mode')
match_mode.text = 'CONTAINS'
root.append(match_mode)
value = etree.Element('value')
value.text = search_string
root.append(value)
# Construct the XML payload expected by search API
payload = '<?xml version="1.0" encoding="UTF-8"?>\n' + etree.tostring(root).decode('utf-8')
# We're sending XML but would like a JSON response
session = self._build_session(content_type='xml')
session.headers.update({'Accept': 'application/json'})
response = session.post(self.rest_url + "/search", params=params, data=payload, timeout=self.timeout)
if not response.ok:
return None
return response.json()
|
pycontribs/python-crowd | crowd.py | CrowdServer.add_user | python | def add_user(self, username, raise_on_error=False, **kwargs):
# Check that mandatory elements have been provided
if 'password' not in kwargs:
raise ValueError("missing password")
if 'email' not in kwargs:
raise ValueError("missing email")
# Populate data with default and mandatory values.
# A KeyError means a mandatory value was not provided,
# so raise a ValueError indicating bad args.
try:
data = {
"name": username,
"first-name": username,
"last-name": username,
"display-name": username,
"email": kwargs["email"],
"password": {"value": kwargs["password"]},
"active": True
}
except KeyError:
return ValueError
# Remove special case 'password'
del(kwargs["password"])
# Put values from kwargs into data
for k, v in kwargs.items():
new_k = k.replace("_", "-")
if new_k not in data:
raise ValueError("invalid argument %s" % k)
data[new_k] = v
response = self._post(self.rest_url + "/user",
data=json.dumps(data))
if response.status_code == 201:
return True
if raise_on_error:
raise RuntimeError(response.json()['message'])
return False | Add a user to the directory
Args:
username: The account username
raise_on_error: optional (default: False)
**kwargs: key-value pairs:
password: mandatory
email: mandatory
first_name: optional
last_name: optional
display_name: optional
active: optional (default True)
Returns:
True: Succeeded
False: If unsuccessful | train | https://github.com/pycontribs/python-crowd/blob/a075e45774dd5baecf0217843cda747084268e32/crowd.py#L321-L380 | [
"def _post(self, *args, **kwargs):\n \"\"\"Wrapper around Requests for POST requests\n\n Returns:\n Response:\n A Requests Response object\n \"\"\"\n\n if 'timeout' not in kwargs:\n kwargs['timeout'] = self.timeout\n\n req = self.session.post(*args, **kwargs)\n return req\... | class CrowdServer(object):
"""Crowd server authentication object.
This is a Crowd authentication class to be configured for a
particular application (app_name) to authenticate users
against a Crowd server (crowd_url).
This module uses the Crowd JSON API for talking to Crowd.
An application account must be configured in the Crowd server
and permitted to authenticate users against one or more user
directories prior to using this module.
Please see the Crowd documentation for information about
configuring additional applications to talk to Crowd.
The ``ssl_verify`` parameter controls how and if certificates are verified.
If ``True``, the SSL certificate will be verified.
A CA_BUNDLE path can also be provided.
The ``client_cert`` tuple (cert,key) specifies a SSL client certificate and key files.
"""
def __init__(self, crowd_url, app_name, app_pass, ssl_verify=True,
timeout=None, client_cert=None):
self.crowd_url = crowd_url
self.app_name = app_name
self.app_pass = app_pass
self.rest_url = crowd_url.rstrip("/") + "/rest/usermanagement/1"
self.ssl_verify = ssl_verify
self.client_cert = client_cert
self.timeout = timeout
self.session = self._build_session(content_type='json')
self.session_xml = self._build_session(content_type='xml')
def __str__(self):
return "Crowd Server at %s" % self.crowd_url
def __repr__(self):
return "<CrowdServer('%s', '%s', '%s')>" % \
(self.crowd_url, self.app_name, self.app_pass)
def _build_session(self, content_type='json'):
headers = {
'Content-Type': 'application/{}'.format(content_type),
'Accept': 'application/{}'.format(content_type),
}
session = requests.Session()
session.verify = self.ssl_verify
session.cert = self.client_cert
session.auth = requests.auth.HTTPBasicAuth(self.app_name, self.app_pass)
session.headers.update(headers)
return session
def _get(self, *args, **kwargs):
"""Wrapper around Requests for GET requests
Returns:
Response:
A Requests Response object
"""
if 'timeout' not in kwargs:
kwargs['timeout'] = self.timeout
req = self.session.get(*args, **kwargs)
return req
def _get_xml(self, *args, **kwargs):
"""Wrapper around Requests for GET XML requests
Returns:
Response:
A Requests Response object
"""
req = self.session_xml.get(*args, **kwargs)
return req
def _post(self, *args, **kwargs):
"""Wrapper around Requests for POST requests
Returns:
Response:
A Requests Response object
"""
if 'timeout' not in kwargs:
kwargs['timeout'] = self.timeout
req = self.session.post(*args, **kwargs)
return req
def _post_xml(self, *args, **kwargs):
"""Wrapper around Requests for POST requests
Returns:
Response:
A Requests Response object
"""
if 'timeout' not in kwargs:
kwargs['timeout'] = self.timeout
req = self.session_xml.post(*args, **kwargs)
return req
def _put(self, *args, **kwargs):
"""Wrapper around Requests for PUT requests
Returns:
Response:
A Requests Response object
"""
if 'timeout' not in kwargs:
kwargs['timeout'] = self.timeout
req = self.session.put(*args, **kwargs)
return req
def _delete(self, *args, **kwargs):
"""Wrapper around Requests for DELETE requests
Returns:
Response:
A Requests Response object
"""
if 'timeout' not in kwargs:
kwargs['timeout'] = self.timeout
req = self.session.delete(*args, **kwargs)
return req
def auth_ping(self):
"""Test that application can authenticate to Crowd.
Attempts to authenticate the application user against
the Crowd server. In order for user authentication to
work, an application must be able to authenticate.
Returns:
bool:
True if the application authentication succeeded.
"""
url = self.rest_url + "/non-existent/location"
response = self._get(url)
if response.status_code == 401:
return False
elif response.status_code == 404:
return True
else:
# An error encountered - problem with the Crowd server?
return False
def auth_user(self, username, password):
"""Authenticate a user account against the Crowd server.
Attempts to authenticate the user against the Crowd server.
Args:
username: The account username.
password: The account password.
Returns:
dict:
A dict mapping of user attributes if the application
authentication was successful. See the Crowd documentation
for the authoritative list of attributes.
None: If authentication failed.
"""
response = self._post(self.rest_url + "/authentication",
data=json.dumps({"value": password}),
params={"username": username})
# If authentication failed for any reason return None
if not response.ok:
return None
# ...otherwise return a dictionary of user attributes
return response.json()
def get_session(self, username, password, remote="127.0.0.1", proxy=None):
"""Create a session for a user.
Attempts to create a user session on the Crowd server.
Args:
username: The account username.
password: The account password.
remote:
The remote address of the user. This can be used
to create multiple concurrent sessions for a user.
The host you run this program on may need to be configured
in Crowd as a trusted proxy for this to work.
proxy: Value of X-Forwarded-For server header.
Returns:
dict:
A dict mapping of user attributes if the application
authentication was successful. See the Crowd
documentation for the authoritative list of attributes.
None: If authentication failed.
"""
params = {
"username": username,
"password": password,
"validation-factors": {
"validationFactors": [
{"name": "remote_address", "value": remote, },
]
}
}
if proxy:
params["validation-factors"]["validationFactors"].append({"name": "X-Forwarded-For", "value": proxy, })
response = self._post(self.rest_url + "/session",
data=json.dumps(params),
params={"expand": "user"})
# If authentication failed for any reason return None
if not response.ok:
return None
# Otherwise return the user object
return response.json()
def validate_session(self, token, remote="127.0.0.1", proxy=None):
"""Validate a session token.
Validate a previously acquired session token against the
Crowd server. This may be a token provided by a user from
a http cookie or by some other means.
Args:
token: The session token.
remote: The remote address of the user.
proxy: Value of X-Forwarded-For server header
Returns:
dict:
A dict mapping of user attributes if the application
authentication was successful. See the Crowd
documentation for the authoritative list of attributes.
None: If authentication failed.
"""
params = {
"validationFactors": [
{"name": "remote_address", "value": remote, },
]
}
if proxy:
params["validation-factors"]["validationFactors"].append({"name": "X-Forwarded-For", "value": proxy, })
url = self.rest_url + "/session/%s" % token
response = self._post(url, data=json.dumps(params), params={"expand": "user"})
# For consistency between methods use None rather than False
# If token validation failed for any reason return None
if not response.ok:
return None
# Otherwise return the user object
return response.json()
def terminate_session(self, token):
"""Terminates the session token, effectively logging out the user
from all crowd-enabled services.
Args:
token: The session token.
Returns:
True: If session terminated
None: If session termination failed
"""
url = self.rest_url + "/session/%s" % token
response = self._delete(url)
# For consistency between methods use None rather than False
# If token validation failed for any reason return None
if not response.ok:
return None
# Otherwise return True
return True
def get_user(self, username):
"""Retrieve information about a user
Returns:
dict: User information
None: If no user or failure occurred
"""
response = self._get(self.rest_url + "/user",
params={"username": username,
"expand": "attributes"})
if not response.ok:
return None
return response.json()
def set_active(self, username, active_state):
"""Set the active state of a user
Args:
username: The account username
active_state: True or False
Returns:
True: If successful
None: If no user or failure occurred
"""
if active_state not in (True, False):
raise ValueError("active_state must be True or False")
user = self.get_user(username)
if user is None:
return None
if user['active'] is active_state:
# Already in desired state
return True
user['active'] = active_state
response = self._put(self.rest_url + "/user",
params={"username": username},
data=json.dumps(user))
if response.status_code == 204:
return True
return None
def set_user_attribute(self, username, attribute, value, raise_on_error=False):
"""Set an attribute on a user
:param username: The username on which to set the attribute
:param attribute: The name of the attribute to set
:param value: The value of the attribute to set
:return: True on success, False on failure.
"""
data = {
'attributes': [
{
'name': attribute,
'values': [
value
]
},
]
}
response = self._post(self.rest_url + "/user/attribute",
params={"username": username,},
data=json.dumps(data))
if response.status_code == 204:
return True
if raise_on_error:
raise RuntimeError(response.json()['message'])
return False
def add_user_to_group(self, username, groupname, raise_on_error=False):
"""Add a user to a group
:param username: The username to assign to the group
:param groupname: The group name into which to assign the user
:return: True on success, False on failure.
"""
data = {
'name': groupname,
}
response = self._post(self.rest_url + "/user/group/direct",
params={"username": username,},
data=json.dumps(data))
if response.status_code == 201:
return True
if raise_on_error:
raise RuntimeError(response.json()['message'])
return False
def remove_user_from_group(self, username, groupname, raise_on_error=False):
"""Remove a user from a group
Attempts to remove a user from a group
Args
username: The username to remove from the group.
groupname: The group name to be removed from the user.
Returns:
True: Succeeded
False: If unsuccessful
"""
response = self._delete(self.rest_url + "/group/user/direct",params={"username": username, "groupname": groupname})
if response.status_code == 204:
return True
if raise_on_error:
raise RuntimeError(response.json()['message'])
return False
def change_password(self, username, newpassword, raise_on_error=False):
"""Change new password for a user
Args:
username: The account username.
newpassword: The account new password.
raise_on_error: optional (default: False)
Returns:
True: Succeeded
False: If unsuccessful
"""
response = self._put(self.rest_url + "/user/password",
data=json.dumps({"value": newpassword}),
params={"username": username})
if response.ok:
return True
if raise_on_error:
raise RuntimeError(response.json()['message'])
return False
def send_password_reset_link(self, username):
"""Sends the user a password reset link (by email)
Args:
username: The account username.
Returns:
True: Succeeded
False: If unsuccessful
"""
response = self._post(self.rest_url + "/user/mail/password",
params={"username": username})
if response.ok:
return True
return False
def get_groups(self, username):
"""Retrieves a list of group names that have <username> as a direct member.
Returns:
list:
A list of strings of group names.
"""
response = self._get(self.rest_url + "/user/group/direct",
params={"username": username})
if not response.ok:
return None
return [g['name'] for g in response.json()['groups']]
def get_nested_groups(self, username):
"""Retrieve a list of all group names that have <username> as a direct or indirect member.
Args:
username: The account username.
Returns:
list:
A list of strings of group names.
"""
response = self._get(self.rest_url + "/user/group/nested",
params={"username": username})
if not response.ok:
return None
return [g['name'] for g in response.json()['groups']]
def get_nested_group_users(self, groupname):
"""Retrieves a list of all users that directly or indirectly belong to the given groupname.
Args:
groupname: The group name.
Returns:
list:
A list of strings of user names.
"""
response = self._get(self.rest_url + "/group/user/nested",
params={"groupname": groupname,
"start-index": 0,
"max-results": 99999})
if not response.ok:
return None
return [u['name'] for u in response.json()['users']]
def user_exists(self, username):
"""Determines if the user exists.
Args:
username: The user name.
Returns:
bool:
True if the user exists in the Crowd application.
"""
response = self._get(self.rest_url + "/user",
params={"username": username})
if not response.ok:
return None
return True
def get_memberships(self):
"""Fetches all group memberships.
Returns:
dict:
key: group name
value: (array of users, array of groups)
"""
response = self._get_xml(self.rest_url + "/group/membership")
if not response.ok:
return None
xmltree = etree.fromstring(response.content)
memberships = {}
for mg in xmltree.findall('membership'):
# coerce values to unicode in a python 2 and 3 compatible way
group = u'{}'.format(mg.get('group'))
users = [u'{}'.format(u.get('name')) for u in mg.find('users').findall('user')]
groups = [u'{}'.format(g.get('name')) for g in mg.find('groups').findall('group')]
memberships[group] = {u'users': users, u'groups': groups}
return memberships
def search(self, entity_type, property_name, search_string, start_index=0, max_results=99999):
"""Performs a user search using the Crowd search API.
https://developer.atlassian.com/display/CROWDDEV/Crowd+REST+Resources#CrowdRESTResources-SearchResource
Args:
entity_type: 'user' or 'group'
property_name: eg. 'email', 'name'
search_string: the string to search for.
start_index: starting index of the results (default: 0)
max_results: maximum number of results returned (default: 99999)
Returns:
json results:
Returns search results.
"""
params = {
"entity-type": entity_type,
"expand": entity_type,
"property-search-restriction": {
"property": {"name": property_name, "type": "STRING"},
"match-mode": "CONTAINS",
"value": search_string,
}
}
params = {
'entity-type': entity_type,
'expand': entity_type,
'start-index': start_index,
'max-results': max_results
}
# Construct XML payload of the form:
# <property-search-restriction>
# <property>
# <name>email</name>
# <type>STRING</type>
# </property>
# <match-mode>EXACTLY_MATCHES</match-mode>
# <value>bob@example.net</value>
# </property-search-restriction>
root = etree.Element('property-search-restriction')
property_ = etree.Element('property')
prop_name = etree.Element('name')
prop_name.text = property_name
property_.append(prop_name)
prop_type = etree.Element('type')
prop_type.text = 'STRING'
property_.append(prop_type)
root.append(property_)
match_mode = etree.Element('match-mode')
match_mode.text = 'CONTAINS'
root.append(match_mode)
value = etree.Element('value')
value.text = search_string
root.append(value)
# Construct the XML payload expected by search API
payload = '<?xml version="1.0" encoding="UTF-8"?>\n' + etree.tostring(root).decode('utf-8')
# We're sending XML but would like a JSON response
session = self._build_session(content_type='xml')
session.headers.update({'Accept': 'application/json'})
response = session.post(self.rest_url + "/search", params=params, data=payload, timeout=self.timeout)
if not response.ok:
return None
return response.json()
|
pycontribs/python-crowd | crowd.py | CrowdServer.get_user | python | def get_user(self, username):
response = self._get(self.rest_url + "/user",
params={"username": username,
"expand": "attributes"})
if not response.ok:
return None
return response.json() | Retrieve information about a user
Returns:
dict: User information
None: If no user or failure occurred | train | https://github.com/pycontribs/python-crowd/blob/a075e45774dd5baecf0217843cda747084268e32/crowd.py#L382-L398 | [
"def _get(self, *args, **kwargs):\n \"\"\"Wrapper around Requests for GET requests\n\n Returns:\n Response:\n A Requests Response object\n \"\"\"\n\n if 'timeout' not in kwargs:\n kwargs['timeout'] = self.timeout\n\n req = self.session.get(*args, **kwargs)\n return req\n"
... | class CrowdServer(object):
"""Crowd server authentication object.
This is a Crowd authentication class to be configured for a
particular application (app_name) to authenticate users
against a Crowd server (crowd_url).
This module uses the Crowd JSON API for talking to Crowd.
An application account must be configured in the Crowd server
and permitted to authenticate users against one or more user
directories prior to using this module.
Please see the Crowd documentation for information about
configuring additional applications to talk to Crowd.
The ``ssl_verify`` parameter controls how and if certificates are verified.
If ``True``, the SSL certificate will be verified.
A CA_BUNDLE path can also be provided.
The ``client_cert`` tuple (cert,key) specifies a SSL client certificate and key files.
"""
def __init__(self, crowd_url, app_name, app_pass, ssl_verify=True,
timeout=None, client_cert=None):
self.crowd_url = crowd_url
self.app_name = app_name
self.app_pass = app_pass
self.rest_url = crowd_url.rstrip("/") + "/rest/usermanagement/1"
self.ssl_verify = ssl_verify
self.client_cert = client_cert
self.timeout = timeout
self.session = self._build_session(content_type='json')
self.session_xml = self._build_session(content_type='xml')
def __str__(self):
return "Crowd Server at %s" % self.crowd_url
def __repr__(self):
return "<CrowdServer('%s', '%s', '%s')>" % \
(self.crowd_url, self.app_name, self.app_pass)
def _build_session(self, content_type='json'):
headers = {
'Content-Type': 'application/{}'.format(content_type),
'Accept': 'application/{}'.format(content_type),
}
session = requests.Session()
session.verify = self.ssl_verify
session.cert = self.client_cert
session.auth = requests.auth.HTTPBasicAuth(self.app_name, self.app_pass)
session.headers.update(headers)
return session
def _get(self, *args, **kwargs):
"""Wrapper around Requests for GET requests
Returns:
Response:
A Requests Response object
"""
if 'timeout' not in kwargs:
kwargs['timeout'] = self.timeout
req = self.session.get(*args, **kwargs)
return req
def _get_xml(self, *args, **kwargs):
"""Wrapper around Requests for GET XML requests
Returns:
Response:
A Requests Response object
"""
req = self.session_xml.get(*args, **kwargs)
return req
def _post(self, *args, **kwargs):
"""Wrapper around Requests for POST requests
Returns:
Response:
A Requests Response object
"""
if 'timeout' not in kwargs:
kwargs['timeout'] = self.timeout
req = self.session.post(*args, **kwargs)
return req
def _post_xml(self, *args, **kwargs):
"""Wrapper around Requests for POST requests
Returns:
Response:
A Requests Response object
"""
if 'timeout' not in kwargs:
kwargs['timeout'] = self.timeout
req = self.session_xml.post(*args, **kwargs)
return req
def _put(self, *args, **kwargs):
"""Wrapper around Requests for PUT requests
Returns:
Response:
A Requests Response object
"""
if 'timeout' not in kwargs:
kwargs['timeout'] = self.timeout
req = self.session.put(*args, **kwargs)
return req
def _delete(self, *args, **kwargs):
"""Wrapper around Requests for DELETE requests
Returns:
Response:
A Requests Response object
"""
if 'timeout' not in kwargs:
kwargs['timeout'] = self.timeout
req = self.session.delete(*args, **kwargs)
return req
def auth_ping(self):
"""Test that application can authenticate to Crowd.
Attempts to authenticate the application user against
the Crowd server. In order for user authentication to
work, an application must be able to authenticate.
Returns:
bool:
True if the application authentication succeeded.
"""
url = self.rest_url + "/non-existent/location"
response = self._get(url)
if response.status_code == 401:
return False
elif response.status_code == 404:
return True
else:
# An error encountered - problem with the Crowd server?
return False
def auth_user(self, username, password):
"""Authenticate a user account against the Crowd server.
Attempts to authenticate the user against the Crowd server.
Args:
username: The account username.
password: The account password.
Returns:
dict:
A dict mapping of user attributes if the application
authentication was successful. See the Crowd documentation
for the authoritative list of attributes.
None: If authentication failed.
"""
response = self._post(self.rest_url + "/authentication",
data=json.dumps({"value": password}),
params={"username": username})
# If authentication failed for any reason return None
if not response.ok:
return None
# ...otherwise return a dictionary of user attributes
return response.json()
def get_session(self, username, password, remote="127.0.0.1", proxy=None):
"""Create a session for a user.
Attempts to create a user session on the Crowd server.
Args:
username: The account username.
password: The account password.
remote:
The remote address of the user. This can be used
to create multiple concurrent sessions for a user.
The host you run this program on may need to be configured
in Crowd as a trusted proxy for this to work.
proxy: Value of X-Forwarded-For server header.
Returns:
dict:
A dict mapping of user attributes if the application
authentication was successful. See the Crowd
documentation for the authoritative list of attributes.
None: If authentication failed.
"""
params = {
"username": username,
"password": password,
"validation-factors": {
"validationFactors": [
{"name": "remote_address", "value": remote, },
]
}
}
if proxy:
params["validation-factors"]["validationFactors"].append({"name": "X-Forwarded-For", "value": proxy, })
response = self._post(self.rest_url + "/session",
data=json.dumps(params),
params={"expand": "user"})
# If authentication failed for any reason return None
if not response.ok:
return None
# Otherwise return the user object
return response.json()
def validate_session(self, token, remote="127.0.0.1", proxy=None):
"""Validate a session token.
Validate a previously acquired session token against the
Crowd server. This may be a token provided by a user from
a http cookie or by some other means.
Args:
token: The session token.
remote: The remote address of the user.
proxy: Value of X-Forwarded-For server header
Returns:
dict:
A dict mapping of user attributes if the application
authentication was successful. See the Crowd
documentation for the authoritative list of attributes.
None: If authentication failed.
"""
params = {
"validationFactors": [
{"name": "remote_address", "value": remote, },
]
}
if proxy:
params["validation-factors"]["validationFactors"].append({"name": "X-Forwarded-For", "value": proxy, })
url = self.rest_url + "/session/%s" % token
response = self._post(url, data=json.dumps(params), params={"expand": "user"})
# For consistency between methods use None rather than False
# If token validation failed for any reason return None
if not response.ok:
return None
# Otherwise return the user object
return response.json()
def terminate_session(self, token):
"""Terminates the session token, effectively logging out the user
from all crowd-enabled services.
Args:
token: The session token.
Returns:
True: If session terminated
None: If session termination failed
"""
url = self.rest_url + "/session/%s" % token
response = self._delete(url)
# For consistency between methods use None rather than False
# If token validation failed for any reason return None
if not response.ok:
return None
# Otherwise return True
return True
def add_user(self, username, raise_on_error=False, **kwargs):
"""Add a user to the directory
Args:
username: The account username
raise_on_error: optional (default: False)
**kwargs: key-value pairs:
password: mandatory
email: mandatory
first_name: optional
last_name: optional
display_name: optional
active: optional (default True)
Returns:
True: Succeeded
False: If unsuccessful
"""
# Check that mandatory elements have been provided
if 'password' not in kwargs:
raise ValueError("missing password")
if 'email' not in kwargs:
raise ValueError("missing email")
# Populate data with default and mandatory values.
# A KeyError means a mandatory value was not provided,
# so raise a ValueError indicating bad args.
try:
data = {
"name": username,
"first-name": username,
"last-name": username,
"display-name": username,
"email": kwargs["email"],
"password": {"value": kwargs["password"]},
"active": True
}
except KeyError:
return ValueError
# Remove special case 'password'
del(kwargs["password"])
# Put values from kwargs into data
for k, v in kwargs.items():
new_k = k.replace("_", "-")
if new_k not in data:
raise ValueError("invalid argument %s" % k)
data[new_k] = v
response = self._post(self.rest_url + "/user",
data=json.dumps(data))
if response.status_code == 201:
return True
if raise_on_error:
raise RuntimeError(response.json()['message'])
return False
def set_active(self, username, active_state):
"""Set the active state of a user
Args:
username: The account username
active_state: True or False
Returns:
True: If successful
None: If no user or failure occurred
"""
if active_state not in (True, False):
raise ValueError("active_state must be True or False")
user = self.get_user(username)
if user is None:
return None
if user['active'] is active_state:
# Already in desired state
return True
user['active'] = active_state
response = self._put(self.rest_url + "/user",
params={"username": username},
data=json.dumps(user))
if response.status_code == 204:
return True
return None
def set_user_attribute(self, username, attribute, value, raise_on_error=False):
"""Set an attribute on a user
:param username: The username on which to set the attribute
:param attribute: The name of the attribute to set
:param value: The value of the attribute to set
:return: True on success, False on failure.
"""
data = {
'attributes': [
{
'name': attribute,
'values': [
value
]
},
]
}
response = self._post(self.rest_url + "/user/attribute",
params={"username": username,},
data=json.dumps(data))
if response.status_code == 204:
return True
if raise_on_error:
raise RuntimeError(response.json()['message'])
return False
def add_user_to_group(self, username, groupname, raise_on_error=False):
"""Add a user to a group
:param username: The username to assign to the group
:param groupname: The group name into which to assign the user
:return: True on success, False on failure.
"""
data = {
'name': groupname,
}
response = self._post(self.rest_url + "/user/group/direct",
params={"username": username,},
data=json.dumps(data))
if response.status_code == 201:
return True
if raise_on_error:
raise RuntimeError(response.json()['message'])
return False
def remove_user_from_group(self, username, groupname, raise_on_error=False):
"""Remove a user from a group
Attempts to remove a user from a group
Args
username: The username to remove from the group.
groupname: The group name to be removed from the user.
Returns:
True: Succeeded
False: If unsuccessful
"""
response = self._delete(self.rest_url + "/group/user/direct",params={"username": username, "groupname": groupname})
if response.status_code == 204:
return True
if raise_on_error:
raise RuntimeError(response.json()['message'])
return False
def change_password(self, username, newpassword, raise_on_error=False):
"""Change new password for a user
Args:
username: The account username.
newpassword: The account new password.
raise_on_error: optional (default: False)
Returns:
True: Succeeded
False: If unsuccessful
"""
response = self._put(self.rest_url + "/user/password",
data=json.dumps({"value": newpassword}),
params={"username": username})
if response.ok:
return True
if raise_on_error:
raise RuntimeError(response.json()['message'])
return False
def send_password_reset_link(self, username):
"""Sends the user a password reset link (by email)
Args:
username: The account username.
Returns:
True: Succeeded
False: If unsuccessful
"""
response = self._post(self.rest_url + "/user/mail/password",
params={"username": username})
if response.ok:
return True
return False
def get_groups(self, username):
"""Retrieves a list of group names that have <username> as a direct member.
Returns:
list:
A list of strings of group names.
"""
response = self._get(self.rest_url + "/user/group/direct",
params={"username": username})
if not response.ok:
return None
return [g['name'] for g in response.json()['groups']]
def get_nested_groups(self, username):
"""Retrieve a list of all group names that have <username> as a direct or indirect member.
Args:
username: The account username.
Returns:
list:
A list of strings of group names.
"""
response = self._get(self.rest_url + "/user/group/nested",
params={"username": username})
if not response.ok:
return None
return [g['name'] for g in response.json()['groups']]
def get_nested_group_users(self, groupname):
"""Retrieves a list of all users that directly or indirectly belong to the given groupname.
Args:
groupname: The group name.
Returns:
list:
A list of strings of user names.
"""
response = self._get(self.rest_url + "/group/user/nested",
params={"groupname": groupname,
"start-index": 0,
"max-results": 99999})
if not response.ok:
return None
return [u['name'] for u in response.json()['users']]
def user_exists(self, username):
"""Determines if the user exists.
Args:
username: The user name.
Returns:
bool:
True if the user exists in the Crowd application.
"""
response = self._get(self.rest_url + "/user",
params={"username": username})
if not response.ok:
return None
return True
def get_memberships(self):
"""Fetches all group memberships.
Returns:
dict:
key: group name
value: (array of users, array of groups)
"""
response = self._get_xml(self.rest_url + "/group/membership")
if not response.ok:
return None
xmltree = etree.fromstring(response.content)
memberships = {}
for mg in xmltree.findall('membership'):
# coerce values to unicode in a python 2 and 3 compatible way
group = u'{}'.format(mg.get('group'))
users = [u'{}'.format(u.get('name')) for u in mg.find('users').findall('user')]
groups = [u'{}'.format(g.get('name')) for g in mg.find('groups').findall('group')]
memberships[group] = {u'users': users, u'groups': groups}
return memberships
def search(self, entity_type, property_name, search_string, start_index=0, max_results=99999):
"""Performs a user search using the Crowd search API.
https://developer.atlassian.com/display/CROWDDEV/Crowd+REST+Resources#CrowdRESTResources-SearchResource
Args:
entity_type: 'user' or 'group'
property_name: eg. 'email', 'name'
search_string: the string to search for.
start_index: starting index of the results (default: 0)
max_results: maximum number of results returned (default: 99999)
Returns:
json results:
Returns search results.
"""
params = {
"entity-type": entity_type,
"expand": entity_type,
"property-search-restriction": {
"property": {"name": property_name, "type": "STRING"},
"match-mode": "CONTAINS",
"value": search_string,
}
}
params = {
'entity-type': entity_type,
'expand': entity_type,
'start-index': start_index,
'max-results': max_results
}
# Construct XML payload of the form:
# <property-search-restriction>
# <property>
# <name>email</name>
# <type>STRING</type>
# </property>
# <match-mode>EXACTLY_MATCHES</match-mode>
# <value>bob@example.net</value>
# </property-search-restriction>
root = etree.Element('property-search-restriction')
property_ = etree.Element('property')
prop_name = etree.Element('name')
prop_name.text = property_name
property_.append(prop_name)
prop_type = etree.Element('type')
prop_type.text = 'STRING'
property_.append(prop_type)
root.append(property_)
match_mode = etree.Element('match-mode')
match_mode.text = 'CONTAINS'
root.append(match_mode)
value = etree.Element('value')
value.text = search_string
root.append(value)
# Construct the XML payload expected by search API
payload = '<?xml version="1.0" encoding="UTF-8"?>\n' + etree.tostring(root).decode('utf-8')
# We're sending XML but would like a JSON response
session = self._build_session(content_type='xml')
session.headers.update({'Accept': 'application/json'})
response = session.post(self.rest_url + "/search", params=params, data=payload, timeout=self.timeout)
if not response.ok:
return None
return response.json()
|
pycontribs/python-crowd | crowd.py | CrowdServer.set_active | python | def set_active(self, username, active_state):
if active_state not in (True, False):
raise ValueError("active_state must be True or False")
user = self.get_user(username)
if user is None:
return None
if user['active'] is active_state:
# Already in desired state
return True
user['active'] = active_state
response = self._put(self.rest_url + "/user",
params={"username": username},
data=json.dumps(user))
if response.status_code == 204:
return True
return None | Set the active state of a user
Args:
username: The account username
active_state: True or False
Returns:
True: If successful
None: If no user or failure occurred | train | https://github.com/pycontribs/python-crowd/blob/a075e45774dd5baecf0217843cda747084268e32/crowd.py#L400-L431 | [
"def _put(self, *args, **kwargs):\n \"\"\"Wrapper around Requests for PUT requests\n\n Returns:\n Response:\n A Requests Response object\n \"\"\"\n\n if 'timeout' not in kwargs:\n kwargs['timeout'] = self.timeout\n\n req = self.session.put(*args, **kwargs)\n return req\n",... | class CrowdServer(object):
"""Crowd server authentication object.
This is a Crowd authentication class to be configured for a
particular application (app_name) to authenticate users
against a Crowd server (crowd_url).
This module uses the Crowd JSON API for talking to Crowd.
An application account must be configured in the Crowd server
and permitted to authenticate users against one or more user
directories prior to using this module.
Please see the Crowd documentation for information about
configuring additional applications to talk to Crowd.
The ``ssl_verify`` parameter controls how and if certificates are verified.
If ``True``, the SSL certificate will be verified.
A CA_BUNDLE path can also be provided.
The ``client_cert`` tuple (cert,key) specifies a SSL client certificate and key files.
"""
def __init__(self, crowd_url, app_name, app_pass, ssl_verify=True,
timeout=None, client_cert=None):
self.crowd_url = crowd_url
self.app_name = app_name
self.app_pass = app_pass
self.rest_url = crowd_url.rstrip("/") + "/rest/usermanagement/1"
self.ssl_verify = ssl_verify
self.client_cert = client_cert
self.timeout = timeout
self.session = self._build_session(content_type='json')
self.session_xml = self._build_session(content_type='xml')
def __str__(self):
return "Crowd Server at %s" % self.crowd_url
def __repr__(self):
return "<CrowdServer('%s', '%s', '%s')>" % \
(self.crowd_url, self.app_name, self.app_pass)
def _build_session(self, content_type='json'):
headers = {
'Content-Type': 'application/{}'.format(content_type),
'Accept': 'application/{}'.format(content_type),
}
session = requests.Session()
session.verify = self.ssl_verify
session.cert = self.client_cert
session.auth = requests.auth.HTTPBasicAuth(self.app_name, self.app_pass)
session.headers.update(headers)
return session
def _get(self, *args, **kwargs):
"""Wrapper around Requests for GET requests
Returns:
Response:
A Requests Response object
"""
if 'timeout' not in kwargs:
kwargs['timeout'] = self.timeout
req = self.session.get(*args, **kwargs)
return req
def _get_xml(self, *args, **kwargs):
"""Wrapper around Requests for GET XML requests
Returns:
Response:
A Requests Response object
"""
req = self.session_xml.get(*args, **kwargs)
return req
def _post(self, *args, **kwargs):
"""Wrapper around Requests for POST requests
Returns:
Response:
A Requests Response object
"""
if 'timeout' not in kwargs:
kwargs['timeout'] = self.timeout
req = self.session.post(*args, **kwargs)
return req
def _post_xml(self, *args, **kwargs):
"""Wrapper around Requests for POST requests
Returns:
Response:
A Requests Response object
"""
if 'timeout' not in kwargs:
kwargs['timeout'] = self.timeout
req = self.session_xml.post(*args, **kwargs)
return req
def _put(self, *args, **kwargs):
"""Wrapper around Requests for PUT requests
Returns:
Response:
A Requests Response object
"""
if 'timeout' not in kwargs:
kwargs['timeout'] = self.timeout
req = self.session.put(*args, **kwargs)
return req
def _delete(self, *args, **kwargs):
"""Wrapper around Requests for DELETE requests
Returns:
Response:
A Requests Response object
"""
if 'timeout' not in kwargs:
kwargs['timeout'] = self.timeout
req = self.session.delete(*args, **kwargs)
return req
def auth_ping(self):
"""Test that application can authenticate to Crowd.
Attempts to authenticate the application user against
the Crowd server. In order for user authentication to
work, an application must be able to authenticate.
Returns:
bool:
True if the application authentication succeeded.
"""
url = self.rest_url + "/non-existent/location"
response = self._get(url)
if response.status_code == 401:
return False
elif response.status_code == 404:
return True
else:
# An error encountered - problem with the Crowd server?
return False
def auth_user(self, username, password):
"""Authenticate a user account against the Crowd server.
Attempts to authenticate the user against the Crowd server.
Args:
username: The account username.
password: The account password.
Returns:
dict:
A dict mapping of user attributes if the application
authentication was successful. See the Crowd documentation
for the authoritative list of attributes.
None: If authentication failed.
"""
response = self._post(self.rest_url + "/authentication",
data=json.dumps({"value": password}),
params={"username": username})
# If authentication failed for any reason return None
if not response.ok:
return None
# ...otherwise return a dictionary of user attributes
return response.json()
def get_session(self, username, password, remote="127.0.0.1", proxy=None):
"""Create a session for a user.
Attempts to create a user session on the Crowd server.
Args:
username: The account username.
password: The account password.
remote:
The remote address of the user. This can be used
to create multiple concurrent sessions for a user.
The host you run this program on may need to be configured
in Crowd as a trusted proxy for this to work.
proxy: Value of X-Forwarded-For server header.
Returns:
dict:
A dict mapping of user attributes if the application
authentication was successful. See the Crowd
documentation for the authoritative list of attributes.
None: If authentication failed.
"""
params = {
"username": username,
"password": password,
"validation-factors": {
"validationFactors": [
{"name": "remote_address", "value": remote, },
]
}
}
if proxy:
params["validation-factors"]["validationFactors"].append({"name": "X-Forwarded-For", "value": proxy, })
response = self._post(self.rest_url + "/session",
data=json.dumps(params),
params={"expand": "user"})
# If authentication failed for any reason return None
if not response.ok:
return None
# Otherwise return the user object
return response.json()
def validate_session(self, token, remote="127.0.0.1", proxy=None):
"""Validate a session token.
Validate a previously acquired session token against the
Crowd server. This may be a token provided by a user from
a http cookie or by some other means.
Args:
token: The session token.
remote: The remote address of the user.
proxy: Value of X-Forwarded-For server header
Returns:
dict:
A dict mapping of user attributes if the application
authentication was successful. See the Crowd
documentation for the authoritative list of attributes.
None: If authentication failed.
"""
params = {
"validationFactors": [
{"name": "remote_address", "value": remote, },
]
}
if proxy:
params["validation-factors"]["validationFactors"].append({"name": "X-Forwarded-For", "value": proxy, })
url = self.rest_url + "/session/%s" % token
response = self._post(url, data=json.dumps(params), params={"expand": "user"})
# For consistency between methods use None rather than False
# If token validation failed for any reason return None
if not response.ok:
return None
# Otherwise return the user object
return response.json()
def terminate_session(self, token):
"""Terminates the session token, effectively logging out the user
from all crowd-enabled services.
Args:
token: The session token.
Returns:
True: If session terminated
None: If session termination failed
"""
url = self.rest_url + "/session/%s" % token
response = self._delete(url)
# For consistency between methods use None rather than False
# If token validation failed for any reason return None
if not response.ok:
return None
# Otherwise return True
return True
def add_user(self, username, raise_on_error=False, **kwargs):
"""Add a user to the directory
Args:
username: The account username
raise_on_error: optional (default: False)
**kwargs: key-value pairs:
password: mandatory
email: mandatory
first_name: optional
last_name: optional
display_name: optional
active: optional (default True)
Returns:
True: Succeeded
False: If unsuccessful
"""
# Check that mandatory elements have been provided
if 'password' not in kwargs:
raise ValueError("missing password")
if 'email' not in kwargs:
raise ValueError("missing email")
# Populate data with default and mandatory values.
# A KeyError means a mandatory value was not provided,
# so raise a ValueError indicating bad args.
try:
data = {
"name": username,
"first-name": username,
"last-name": username,
"display-name": username,
"email": kwargs["email"],
"password": {"value": kwargs["password"]},
"active": True
}
except KeyError:
return ValueError
# Remove special case 'password'
del(kwargs["password"])
# Put values from kwargs into data
for k, v in kwargs.items():
new_k = k.replace("_", "-")
if new_k not in data:
raise ValueError("invalid argument %s" % k)
data[new_k] = v
response = self._post(self.rest_url + "/user",
data=json.dumps(data))
if response.status_code == 201:
return True
if raise_on_error:
raise RuntimeError(response.json()['message'])
return False
def get_user(self, username):
"""Retrieve information about a user
Returns:
dict: User information
None: If no user or failure occurred
"""
response = self._get(self.rest_url + "/user",
params={"username": username,
"expand": "attributes"})
if not response.ok:
return None
return response.json()
def set_user_attribute(self, username, attribute, value, raise_on_error=False):
"""Set an attribute on a user
:param username: The username on which to set the attribute
:param attribute: The name of the attribute to set
:param value: The value of the attribute to set
:return: True on success, False on failure.
"""
data = {
'attributes': [
{
'name': attribute,
'values': [
value
]
},
]
}
response = self._post(self.rest_url + "/user/attribute",
params={"username": username,},
data=json.dumps(data))
if response.status_code == 204:
return True
if raise_on_error:
raise RuntimeError(response.json()['message'])
return False
def add_user_to_group(self, username, groupname, raise_on_error=False):
"""Add a user to a group
:param username: The username to assign to the group
:param groupname: The group name into which to assign the user
:return: True on success, False on failure.
"""
data = {
'name': groupname,
}
response = self._post(self.rest_url + "/user/group/direct",
params={"username": username,},
data=json.dumps(data))
if response.status_code == 201:
return True
if raise_on_error:
raise RuntimeError(response.json()['message'])
return False
def remove_user_from_group(self, username, groupname, raise_on_error=False):
"""Remove a user from a group
Attempts to remove a user from a group
Args
username: The username to remove from the group.
groupname: The group name to be removed from the user.
Returns:
True: Succeeded
False: If unsuccessful
"""
response = self._delete(self.rest_url + "/group/user/direct",params={"username": username, "groupname": groupname})
if response.status_code == 204:
return True
if raise_on_error:
raise RuntimeError(response.json()['message'])
return False
def change_password(self, username, newpassword, raise_on_error=False):
"""Change new password for a user
Args:
username: The account username.
newpassword: The account new password.
raise_on_error: optional (default: False)
Returns:
True: Succeeded
False: If unsuccessful
"""
response = self._put(self.rest_url + "/user/password",
data=json.dumps({"value": newpassword}),
params={"username": username})
if response.ok:
return True
if raise_on_error:
raise RuntimeError(response.json()['message'])
return False
def send_password_reset_link(self, username):
"""Sends the user a password reset link (by email)
Args:
username: The account username.
Returns:
True: Succeeded
False: If unsuccessful
"""
response = self._post(self.rest_url + "/user/mail/password",
params={"username": username})
if response.ok:
return True
return False
def get_groups(self, username):
"""Retrieves a list of group names that have <username> as a direct member.
Returns:
list:
A list of strings of group names.
"""
response = self._get(self.rest_url + "/user/group/direct",
params={"username": username})
if not response.ok:
return None
return [g['name'] for g in response.json()['groups']]
def get_nested_groups(self, username):
"""Retrieve a list of all group names that have <username> as a direct or indirect member.
Args:
username: The account username.
Returns:
list:
A list of strings of group names.
"""
response = self._get(self.rest_url + "/user/group/nested",
params={"username": username})
if not response.ok:
return None
return [g['name'] for g in response.json()['groups']]
def get_nested_group_users(self, groupname):
"""Retrieves a list of all users that directly or indirectly belong to the given groupname.
Args:
groupname: The group name.
Returns:
list:
A list of strings of user names.
"""
response = self._get(self.rest_url + "/group/user/nested",
params={"groupname": groupname,
"start-index": 0,
"max-results": 99999})
if not response.ok:
return None
return [u['name'] for u in response.json()['users']]
def user_exists(self, username):
"""Determines if the user exists.
Args:
username: The user name.
Returns:
bool:
True if the user exists in the Crowd application.
"""
response = self._get(self.rest_url + "/user",
params={"username": username})
if not response.ok:
return None
return True
def get_memberships(self):
"""Fetches all group memberships.
Returns:
dict:
key: group name
value: (array of users, array of groups)
"""
response = self._get_xml(self.rest_url + "/group/membership")
if not response.ok:
return None
xmltree = etree.fromstring(response.content)
memberships = {}
for mg in xmltree.findall('membership'):
# coerce values to unicode in a python 2 and 3 compatible way
group = u'{}'.format(mg.get('group'))
users = [u'{}'.format(u.get('name')) for u in mg.find('users').findall('user')]
groups = [u'{}'.format(g.get('name')) for g in mg.find('groups').findall('group')]
memberships[group] = {u'users': users, u'groups': groups}
return memberships
def search(self, entity_type, property_name, search_string, start_index=0, max_results=99999):
"""Performs a user search using the Crowd search API.
https://developer.atlassian.com/display/CROWDDEV/Crowd+REST+Resources#CrowdRESTResources-SearchResource
Args:
entity_type: 'user' or 'group'
property_name: eg. 'email', 'name'
search_string: the string to search for.
start_index: starting index of the results (default: 0)
max_results: maximum number of results returned (default: 99999)
Returns:
json results:
Returns search results.
"""
params = {
"entity-type": entity_type,
"expand": entity_type,
"property-search-restriction": {
"property": {"name": property_name, "type": "STRING"},
"match-mode": "CONTAINS",
"value": search_string,
}
}
params = {
'entity-type': entity_type,
'expand': entity_type,
'start-index': start_index,
'max-results': max_results
}
# Construct XML payload of the form:
# <property-search-restriction>
# <property>
# <name>email</name>
# <type>STRING</type>
# </property>
# <match-mode>EXACTLY_MATCHES</match-mode>
# <value>bob@example.net</value>
# </property-search-restriction>
root = etree.Element('property-search-restriction')
property_ = etree.Element('property')
prop_name = etree.Element('name')
prop_name.text = property_name
property_.append(prop_name)
prop_type = etree.Element('type')
prop_type.text = 'STRING'
property_.append(prop_type)
root.append(property_)
match_mode = etree.Element('match-mode')
match_mode.text = 'CONTAINS'
root.append(match_mode)
value = etree.Element('value')
value.text = search_string
root.append(value)
# Construct the XML payload expected by search API
payload = '<?xml version="1.0" encoding="UTF-8"?>\n' + etree.tostring(root).decode('utf-8')
# We're sending XML but would like a JSON response
session = self._build_session(content_type='xml')
session.headers.update({'Accept': 'application/json'})
response = session.post(self.rest_url + "/search", params=params, data=payload, timeout=self.timeout)
if not response.ok:
return None
return response.json()
|
pycontribs/python-crowd | crowd.py | CrowdServer.set_user_attribute | python | def set_user_attribute(self, username, attribute, value, raise_on_error=False):
data = {
'attributes': [
{
'name': attribute,
'values': [
value
]
},
]
}
response = self._post(self.rest_url + "/user/attribute",
params={"username": username,},
data=json.dumps(data))
if response.status_code == 204:
return True
if raise_on_error:
raise RuntimeError(response.json()['message'])
return False | Set an attribute on a user
:param username: The username on which to set the attribute
:param attribute: The name of the attribute to set
:param value: The value of the attribute to set
:return: True on success, False on failure. | train | https://github.com/pycontribs/python-crowd/blob/a075e45774dd5baecf0217843cda747084268e32/crowd.py#L433-L460 | [
"def _post(self, *args, **kwargs):\n \"\"\"Wrapper around Requests for POST requests\n\n Returns:\n Response:\n A Requests Response object\n \"\"\"\n\n if 'timeout' not in kwargs:\n kwargs['timeout'] = self.timeout\n\n req = self.session.post(*args, **kwargs)\n return req\... | class CrowdServer(object):
"""Crowd server authentication object.
This is a Crowd authentication class to be configured for a
particular application (app_name) to authenticate users
against a Crowd server (crowd_url).
This module uses the Crowd JSON API for talking to Crowd.
An application account must be configured in the Crowd server
and permitted to authenticate users against one or more user
directories prior to using this module.
Please see the Crowd documentation for information about
configuring additional applications to talk to Crowd.
The ``ssl_verify`` parameter controls how and if certificates are verified.
If ``True``, the SSL certificate will be verified.
A CA_BUNDLE path can also be provided.
The ``client_cert`` tuple (cert,key) specifies a SSL client certificate and key files.
"""
def __init__(self, crowd_url, app_name, app_pass, ssl_verify=True,
timeout=None, client_cert=None):
self.crowd_url = crowd_url
self.app_name = app_name
self.app_pass = app_pass
self.rest_url = crowd_url.rstrip("/") + "/rest/usermanagement/1"
self.ssl_verify = ssl_verify
self.client_cert = client_cert
self.timeout = timeout
self.session = self._build_session(content_type='json')
self.session_xml = self._build_session(content_type='xml')
def __str__(self):
return "Crowd Server at %s" % self.crowd_url
def __repr__(self):
return "<CrowdServer('%s', '%s', '%s')>" % \
(self.crowd_url, self.app_name, self.app_pass)
def _build_session(self, content_type='json'):
headers = {
'Content-Type': 'application/{}'.format(content_type),
'Accept': 'application/{}'.format(content_type),
}
session = requests.Session()
session.verify = self.ssl_verify
session.cert = self.client_cert
session.auth = requests.auth.HTTPBasicAuth(self.app_name, self.app_pass)
session.headers.update(headers)
return session
def _get(self, *args, **kwargs):
"""Wrapper around Requests for GET requests
Returns:
Response:
A Requests Response object
"""
if 'timeout' not in kwargs:
kwargs['timeout'] = self.timeout
req = self.session.get(*args, **kwargs)
return req
def _get_xml(self, *args, **kwargs):
"""Wrapper around Requests for GET XML requests
Returns:
Response:
A Requests Response object
"""
req = self.session_xml.get(*args, **kwargs)
return req
def _post(self, *args, **kwargs):
"""Wrapper around Requests for POST requests
Returns:
Response:
A Requests Response object
"""
if 'timeout' not in kwargs:
kwargs['timeout'] = self.timeout
req = self.session.post(*args, **kwargs)
return req
def _post_xml(self, *args, **kwargs):
"""Wrapper around Requests for POST requests
Returns:
Response:
A Requests Response object
"""
if 'timeout' not in kwargs:
kwargs['timeout'] = self.timeout
req = self.session_xml.post(*args, **kwargs)
return req
def _put(self, *args, **kwargs):
"""Wrapper around Requests for PUT requests
Returns:
Response:
A Requests Response object
"""
if 'timeout' not in kwargs:
kwargs['timeout'] = self.timeout
req = self.session.put(*args, **kwargs)
return req
def _delete(self, *args, **kwargs):
"""Wrapper around Requests for DELETE requests
Returns:
Response:
A Requests Response object
"""
if 'timeout' not in kwargs:
kwargs['timeout'] = self.timeout
req = self.session.delete(*args, **kwargs)
return req
def auth_ping(self):
"""Test that application can authenticate to Crowd.
Attempts to authenticate the application user against
the Crowd server. In order for user authentication to
work, an application must be able to authenticate.
Returns:
bool:
True if the application authentication succeeded.
"""
url = self.rest_url + "/non-existent/location"
response = self._get(url)
if response.status_code == 401:
return False
elif response.status_code == 404:
return True
else:
# An error encountered - problem with the Crowd server?
return False
def auth_user(self, username, password):
"""Authenticate a user account against the Crowd server.
Attempts to authenticate the user against the Crowd server.
Args:
username: The account username.
password: The account password.
Returns:
dict:
A dict mapping of user attributes if the application
authentication was successful. See the Crowd documentation
for the authoritative list of attributes.
None: If authentication failed.
"""
response = self._post(self.rest_url + "/authentication",
data=json.dumps({"value": password}),
params={"username": username})
# If authentication failed for any reason return None
if not response.ok:
return None
# ...otherwise return a dictionary of user attributes
return response.json()
def get_session(self, username, password, remote="127.0.0.1", proxy=None):
"""Create a session for a user.
Attempts to create a user session on the Crowd server.
Args:
username: The account username.
password: The account password.
remote:
The remote address of the user. This can be used
to create multiple concurrent sessions for a user.
The host you run this program on may need to be configured
in Crowd as a trusted proxy for this to work.
proxy: Value of X-Forwarded-For server header.
Returns:
dict:
A dict mapping of user attributes if the application
authentication was successful. See the Crowd
documentation for the authoritative list of attributes.
None: If authentication failed.
"""
params = {
"username": username,
"password": password,
"validation-factors": {
"validationFactors": [
{"name": "remote_address", "value": remote, },
]
}
}
if proxy:
params["validation-factors"]["validationFactors"].append({"name": "X-Forwarded-For", "value": proxy, })
response = self._post(self.rest_url + "/session",
data=json.dumps(params),
params={"expand": "user"})
# If authentication failed for any reason return None
if not response.ok:
return None
# Otherwise return the user object
return response.json()
def validate_session(self, token, remote="127.0.0.1", proxy=None):
"""Validate a session token.
Validate a previously acquired session token against the
Crowd server. This may be a token provided by a user from
a http cookie or by some other means.
Args:
token: The session token.
remote: The remote address of the user.
proxy: Value of X-Forwarded-For server header
Returns:
dict:
A dict mapping of user attributes if the application
authentication was successful. See the Crowd
documentation for the authoritative list of attributes.
None: If authentication failed.
"""
params = {
"validationFactors": [
{"name": "remote_address", "value": remote, },
]
}
if proxy:
params["validation-factors"]["validationFactors"].append({"name": "X-Forwarded-For", "value": proxy, })
url = self.rest_url + "/session/%s" % token
response = self._post(url, data=json.dumps(params), params={"expand": "user"})
# For consistency between methods use None rather than False
# If token validation failed for any reason return None
if not response.ok:
return None
# Otherwise return the user object
return response.json()
def terminate_session(self, token):
"""Terminates the session token, effectively logging out the user
from all crowd-enabled services.
Args:
token: The session token.
Returns:
True: If session terminated
None: If session termination failed
"""
url = self.rest_url + "/session/%s" % token
response = self._delete(url)
# For consistency between methods use None rather than False
# If token validation failed for any reason return None
if not response.ok:
return None
# Otherwise return True
return True
def add_user(self, username, raise_on_error=False, **kwargs):
"""Add a user to the directory
Args:
username: The account username
raise_on_error: optional (default: False)
**kwargs: key-value pairs:
password: mandatory
email: mandatory
first_name: optional
last_name: optional
display_name: optional
active: optional (default True)
Returns:
True: Succeeded
False: If unsuccessful
"""
# Check that mandatory elements have been provided
if 'password' not in kwargs:
raise ValueError("missing password")
if 'email' not in kwargs:
raise ValueError("missing email")
# Populate data with default and mandatory values.
# A KeyError means a mandatory value was not provided,
# so raise a ValueError indicating bad args.
try:
data = {
"name": username,
"first-name": username,
"last-name": username,
"display-name": username,
"email": kwargs["email"],
"password": {"value": kwargs["password"]},
"active": True
}
except KeyError:
return ValueError
# Remove special case 'password'
del(kwargs["password"])
# Put values from kwargs into data
for k, v in kwargs.items():
new_k = k.replace("_", "-")
if new_k not in data:
raise ValueError("invalid argument %s" % k)
data[new_k] = v
response = self._post(self.rest_url + "/user",
data=json.dumps(data))
if response.status_code == 201:
return True
if raise_on_error:
raise RuntimeError(response.json()['message'])
return False
def get_user(self, username):
"""Retrieve information about a user
Returns:
dict: User information
None: If no user or failure occurred
"""
response = self._get(self.rest_url + "/user",
params={"username": username,
"expand": "attributes"})
if not response.ok:
return None
return response.json()
def set_active(self, username, active_state):
"""Set the active state of a user
Args:
username: The account username
active_state: True or False
Returns:
True: If successful
None: If no user or failure occurred
"""
if active_state not in (True, False):
raise ValueError("active_state must be True or False")
user = self.get_user(username)
if user is None:
return None
if user['active'] is active_state:
# Already in desired state
return True
user['active'] = active_state
response = self._put(self.rest_url + "/user",
params={"username": username},
data=json.dumps(user))
if response.status_code == 204:
return True
return None
def add_user_to_group(self, username, groupname, raise_on_error=False):
"""Add a user to a group
:param username: The username to assign to the group
:param groupname: The group name into which to assign the user
:return: True on success, False on failure.
"""
data = {
'name': groupname,
}
response = self._post(self.rest_url + "/user/group/direct",
params={"username": username,},
data=json.dumps(data))
if response.status_code == 201:
return True
if raise_on_error:
raise RuntimeError(response.json()['message'])
return False
def remove_user_from_group(self, username, groupname, raise_on_error=False):
"""Remove a user from a group
Attempts to remove a user from a group
Args
username: The username to remove from the group.
groupname: The group name to be removed from the user.
Returns:
True: Succeeded
False: If unsuccessful
"""
response = self._delete(self.rest_url + "/group/user/direct",params={"username": username, "groupname": groupname})
if response.status_code == 204:
return True
if raise_on_error:
raise RuntimeError(response.json()['message'])
return False
def change_password(self, username, newpassword, raise_on_error=False):
"""Change new password for a user
Args:
username: The account username.
newpassword: The account new password.
raise_on_error: optional (default: False)
Returns:
True: Succeeded
False: If unsuccessful
"""
response = self._put(self.rest_url + "/user/password",
data=json.dumps({"value": newpassword}),
params={"username": username})
if response.ok:
return True
if raise_on_error:
raise RuntimeError(response.json()['message'])
return False
def send_password_reset_link(self, username):
"""Sends the user a password reset link (by email)
Args:
username: The account username.
Returns:
True: Succeeded
False: If unsuccessful
"""
response = self._post(self.rest_url + "/user/mail/password",
params={"username": username})
if response.ok:
return True
return False
def get_groups(self, username):
"""Retrieves a list of group names that have <username> as a direct member.
Returns:
list:
A list of strings of group names.
"""
response = self._get(self.rest_url + "/user/group/direct",
params={"username": username})
if not response.ok:
return None
return [g['name'] for g in response.json()['groups']]
def get_nested_groups(self, username):
"""Retrieve a list of all group names that have <username> as a direct or indirect member.
Args:
username: The account username.
Returns:
list:
A list of strings of group names.
"""
response = self._get(self.rest_url + "/user/group/nested",
params={"username": username})
if not response.ok:
return None
return [g['name'] for g in response.json()['groups']]
def get_nested_group_users(self, groupname):
"""Retrieves a list of all users that directly or indirectly belong to the given groupname.
Args:
groupname: The group name.
Returns:
list:
A list of strings of user names.
"""
response = self._get(self.rest_url + "/group/user/nested",
params={"groupname": groupname,
"start-index": 0,
"max-results": 99999})
if not response.ok:
return None
return [u['name'] for u in response.json()['users']]
def user_exists(self, username):
"""Determines if the user exists.
Args:
username: The user name.
Returns:
bool:
True if the user exists in the Crowd application.
"""
response = self._get(self.rest_url + "/user",
params={"username": username})
if not response.ok:
return None
return True
def get_memberships(self):
"""Fetches all group memberships.
Returns:
dict:
key: group name
value: (array of users, array of groups)
"""
response = self._get_xml(self.rest_url + "/group/membership")
if not response.ok:
return None
xmltree = etree.fromstring(response.content)
memberships = {}
for mg in xmltree.findall('membership'):
# coerce values to unicode in a python 2 and 3 compatible way
group = u'{}'.format(mg.get('group'))
users = [u'{}'.format(u.get('name')) for u in mg.find('users').findall('user')]
groups = [u'{}'.format(g.get('name')) for g in mg.find('groups').findall('group')]
memberships[group] = {u'users': users, u'groups': groups}
return memberships
def search(self, entity_type, property_name, search_string, start_index=0, max_results=99999):
"""Performs a user search using the Crowd search API.
https://developer.atlassian.com/display/CROWDDEV/Crowd+REST+Resources#CrowdRESTResources-SearchResource
Args:
entity_type: 'user' or 'group'
property_name: eg. 'email', 'name'
search_string: the string to search for.
start_index: starting index of the results (default: 0)
max_results: maximum number of results returned (default: 99999)
Returns:
json results:
Returns search results.
"""
params = {
"entity-type": entity_type,
"expand": entity_type,
"property-search-restriction": {
"property": {"name": property_name, "type": "STRING"},
"match-mode": "CONTAINS",
"value": search_string,
}
}
params = {
'entity-type': entity_type,
'expand': entity_type,
'start-index': start_index,
'max-results': max_results
}
# Construct XML payload of the form:
# <property-search-restriction>
# <property>
# <name>email</name>
# <type>STRING</type>
# </property>
# <match-mode>EXACTLY_MATCHES</match-mode>
# <value>bob@example.net</value>
# </property-search-restriction>
root = etree.Element('property-search-restriction')
property_ = etree.Element('property')
prop_name = etree.Element('name')
prop_name.text = property_name
property_.append(prop_name)
prop_type = etree.Element('type')
prop_type.text = 'STRING'
property_.append(prop_type)
root.append(property_)
match_mode = etree.Element('match-mode')
match_mode.text = 'CONTAINS'
root.append(match_mode)
value = etree.Element('value')
value.text = search_string
root.append(value)
# Construct the XML payload expected by search API
payload = '<?xml version="1.0" encoding="UTF-8"?>\n' + etree.tostring(root).decode('utf-8')
# We're sending XML but would like a JSON response
session = self._build_session(content_type='xml')
session.headers.update({'Accept': 'application/json'})
response = session.post(self.rest_url + "/search", params=params, data=payload, timeout=self.timeout)
if not response.ok:
return None
return response.json()
|
pycontribs/python-crowd | crowd.py | CrowdServer.add_user_to_group | python | def add_user_to_group(self, username, groupname, raise_on_error=False):
data = {
'name': groupname,
}
response = self._post(self.rest_url + "/user/group/direct",
params={"username": username,},
data=json.dumps(data))
if response.status_code == 201:
return True
if raise_on_error:
raise RuntimeError(response.json()['message'])
return False | Add a user to a group
:param username: The username to assign to the group
:param groupname: The group name into which to assign the user
:return: True on success, False on failure. | train | https://github.com/pycontribs/python-crowd/blob/a075e45774dd5baecf0217843cda747084268e32/crowd.py#L462-L481 | [
"def _post(self, *args, **kwargs):\n \"\"\"Wrapper around Requests for POST requests\n\n Returns:\n Response:\n A Requests Response object\n \"\"\"\n\n if 'timeout' not in kwargs:\n kwargs['timeout'] = self.timeout\n\n req = self.session.post(*args, **kwargs)\n return req\... | class CrowdServer(object):
"""Crowd server authentication object.
This is a Crowd authentication class to be configured for a
particular application (app_name) to authenticate users
against a Crowd server (crowd_url).
This module uses the Crowd JSON API for talking to Crowd.
An application account must be configured in the Crowd server
and permitted to authenticate users against one or more user
directories prior to using this module.
Please see the Crowd documentation for information about
configuring additional applications to talk to Crowd.
The ``ssl_verify`` parameter controls how and if certificates are verified.
If ``True``, the SSL certificate will be verified.
A CA_BUNDLE path can also be provided.
The ``client_cert`` tuple (cert,key) specifies a SSL client certificate and key files.
"""
def __init__(self, crowd_url, app_name, app_pass, ssl_verify=True,
timeout=None, client_cert=None):
self.crowd_url = crowd_url
self.app_name = app_name
self.app_pass = app_pass
self.rest_url = crowd_url.rstrip("/") + "/rest/usermanagement/1"
self.ssl_verify = ssl_verify
self.client_cert = client_cert
self.timeout = timeout
self.session = self._build_session(content_type='json')
self.session_xml = self._build_session(content_type='xml')
def __str__(self):
return "Crowd Server at %s" % self.crowd_url
def __repr__(self):
return "<CrowdServer('%s', '%s', '%s')>" % \
(self.crowd_url, self.app_name, self.app_pass)
def _build_session(self, content_type='json'):
headers = {
'Content-Type': 'application/{}'.format(content_type),
'Accept': 'application/{}'.format(content_type),
}
session = requests.Session()
session.verify = self.ssl_verify
session.cert = self.client_cert
session.auth = requests.auth.HTTPBasicAuth(self.app_name, self.app_pass)
session.headers.update(headers)
return session
def _get(self, *args, **kwargs):
"""Wrapper around Requests for GET requests
Returns:
Response:
A Requests Response object
"""
if 'timeout' not in kwargs:
kwargs['timeout'] = self.timeout
req = self.session.get(*args, **kwargs)
return req
def _get_xml(self, *args, **kwargs):
"""Wrapper around Requests for GET XML requests
Returns:
Response:
A Requests Response object
"""
req = self.session_xml.get(*args, **kwargs)
return req
def _post(self, *args, **kwargs):
"""Wrapper around Requests for POST requests
Returns:
Response:
A Requests Response object
"""
if 'timeout' not in kwargs:
kwargs['timeout'] = self.timeout
req = self.session.post(*args, **kwargs)
return req
def _post_xml(self, *args, **kwargs):
"""Wrapper around Requests for POST requests
Returns:
Response:
A Requests Response object
"""
if 'timeout' not in kwargs:
kwargs['timeout'] = self.timeout
req = self.session_xml.post(*args, **kwargs)
return req
def _put(self, *args, **kwargs):
"""Wrapper around Requests for PUT requests
Returns:
Response:
A Requests Response object
"""
if 'timeout' not in kwargs:
kwargs['timeout'] = self.timeout
req = self.session.put(*args, **kwargs)
return req
def _delete(self, *args, **kwargs):
"""Wrapper around Requests for DELETE requests
Returns:
Response:
A Requests Response object
"""
if 'timeout' not in kwargs:
kwargs['timeout'] = self.timeout
req = self.session.delete(*args, **kwargs)
return req
def auth_ping(self):
"""Test that application can authenticate to Crowd.
Attempts to authenticate the application user against
the Crowd server. In order for user authentication to
work, an application must be able to authenticate.
Returns:
bool:
True if the application authentication succeeded.
"""
url = self.rest_url + "/non-existent/location"
response = self._get(url)
if response.status_code == 401:
return False
elif response.status_code == 404:
return True
else:
# An error encountered - problem with the Crowd server?
return False
def auth_user(self, username, password):
"""Authenticate a user account against the Crowd server.
Attempts to authenticate the user against the Crowd server.
Args:
username: The account username.
password: The account password.
Returns:
dict:
A dict mapping of user attributes if the application
authentication was successful. See the Crowd documentation
for the authoritative list of attributes.
None: If authentication failed.
"""
response = self._post(self.rest_url + "/authentication",
data=json.dumps({"value": password}),
params={"username": username})
# If authentication failed for any reason return None
if not response.ok:
return None
# ...otherwise return a dictionary of user attributes
return response.json()
def get_session(self, username, password, remote="127.0.0.1", proxy=None):
"""Create a session for a user.
Attempts to create a user session on the Crowd server.
Args:
username: The account username.
password: The account password.
remote:
The remote address of the user. This can be used
to create multiple concurrent sessions for a user.
The host you run this program on may need to be configured
in Crowd as a trusted proxy for this to work.
proxy: Value of X-Forwarded-For server header.
Returns:
dict:
A dict mapping of user attributes if the application
authentication was successful. See the Crowd
documentation for the authoritative list of attributes.
None: If authentication failed.
"""
params = {
"username": username,
"password": password,
"validation-factors": {
"validationFactors": [
{"name": "remote_address", "value": remote, },
]
}
}
if proxy:
params["validation-factors"]["validationFactors"].append({"name": "X-Forwarded-For", "value": proxy, })
response = self._post(self.rest_url + "/session",
data=json.dumps(params),
params={"expand": "user"})
# If authentication failed for any reason return None
if not response.ok:
return None
# Otherwise return the user object
return response.json()
def validate_session(self, token, remote="127.0.0.1", proxy=None):
"""Validate a session token.
Validate a previously acquired session token against the
Crowd server. This may be a token provided by a user from
a http cookie or by some other means.
Args:
token: The session token.
remote: The remote address of the user.
proxy: Value of X-Forwarded-For server header
Returns:
dict:
A dict mapping of user attributes if the application
authentication was successful. See the Crowd
documentation for the authoritative list of attributes.
None: If authentication failed.
"""
params = {
"validationFactors": [
{"name": "remote_address", "value": remote, },
]
}
if proxy:
params["validation-factors"]["validationFactors"].append({"name": "X-Forwarded-For", "value": proxy, })
url = self.rest_url + "/session/%s" % token
response = self._post(url, data=json.dumps(params), params={"expand": "user"})
# For consistency between methods use None rather than False
# If token validation failed for any reason return None
if not response.ok:
return None
# Otherwise return the user object
return response.json()
def terminate_session(self, token):
"""Terminates the session token, effectively logging out the user
from all crowd-enabled services.
Args:
token: The session token.
Returns:
True: If session terminated
None: If session termination failed
"""
url = self.rest_url + "/session/%s" % token
response = self._delete(url)
# For consistency between methods use None rather than False
# If token validation failed for any reason return None
if not response.ok:
return None
# Otherwise return True
return True
def add_user(self, username, raise_on_error=False, **kwargs):
"""Add a user to the directory
Args:
username: The account username
raise_on_error: optional (default: False)
**kwargs: key-value pairs:
password: mandatory
email: mandatory
first_name: optional
last_name: optional
display_name: optional
active: optional (default True)
Returns:
True: Succeeded
False: If unsuccessful
"""
# Check that mandatory elements have been provided
if 'password' not in kwargs:
raise ValueError("missing password")
if 'email' not in kwargs:
raise ValueError("missing email")
# Populate data with default and mandatory values.
# A KeyError means a mandatory value was not provided,
# so raise a ValueError indicating bad args.
try:
data = {
"name": username,
"first-name": username,
"last-name": username,
"display-name": username,
"email": kwargs["email"],
"password": {"value": kwargs["password"]},
"active": True
}
except KeyError:
return ValueError
# Remove special case 'password'
del(kwargs["password"])
# Put values from kwargs into data
for k, v in kwargs.items():
new_k = k.replace("_", "-")
if new_k not in data:
raise ValueError("invalid argument %s" % k)
data[new_k] = v
response = self._post(self.rest_url + "/user",
data=json.dumps(data))
if response.status_code == 201:
return True
if raise_on_error:
raise RuntimeError(response.json()['message'])
return False
def get_user(self, username):
"""Retrieve information about a user
Returns:
dict: User information
None: If no user or failure occurred
"""
response = self._get(self.rest_url + "/user",
params={"username": username,
"expand": "attributes"})
if not response.ok:
return None
return response.json()
def set_active(self, username, active_state):
"""Set the active state of a user
Args:
username: The account username
active_state: True or False
Returns:
True: If successful
None: If no user or failure occurred
"""
if active_state not in (True, False):
raise ValueError("active_state must be True or False")
user = self.get_user(username)
if user is None:
return None
if user['active'] is active_state:
# Already in desired state
return True
user['active'] = active_state
response = self._put(self.rest_url + "/user",
params={"username": username},
data=json.dumps(user))
if response.status_code == 204:
return True
return None
def set_user_attribute(self, username, attribute, value, raise_on_error=False):
"""Set an attribute on a user
:param username: The username on which to set the attribute
:param attribute: The name of the attribute to set
:param value: The value of the attribute to set
:return: True on success, False on failure.
"""
data = {
'attributes': [
{
'name': attribute,
'values': [
value
]
},
]
}
response = self._post(self.rest_url + "/user/attribute",
params={"username": username,},
data=json.dumps(data))
if response.status_code == 204:
return True
if raise_on_error:
raise RuntimeError(response.json()['message'])
return False
def remove_user_from_group(self, username, groupname, raise_on_error=False):
"""Remove a user from a group
Attempts to remove a user from a group
Args
username: The username to remove from the group.
groupname: The group name to be removed from the user.
Returns:
True: Succeeded
False: If unsuccessful
"""
response = self._delete(self.rest_url + "/group/user/direct",params={"username": username, "groupname": groupname})
if response.status_code == 204:
return True
if raise_on_error:
raise RuntimeError(response.json()['message'])
return False
def change_password(self, username, newpassword, raise_on_error=False):
"""Change new password for a user
Args:
username: The account username.
newpassword: The account new password.
raise_on_error: optional (default: False)
Returns:
True: Succeeded
False: If unsuccessful
"""
response = self._put(self.rest_url + "/user/password",
data=json.dumps({"value": newpassword}),
params={"username": username})
if response.ok:
return True
if raise_on_error:
raise RuntimeError(response.json()['message'])
return False
def send_password_reset_link(self, username):
"""Sends the user a password reset link (by email)
Args:
username: The account username.
Returns:
True: Succeeded
False: If unsuccessful
"""
response = self._post(self.rest_url + "/user/mail/password",
params={"username": username})
if response.ok:
return True
return False
def get_groups(self, username):
"""Retrieves a list of group names that have <username> as a direct member.
Returns:
list:
A list of strings of group names.
"""
response = self._get(self.rest_url + "/user/group/direct",
params={"username": username})
if not response.ok:
return None
return [g['name'] for g in response.json()['groups']]
def get_nested_groups(self, username):
"""Retrieve a list of all group names that have <username> as a direct or indirect member.
Args:
username: The account username.
Returns:
list:
A list of strings of group names.
"""
response = self._get(self.rest_url + "/user/group/nested",
params={"username": username})
if not response.ok:
return None
return [g['name'] for g in response.json()['groups']]
def get_nested_group_users(self, groupname):
"""Retrieves a list of all users that directly or indirectly belong to the given groupname.
Args:
groupname: The group name.
Returns:
list:
A list of strings of user names.
"""
response = self._get(self.rest_url + "/group/user/nested",
params={"groupname": groupname,
"start-index": 0,
"max-results": 99999})
if not response.ok:
return None
return [u['name'] for u in response.json()['users']]
def user_exists(self, username):
"""Determines if the user exists.
Args:
username: The user name.
Returns:
bool:
True if the user exists in the Crowd application.
"""
response = self._get(self.rest_url + "/user",
params={"username": username})
if not response.ok:
return None
return True
def get_memberships(self):
"""Fetches all group memberships.
Returns:
dict:
key: group name
value: (array of users, array of groups)
"""
response = self._get_xml(self.rest_url + "/group/membership")
if not response.ok:
return None
xmltree = etree.fromstring(response.content)
memberships = {}
for mg in xmltree.findall('membership'):
# coerce values to unicode in a python 2 and 3 compatible way
group = u'{}'.format(mg.get('group'))
users = [u'{}'.format(u.get('name')) for u in mg.find('users').findall('user')]
groups = [u'{}'.format(g.get('name')) for g in mg.find('groups').findall('group')]
memberships[group] = {u'users': users, u'groups': groups}
return memberships
def search(self, entity_type, property_name, search_string, start_index=0, max_results=99999):
"""Performs a user search using the Crowd search API.
https://developer.atlassian.com/display/CROWDDEV/Crowd+REST+Resources#CrowdRESTResources-SearchResource
Args:
entity_type: 'user' or 'group'
property_name: eg. 'email', 'name'
search_string: the string to search for.
start_index: starting index of the results (default: 0)
max_results: maximum number of results returned (default: 99999)
Returns:
json results:
Returns search results.
"""
params = {
"entity-type": entity_type,
"expand": entity_type,
"property-search-restriction": {
"property": {"name": property_name, "type": "STRING"},
"match-mode": "CONTAINS",
"value": search_string,
}
}
params = {
'entity-type': entity_type,
'expand': entity_type,
'start-index': start_index,
'max-results': max_results
}
# Construct XML payload of the form:
# <property-search-restriction>
# <property>
# <name>email</name>
# <type>STRING</type>
# </property>
# <match-mode>EXACTLY_MATCHES</match-mode>
# <value>bob@example.net</value>
# </property-search-restriction>
root = etree.Element('property-search-restriction')
property_ = etree.Element('property')
prop_name = etree.Element('name')
prop_name.text = property_name
property_.append(prop_name)
prop_type = etree.Element('type')
prop_type.text = 'STRING'
property_.append(prop_type)
root.append(property_)
match_mode = etree.Element('match-mode')
match_mode.text = 'CONTAINS'
root.append(match_mode)
value = etree.Element('value')
value.text = search_string
root.append(value)
# Construct the XML payload expected by search API
payload = '<?xml version="1.0" encoding="UTF-8"?>\n' + etree.tostring(root).decode('utf-8')
# We're sending XML but would like a JSON response
session = self._build_session(content_type='xml')
session.headers.update({'Accept': 'application/json'})
response = session.post(self.rest_url + "/search", params=params, data=payload, timeout=self.timeout)
if not response.ok:
return None
return response.json()
|
pycontribs/python-crowd | crowd.py | CrowdServer.remove_user_from_group | python | def remove_user_from_group(self, username, groupname, raise_on_error=False):
response = self._delete(self.rest_url + "/group/user/direct",params={"username": username, "groupname": groupname})
if response.status_code == 204:
return True
if raise_on_error:
raise RuntimeError(response.json()['message'])
return False | Remove a user from a group
Attempts to remove a user from a group
Args
username: The username to remove from the group.
groupname: The group name to be removed from the user.
Returns:
True: Succeeded
False: If unsuccessful | train | https://github.com/pycontribs/python-crowd/blob/a075e45774dd5baecf0217843cda747084268e32/crowd.py#L483-L505 | [
"def _delete(self, *args, **kwargs):\n \"\"\"Wrapper around Requests for DELETE requests\n\n Returns:\n Response:\n A Requests Response object\n \"\"\"\n\n if 'timeout' not in kwargs:\n kwargs['timeout'] = self.timeout\n\n req = self.session.delete(*args, **kwargs)\n retur... | class CrowdServer(object):
"""Crowd server authentication object.
This is a Crowd authentication class to be configured for a
particular application (app_name) to authenticate users
against a Crowd server (crowd_url).
This module uses the Crowd JSON API for talking to Crowd.
An application account must be configured in the Crowd server
and permitted to authenticate users against one or more user
directories prior to using this module.
Please see the Crowd documentation for information about
configuring additional applications to talk to Crowd.
The ``ssl_verify`` parameter controls how and if certificates are verified.
If ``True``, the SSL certificate will be verified.
A CA_BUNDLE path can also be provided.
The ``client_cert`` tuple (cert,key) specifies a SSL client certificate and key files.
"""
def __init__(self, crowd_url, app_name, app_pass, ssl_verify=True,
timeout=None, client_cert=None):
self.crowd_url = crowd_url
self.app_name = app_name
self.app_pass = app_pass
self.rest_url = crowd_url.rstrip("/") + "/rest/usermanagement/1"
self.ssl_verify = ssl_verify
self.client_cert = client_cert
self.timeout = timeout
self.session = self._build_session(content_type='json')
self.session_xml = self._build_session(content_type='xml')
def __str__(self):
return "Crowd Server at %s" % self.crowd_url
def __repr__(self):
return "<CrowdServer('%s', '%s', '%s')>" % \
(self.crowd_url, self.app_name, self.app_pass)
def _build_session(self, content_type='json'):
headers = {
'Content-Type': 'application/{}'.format(content_type),
'Accept': 'application/{}'.format(content_type),
}
session = requests.Session()
session.verify = self.ssl_verify
session.cert = self.client_cert
session.auth = requests.auth.HTTPBasicAuth(self.app_name, self.app_pass)
session.headers.update(headers)
return session
def _get(self, *args, **kwargs):
"""Wrapper around Requests for GET requests
Returns:
Response:
A Requests Response object
"""
if 'timeout' not in kwargs:
kwargs['timeout'] = self.timeout
req = self.session.get(*args, **kwargs)
return req
def _get_xml(self, *args, **kwargs):
"""Wrapper around Requests for GET XML requests
Returns:
Response:
A Requests Response object
"""
req = self.session_xml.get(*args, **kwargs)
return req
def _post(self, *args, **kwargs):
"""Wrapper around Requests for POST requests
Returns:
Response:
A Requests Response object
"""
if 'timeout' not in kwargs:
kwargs['timeout'] = self.timeout
req = self.session.post(*args, **kwargs)
return req
def _post_xml(self, *args, **kwargs):
"""Wrapper around Requests for POST requests
Returns:
Response:
A Requests Response object
"""
if 'timeout' not in kwargs:
kwargs['timeout'] = self.timeout
req = self.session_xml.post(*args, **kwargs)
return req
def _put(self, *args, **kwargs):
"""Wrapper around Requests for PUT requests
Returns:
Response:
A Requests Response object
"""
if 'timeout' not in kwargs:
kwargs['timeout'] = self.timeout
req = self.session.put(*args, **kwargs)
return req
def _delete(self, *args, **kwargs):
"""Wrapper around Requests for DELETE requests
Returns:
Response:
A Requests Response object
"""
if 'timeout' not in kwargs:
kwargs['timeout'] = self.timeout
req = self.session.delete(*args, **kwargs)
return req
def auth_ping(self):
"""Test that application can authenticate to Crowd.
Attempts to authenticate the application user against
the Crowd server. In order for user authentication to
work, an application must be able to authenticate.
Returns:
bool:
True if the application authentication succeeded.
"""
url = self.rest_url + "/non-existent/location"
response = self._get(url)
if response.status_code == 401:
return False
elif response.status_code == 404:
return True
else:
# An error encountered - problem with the Crowd server?
return False
def auth_user(self, username, password):
"""Authenticate a user account against the Crowd server.
Attempts to authenticate the user against the Crowd server.
Args:
username: The account username.
password: The account password.
Returns:
dict:
A dict mapping of user attributes if the application
authentication was successful. See the Crowd documentation
for the authoritative list of attributes.
None: If authentication failed.
"""
response = self._post(self.rest_url + "/authentication",
data=json.dumps({"value": password}),
params={"username": username})
# If authentication failed for any reason return None
if not response.ok:
return None
# ...otherwise return a dictionary of user attributes
return response.json()
def get_session(self, username, password, remote="127.0.0.1", proxy=None):
"""Create a session for a user.
Attempts to create a user session on the Crowd server.
Args:
username: The account username.
password: The account password.
remote:
The remote address of the user. This can be used
to create multiple concurrent sessions for a user.
The host you run this program on may need to be configured
in Crowd as a trusted proxy for this to work.
proxy: Value of X-Forwarded-For server header.
Returns:
dict:
A dict mapping of user attributes if the application
authentication was successful. See the Crowd
documentation for the authoritative list of attributes.
None: If authentication failed.
"""
params = {
"username": username,
"password": password,
"validation-factors": {
"validationFactors": [
{"name": "remote_address", "value": remote, },
]
}
}
if proxy:
params["validation-factors"]["validationFactors"].append({"name": "X-Forwarded-For", "value": proxy, })
response = self._post(self.rest_url + "/session",
data=json.dumps(params),
params={"expand": "user"})
# If authentication failed for any reason return None
if not response.ok:
return None
# Otherwise return the user object
return response.json()
def validate_session(self, token, remote="127.0.0.1", proxy=None):
"""Validate a session token.
Validate a previously acquired session token against the
Crowd server. This may be a token provided by a user from
a http cookie or by some other means.
Args:
token: The session token.
remote: The remote address of the user.
proxy: Value of X-Forwarded-For server header
Returns:
dict:
A dict mapping of user attributes if the application
authentication was successful. See the Crowd
documentation for the authoritative list of attributes.
None: If authentication failed.
"""
params = {
"validationFactors": [
{"name": "remote_address", "value": remote, },
]
}
if proxy:
params["validation-factors"]["validationFactors"].append({"name": "X-Forwarded-For", "value": proxy, })
url = self.rest_url + "/session/%s" % token
response = self._post(url, data=json.dumps(params), params={"expand": "user"})
# For consistency between methods use None rather than False
# If token validation failed for any reason return None
if not response.ok:
return None
# Otherwise return the user object
return response.json()
def terminate_session(self, token):
"""Terminates the session token, effectively logging out the user
from all crowd-enabled services.
Args:
token: The session token.
Returns:
True: If session terminated
None: If session termination failed
"""
url = self.rest_url + "/session/%s" % token
response = self._delete(url)
# For consistency between methods use None rather than False
# If token validation failed for any reason return None
if not response.ok:
return None
# Otherwise return True
return True
def add_user(self, username, raise_on_error=False, **kwargs):
"""Add a user to the directory
Args:
username: The account username
raise_on_error: optional (default: False)
**kwargs: key-value pairs:
password: mandatory
email: mandatory
first_name: optional
last_name: optional
display_name: optional
active: optional (default True)
Returns:
True: Succeeded
False: If unsuccessful
"""
# Check that mandatory elements have been provided
if 'password' not in kwargs:
raise ValueError("missing password")
if 'email' not in kwargs:
raise ValueError("missing email")
# Populate data with default and mandatory values.
# A KeyError means a mandatory value was not provided,
# so raise a ValueError indicating bad args.
try:
data = {
"name": username,
"first-name": username,
"last-name": username,
"display-name": username,
"email": kwargs["email"],
"password": {"value": kwargs["password"]},
"active": True
}
except KeyError:
return ValueError
# Remove special case 'password'
del(kwargs["password"])
# Put values from kwargs into data
for k, v in kwargs.items():
new_k = k.replace("_", "-")
if new_k not in data:
raise ValueError("invalid argument %s" % k)
data[new_k] = v
response = self._post(self.rest_url + "/user",
data=json.dumps(data))
if response.status_code == 201:
return True
if raise_on_error:
raise RuntimeError(response.json()['message'])
return False
def get_user(self, username):
"""Retrieve information about a user
Returns:
dict: User information
None: If no user or failure occurred
"""
response = self._get(self.rest_url + "/user",
params={"username": username,
"expand": "attributes"})
if not response.ok:
return None
return response.json()
def set_active(self, username, active_state):
"""Set the active state of a user
Args:
username: The account username
active_state: True or False
Returns:
True: If successful
None: If no user or failure occurred
"""
if active_state not in (True, False):
raise ValueError("active_state must be True or False")
user = self.get_user(username)
if user is None:
return None
if user['active'] is active_state:
# Already in desired state
return True
user['active'] = active_state
response = self._put(self.rest_url + "/user",
params={"username": username},
data=json.dumps(user))
if response.status_code == 204:
return True
return None
def set_user_attribute(self, username, attribute, value, raise_on_error=False):
"""Set an attribute on a user
:param username: The username on which to set the attribute
:param attribute: The name of the attribute to set
:param value: The value of the attribute to set
:return: True on success, False on failure.
"""
data = {
'attributes': [
{
'name': attribute,
'values': [
value
]
},
]
}
response = self._post(self.rest_url + "/user/attribute",
params={"username": username,},
data=json.dumps(data))
if response.status_code == 204:
return True
if raise_on_error:
raise RuntimeError(response.json()['message'])
return False
def add_user_to_group(self, username, groupname, raise_on_error=False):
"""Add a user to a group
:param username: The username to assign to the group
:param groupname: The group name into which to assign the user
:return: True on success, False on failure.
"""
data = {
'name': groupname,
}
response = self._post(self.rest_url + "/user/group/direct",
params={"username": username,},
data=json.dumps(data))
if response.status_code == 201:
return True
if raise_on_error:
raise RuntimeError(response.json()['message'])
return False
def change_password(self, username, newpassword, raise_on_error=False):
"""Change new password for a user
Args:
username: The account username.
newpassword: The account new password.
raise_on_error: optional (default: False)
Returns:
True: Succeeded
False: If unsuccessful
"""
response = self._put(self.rest_url + "/user/password",
data=json.dumps({"value": newpassword}),
params={"username": username})
if response.ok:
return True
if raise_on_error:
raise RuntimeError(response.json()['message'])
return False
def send_password_reset_link(self, username):
"""Sends the user a password reset link (by email)
Args:
username: The account username.
Returns:
True: Succeeded
False: If unsuccessful
"""
response = self._post(self.rest_url + "/user/mail/password",
params={"username": username})
if response.ok:
return True
return False
def get_groups(self, username):
"""Retrieves a list of group names that have <username> as a direct member.
Returns:
list:
A list of strings of group names.
"""
response = self._get(self.rest_url + "/user/group/direct",
params={"username": username})
if not response.ok:
return None
return [g['name'] for g in response.json()['groups']]
def get_nested_groups(self, username):
"""Retrieve a list of all group names that have <username> as a direct or indirect member.
Args:
username: The account username.
Returns:
list:
A list of strings of group names.
"""
response = self._get(self.rest_url + "/user/group/nested",
params={"username": username})
if not response.ok:
return None
return [g['name'] for g in response.json()['groups']]
def get_nested_group_users(self, groupname):
"""Retrieves a list of all users that directly or indirectly belong to the given groupname.
Args:
groupname: The group name.
Returns:
list:
A list of strings of user names.
"""
response = self._get(self.rest_url + "/group/user/nested",
params={"groupname": groupname,
"start-index": 0,
"max-results": 99999})
if not response.ok:
return None
return [u['name'] for u in response.json()['users']]
def user_exists(self, username):
"""Determines if the user exists.
Args:
username: The user name.
Returns:
bool:
True if the user exists in the Crowd application.
"""
response = self._get(self.rest_url + "/user",
params={"username": username})
if not response.ok:
return None
return True
def get_memberships(self):
"""Fetches all group memberships.
Returns:
dict:
key: group name
value: (array of users, array of groups)
"""
response = self._get_xml(self.rest_url + "/group/membership")
if not response.ok:
return None
xmltree = etree.fromstring(response.content)
memberships = {}
for mg in xmltree.findall('membership'):
# coerce values to unicode in a python 2 and 3 compatible way
group = u'{}'.format(mg.get('group'))
users = [u'{}'.format(u.get('name')) for u in mg.find('users').findall('user')]
groups = [u'{}'.format(g.get('name')) for g in mg.find('groups').findall('group')]
memberships[group] = {u'users': users, u'groups': groups}
return memberships
def search(self, entity_type, property_name, search_string, start_index=0, max_results=99999):
"""Performs a user search using the Crowd search API.
https://developer.atlassian.com/display/CROWDDEV/Crowd+REST+Resources#CrowdRESTResources-SearchResource
Args:
entity_type: 'user' or 'group'
property_name: eg. 'email', 'name'
search_string: the string to search for.
start_index: starting index of the results (default: 0)
max_results: maximum number of results returned (default: 99999)
Returns:
json results:
Returns search results.
"""
params = {
"entity-type": entity_type,
"expand": entity_type,
"property-search-restriction": {
"property": {"name": property_name, "type": "STRING"},
"match-mode": "CONTAINS",
"value": search_string,
}
}
params = {
'entity-type': entity_type,
'expand': entity_type,
'start-index': start_index,
'max-results': max_results
}
# Construct XML payload of the form:
# <property-search-restriction>
# <property>
# <name>email</name>
# <type>STRING</type>
# </property>
# <match-mode>EXACTLY_MATCHES</match-mode>
# <value>bob@example.net</value>
# </property-search-restriction>
root = etree.Element('property-search-restriction')
property_ = etree.Element('property')
prop_name = etree.Element('name')
prop_name.text = property_name
property_.append(prop_name)
prop_type = etree.Element('type')
prop_type.text = 'STRING'
property_.append(prop_type)
root.append(property_)
match_mode = etree.Element('match-mode')
match_mode.text = 'CONTAINS'
root.append(match_mode)
value = etree.Element('value')
value.text = search_string
root.append(value)
# Construct the XML payload expected by search API
payload = '<?xml version="1.0" encoding="UTF-8"?>\n' + etree.tostring(root).decode('utf-8')
# We're sending XML but would like a JSON response
session = self._build_session(content_type='xml')
session.headers.update({'Accept': 'application/json'})
response = session.post(self.rest_url + "/search", params=params, data=payload, timeout=self.timeout)
if not response.ok:
return None
return response.json()
|
pycontribs/python-crowd | crowd.py | CrowdServer.change_password | python | def change_password(self, username, newpassword, raise_on_error=False):
response = self._put(self.rest_url + "/user/password",
data=json.dumps({"value": newpassword}),
params={"username": username})
if response.ok:
return True
if raise_on_error:
raise RuntimeError(response.json()['message'])
return False | Change new password for a user
Args:
username: The account username.
newpassword: The account new password.
raise_on_error: optional (default: False)
Returns:
True: Succeeded
False: If unsuccessful | train | https://github.com/pycontribs/python-crowd/blob/a075e45774dd5baecf0217843cda747084268e32/crowd.py#L507-L532 | [
"def _put(self, *args, **kwargs):\n \"\"\"Wrapper around Requests for PUT requests\n\n Returns:\n Response:\n A Requests Response object\n \"\"\"\n\n if 'timeout' not in kwargs:\n kwargs['timeout'] = self.timeout\n\n req = self.session.put(*args, **kwargs)\n return req\n"
... | class CrowdServer(object):
"""Crowd server authentication object.
This is a Crowd authentication class to be configured for a
particular application (app_name) to authenticate users
against a Crowd server (crowd_url).
This module uses the Crowd JSON API for talking to Crowd.
An application account must be configured in the Crowd server
and permitted to authenticate users against one or more user
directories prior to using this module.
Please see the Crowd documentation for information about
configuring additional applications to talk to Crowd.
The ``ssl_verify`` parameter controls how and if certificates are verified.
If ``True``, the SSL certificate will be verified.
A CA_BUNDLE path can also be provided.
The ``client_cert`` tuple (cert,key) specifies a SSL client certificate and key files.
"""
def __init__(self, crowd_url, app_name, app_pass, ssl_verify=True,
timeout=None, client_cert=None):
self.crowd_url = crowd_url
self.app_name = app_name
self.app_pass = app_pass
self.rest_url = crowd_url.rstrip("/") + "/rest/usermanagement/1"
self.ssl_verify = ssl_verify
self.client_cert = client_cert
self.timeout = timeout
self.session = self._build_session(content_type='json')
self.session_xml = self._build_session(content_type='xml')
def __str__(self):
return "Crowd Server at %s" % self.crowd_url
def __repr__(self):
return "<CrowdServer('%s', '%s', '%s')>" % \
(self.crowd_url, self.app_name, self.app_pass)
def _build_session(self, content_type='json'):
headers = {
'Content-Type': 'application/{}'.format(content_type),
'Accept': 'application/{}'.format(content_type),
}
session = requests.Session()
session.verify = self.ssl_verify
session.cert = self.client_cert
session.auth = requests.auth.HTTPBasicAuth(self.app_name, self.app_pass)
session.headers.update(headers)
return session
def _get(self, *args, **kwargs):
"""Wrapper around Requests for GET requests
Returns:
Response:
A Requests Response object
"""
if 'timeout' not in kwargs:
kwargs['timeout'] = self.timeout
req = self.session.get(*args, **kwargs)
return req
def _get_xml(self, *args, **kwargs):
"""Wrapper around Requests for GET XML requests
Returns:
Response:
A Requests Response object
"""
req = self.session_xml.get(*args, **kwargs)
return req
def _post(self, *args, **kwargs):
"""Wrapper around Requests for POST requests
Returns:
Response:
A Requests Response object
"""
if 'timeout' not in kwargs:
kwargs['timeout'] = self.timeout
req = self.session.post(*args, **kwargs)
return req
def _post_xml(self, *args, **kwargs):
"""Wrapper around Requests for POST requests
Returns:
Response:
A Requests Response object
"""
if 'timeout' not in kwargs:
kwargs['timeout'] = self.timeout
req = self.session_xml.post(*args, **kwargs)
return req
def _put(self, *args, **kwargs):
"""Wrapper around Requests for PUT requests
Returns:
Response:
A Requests Response object
"""
if 'timeout' not in kwargs:
kwargs['timeout'] = self.timeout
req = self.session.put(*args, **kwargs)
return req
def _delete(self, *args, **kwargs):
"""Wrapper around Requests for DELETE requests
Returns:
Response:
A Requests Response object
"""
if 'timeout' not in kwargs:
kwargs['timeout'] = self.timeout
req = self.session.delete(*args, **kwargs)
return req
def auth_ping(self):
"""Test that application can authenticate to Crowd.
Attempts to authenticate the application user against
the Crowd server. In order for user authentication to
work, an application must be able to authenticate.
Returns:
bool:
True if the application authentication succeeded.
"""
url = self.rest_url + "/non-existent/location"
response = self._get(url)
if response.status_code == 401:
return False
elif response.status_code == 404:
return True
else:
# An error encountered - problem with the Crowd server?
return False
def auth_user(self, username, password):
"""Authenticate a user account against the Crowd server.
Attempts to authenticate the user against the Crowd server.
Args:
username: The account username.
password: The account password.
Returns:
dict:
A dict mapping of user attributes if the application
authentication was successful. See the Crowd documentation
for the authoritative list of attributes.
None: If authentication failed.
"""
response = self._post(self.rest_url + "/authentication",
data=json.dumps({"value": password}),
params={"username": username})
# If authentication failed for any reason return None
if not response.ok:
return None
# ...otherwise return a dictionary of user attributes
return response.json()
def get_session(self, username, password, remote="127.0.0.1", proxy=None):
"""Create a session for a user.
Attempts to create a user session on the Crowd server.
Args:
username: The account username.
password: The account password.
remote:
The remote address of the user. This can be used
to create multiple concurrent sessions for a user.
The host you run this program on may need to be configured
in Crowd as a trusted proxy for this to work.
proxy: Value of X-Forwarded-For server header.
Returns:
dict:
A dict mapping of user attributes if the application
authentication was successful. See the Crowd
documentation for the authoritative list of attributes.
None: If authentication failed.
"""
params = {
"username": username,
"password": password,
"validation-factors": {
"validationFactors": [
{"name": "remote_address", "value": remote, },
]
}
}
if proxy:
params["validation-factors"]["validationFactors"].append({"name": "X-Forwarded-For", "value": proxy, })
response = self._post(self.rest_url + "/session",
data=json.dumps(params),
params={"expand": "user"})
# If authentication failed for any reason return None
if not response.ok:
return None
# Otherwise return the user object
return response.json()
def validate_session(self, token, remote="127.0.0.1", proxy=None):
"""Validate a session token.
Validate a previously acquired session token against the
Crowd server. This may be a token provided by a user from
a http cookie or by some other means.
Args:
token: The session token.
remote: The remote address of the user.
proxy: Value of X-Forwarded-For server header
Returns:
dict:
A dict mapping of user attributes if the application
authentication was successful. See the Crowd
documentation for the authoritative list of attributes.
None: If authentication failed.
"""
params = {
"validationFactors": [
{"name": "remote_address", "value": remote, },
]
}
if proxy:
params["validation-factors"]["validationFactors"].append({"name": "X-Forwarded-For", "value": proxy, })
url = self.rest_url + "/session/%s" % token
response = self._post(url, data=json.dumps(params), params={"expand": "user"})
# For consistency between methods use None rather than False
# If token validation failed for any reason return None
if not response.ok:
return None
# Otherwise return the user object
return response.json()
def terminate_session(self, token):
"""Terminates the session token, effectively logging out the user
from all crowd-enabled services.
Args:
token: The session token.
Returns:
True: If session terminated
None: If session termination failed
"""
url = self.rest_url + "/session/%s" % token
response = self._delete(url)
# For consistency between methods use None rather than False
# If token validation failed for any reason return None
if not response.ok:
return None
# Otherwise return True
return True
def add_user(self, username, raise_on_error=False, **kwargs):
"""Add a user to the directory
Args:
username: The account username
raise_on_error: optional (default: False)
**kwargs: key-value pairs:
password: mandatory
email: mandatory
first_name: optional
last_name: optional
display_name: optional
active: optional (default True)
Returns:
True: Succeeded
False: If unsuccessful
"""
# Check that mandatory elements have been provided
if 'password' not in kwargs:
raise ValueError("missing password")
if 'email' not in kwargs:
raise ValueError("missing email")
# Populate data with default and mandatory values.
# A KeyError means a mandatory value was not provided,
# so raise a ValueError indicating bad args.
try:
data = {
"name": username,
"first-name": username,
"last-name": username,
"display-name": username,
"email": kwargs["email"],
"password": {"value": kwargs["password"]},
"active": True
}
except KeyError:
return ValueError
# Remove special case 'password'
del(kwargs["password"])
# Put values from kwargs into data
for k, v in kwargs.items():
new_k = k.replace("_", "-")
if new_k not in data:
raise ValueError("invalid argument %s" % k)
data[new_k] = v
response = self._post(self.rest_url + "/user",
data=json.dumps(data))
if response.status_code == 201:
return True
if raise_on_error:
raise RuntimeError(response.json()['message'])
return False
def get_user(self, username):
"""Retrieve information about a user
Returns:
dict: User information
None: If no user or failure occurred
"""
response = self._get(self.rest_url + "/user",
params={"username": username,
"expand": "attributes"})
if not response.ok:
return None
return response.json()
def set_active(self, username, active_state):
"""Set the active state of a user
Args:
username: The account username
active_state: True or False
Returns:
True: If successful
None: If no user or failure occurred
"""
if active_state not in (True, False):
raise ValueError("active_state must be True or False")
user = self.get_user(username)
if user is None:
return None
if user['active'] is active_state:
# Already in desired state
return True
user['active'] = active_state
response = self._put(self.rest_url + "/user",
params={"username": username},
data=json.dumps(user))
if response.status_code == 204:
return True
return None
def set_user_attribute(self, username, attribute, value, raise_on_error=False):
"""Set an attribute on a user
:param username: The username on which to set the attribute
:param attribute: The name of the attribute to set
:param value: The value of the attribute to set
:return: True on success, False on failure.
"""
data = {
'attributes': [
{
'name': attribute,
'values': [
value
]
},
]
}
response = self._post(self.rest_url + "/user/attribute",
params={"username": username,},
data=json.dumps(data))
if response.status_code == 204:
return True
if raise_on_error:
raise RuntimeError(response.json()['message'])
return False
def add_user_to_group(self, username, groupname, raise_on_error=False):
"""Add a user to a group
:param username: The username to assign to the group
:param groupname: The group name into which to assign the user
:return: True on success, False on failure.
"""
data = {
'name': groupname,
}
response = self._post(self.rest_url + "/user/group/direct",
params={"username": username,},
data=json.dumps(data))
if response.status_code == 201:
return True
if raise_on_error:
raise RuntimeError(response.json()['message'])
return False
def remove_user_from_group(self, username, groupname, raise_on_error=False):
"""Remove a user from a group
Attempts to remove a user from a group
Args
username: The username to remove from the group.
groupname: The group name to be removed from the user.
Returns:
True: Succeeded
False: If unsuccessful
"""
response = self._delete(self.rest_url + "/group/user/direct",params={"username": username, "groupname": groupname})
if response.status_code == 204:
return True
if raise_on_error:
raise RuntimeError(response.json()['message'])
return False
def send_password_reset_link(self, username):
"""Sends the user a password reset link (by email)
Args:
username: The account username.
Returns:
True: Succeeded
False: If unsuccessful
"""
response = self._post(self.rest_url + "/user/mail/password",
params={"username": username})
if response.ok:
return True
return False
def get_groups(self, username):
"""Retrieves a list of group names that have <username> as a direct member.
Returns:
list:
A list of strings of group names.
"""
response = self._get(self.rest_url + "/user/group/direct",
params={"username": username})
if not response.ok:
return None
return [g['name'] for g in response.json()['groups']]
def get_nested_groups(self, username):
"""Retrieve a list of all group names that have <username> as a direct or indirect member.
Args:
username: The account username.
Returns:
list:
A list of strings of group names.
"""
response = self._get(self.rest_url + "/user/group/nested",
params={"username": username})
if not response.ok:
return None
return [g['name'] for g in response.json()['groups']]
def get_nested_group_users(self, groupname):
"""Retrieves a list of all users that directly or indirectly belong to the given groupname.
Args:
groupname: The group name.
Returns:
list:
A list of strings of user names.
"""
response = self._get(self.rest_url + "/group/user/nested",
params={"groupname": groupname,
"start-index": 0,
"max-results": 99999})
if not response.ok:
return None
return [u['name'] for u in response.json()['users']]
def user_exists(self, username):
"""Determines if the user exists.
Args:
username: The user name.
Returns:
bool:
True if the user exists in the Crowd application.
"""
response = self._get(self.rest_url + "/user",
params={"username": username})
if not response.ok:
return None
return True
def get_memberships(self):
"""Fetches all group memberships.
Returns:
dict:
key: group name
value: (array of users, array of groups)
"""
response = self._get_xml(self.rest_url + "/group/membership")
if not response.ok:
return None
xmltree = etree.fromstring(response.content)
memberships = {}
for mg in xmltree.findall('membership'):
# coerce values to unicode in a python 2 and 3 compatible way
group = u'{}'.format(mg.get('group'))
users = [u'{}'.format(u.get('name')) for u in mg.find('users').findall('user')]
groups = [u'{}'.format(g.get('name')) for g in mg.find('groups').findall('group')]
memberships[group] = {u'users': users, u'groups': groups}
return memberships
def search(self, entity_type, property_name, search_string, start_index=0, max_results=99999):
"""Performs a user search using the Crowd search API.
https://developer.atlassian.com/display/CROWDDEV/Crowd+REST+Resources#CrowdRESTResources-SearchResource
Args:
entity_type: 'user' or 'group'
property_name: eg. 'email', 'name'
search_string: the string to search for.
start_index: starting index of the results (default: 0)
max_results: maximum number of results returned (default: 99999)
Returns:
json results:
Returns search results.
"""
params = {
"entity-type": entity_type,
"expand": entity_type,
"property-search-restriction": {
"property": {"name": property_name, "type": "STRING"},
"match-mode": "CONTAINS",
"value": search_string,
}
}
params = {
'entity-type': entity_type,
'expand': entity_type,
'start-index': start_index,
'max-results': max_results
}
# Construct XML payload of the form:
# <property-search-restriction>
# <property>
# <name>email</name>
# <type>STRING</type>
# </property>
# <match-mode>EXACTLY_MATCHES</match-mode>
# <value>bob@example.net</value>
# </property-search-restriction>
root = etree.Element('property-search-restriction')
property_ = etree.Element('property')
prop_name = etree.Element('name')
prop_name.text = property_name
property_.append(prop_name)
prop_type = etree.Element('type')
prop_type.text = 'STRING'
property_.append(prop_type)
root.append(property_)
match_mode = etree.Element('match-mode')
match_mode.text = 'CONTAINS'
root.append(match_mode)
value = etree.Element('value')
value.text = search_string
root.append(value)
# Construct the XML payload expected by search API
payload = '<?xml version="1.0" encoding="UTF-8"?>\n' + etree.tostring(root).decode('utf-8')
# We're sending XML but would like a JSON response
session = self._build_session(content_type='xml')
session.headers.update({'Accept': 'application/json'})
response = session.post(self.rest_url + "/search", params=params, data=payload, timeout=self.timeout)
if not response.ok:
return None
return response.json()
|
pycontribs/python-crowd | crowd.py | CrowdServer.send_password_reset_link | python | def send_password_reset_link(self, username):
response = self._post(self.rest_url + "/user/mail/password",
params={"username": username})
if response.ok:
return True
return False | Sends the user a password reset link (by email)
Args:
username: The account username.
Returns:
True: Succeeded
False: If unsuccessful | train | https://github.com/pycontribs/python-crowd/blob/a075e45774dd5baecf0217843cda747084268e32/crowd.py#L534-L551 | [
"def _post(self, *args, **kwargs):\n \"\"\"Wrapper around Requests for POST requests\n\n Returns:\n Response:\n A Requests Response object\n \"\"\"\n\n if 'timeout' not in kwargs:\n kwargs['timeout'] = self.timeout\n\n req = self.session.post(*args, **kwargs)\n return req\... | class CrowdServer(object):
"""Crowd server authentication object.
This is a Crowd authentication class to be configured for a
particular application (app_name) to authenticate users
against a Crowd server (crowd_url).
This module uses the Crowd JSON API for talking to Crowd.
An application account must be configured in the Crowd server
and permitted to authenticate users against one or more user
directories prior to using this module.
Please see the Crowd documentation for information about
configuring additional applications to talk to Crowd.
The ``ssl_verify`` parameter controls how and if certificates are verified.
If ``True``, the SSL certificate will be verified.
A CA_BUNDLE path can also be provided.
The ``client_cert`` tuple (cert,key) specifies a SSL client certificate and key files.
"""
def __init__(self, crowd_url, app_name, app_pass, ssl_verify=True,
timeout=None, client_cert=None):
self.crowd_url = crowd_url
self.app_name = app_name
self.app_pass = app_pass
self.rest_url = crowd_url.rstrip("/") + "/rest/usermanagement/1"
self.ssl_verify = ssl_verify
self.client_cert = client_cert
self.timeout = timeout
self.session = self._build_session(content_type='json')
self.session_xml = self._build_session(content_type='xml')
def __str__(self):
return "Crowd Server at %s" % self.crowd_url
def __repr__(self):
return "<CrowdServer('%s', '%s', '%s')>" % \
(self.crowd_url, self.app_name, self.app_pass)
def _build_session(self, content_type='json'):
headers = {
'Content-Type': 'application/{}'.format(content_type),
'Accept': 'application/{}'.format(content_type),
}
session = requests.Session()
session.verify = self.ssl_verify
session.cert = self.client_cert
session.auth = requests.auth.HTTPBasicAuth(self.app_name, self.app_pass)
session.headers.update(headers)
return session
def _get(self, *args, **kwargs):
"""Wrapper around Requests for GET requests
Returns:
Response:
A Requests Response object
"""
if 'timeout' not in kwargs:
kwargs['timeout'] = self.timeout
req = self.session.get(*args, **kwargs)
return req
def _get_xml(self, *args, **kwargs):
"""Wrapper around Requests for GET XML requests
Returns:
Response:
A Requests Response object
"""
req = self.session_xml.get(*args, **kwargs)
return req
def _post(self, *args, **kwargs):
"""Wrapper around Requests for POST requests
Returns:
Response:
A Requests Response object
"""
if 'timeout' not in kwargs:
kwargs['timeout'] = self.timeout
req = self.session.post(*args, **kwargs)
return req
def _post_xml(self, *args, **kwargs):
"""Wrapper around Requests for POST requests
Returns:
Response:
A Requests Response object
"""
if 'timeout' not in kwargs:
kwargs['timeout'] = self.timeout
req = self.session_xml.post(*args, **kwargs)
return req
def _put(self, *args, **kwargs):
"""Wrapper around Requests for PUT requests
Returns:
Response:
A Requests Response object
"""
if 'timeout' not in kwargs:
kwargs['timeout'] = self.timeout
req = self.session.put(*args, **kwargs)
return req
def _delete(self, *args, **kwargs):
"""Wrapper around Requests for DELETE requests
Returns:
Response:
A Requests Response object
"""
if 'timeout' not in kwargs:
kwargs['timeout'] = self.timeout
req = self.session.delete(*args, **kwargs)
return req
def auth_ping(self):
"""Test that application can authenticate to Crowd.
Attempts to authenticate the application user against
the Crowd server. In order for user authentication to
work, an application must be able to authenticate.
Returns:
bool:
True if the application authentication succeeded.
"""
url = self.rest_url + "/non-existent/location"
response = self._get(url)
if response.status_code == 401:
return False
elif response.status_code == 404:
return True
else:
# An error encountered - problem with the Crowd server?
return False
def auth_user(self, username, password):
"""Authenticate a user account against the Crowd server.
Attempts to authenticate the user against the Crowd server.
Args:
username: The account username.
password: The account password.
Returns:
dict:
A dict mapping of user attributes if the application
authentication was successful. See the Crowd documentation
for the authoritative list of attributes.
None: If authentication failed.
"""
response = self._post(self.rest_url + "/authentication",
data=json.dumps({"value": password}),
params={"username": username})
# If authentication failed for any reason return None
if not response.ok:
return None
# ...otherwise return a dictionary of user attributes
return response.json()
def get_session(self, username, password, remote="127.0.0.1", proxy=None):
"""Create a session for a user.
Attempts to create a user session on the Crowd server.
Args:
username: The account username.
password: The account password.
remote:
The remote address of the user. This can be used
to create multiple concurrent sessions for a user.
The host you run this program on may need to be configured
in Crowd as a trusted proxy for this to work.
proxy: Value of X-Forwarded-For server header.
Returns:
dict:
A dict mapping of user attributes if the application
authentication was successful. See the Crowd
documentation for the authoritative list of attributes.
None: If authentication failed.
"""
params = {
"username": username,
"password": password,
"validation-factors": {
"validationFactors": [
{"name": "remote_address", "value": remote, },
]
}
}
if proxy:
params["validation-factors"]["validationFactors"].append({"name": "X-Forwarded-For", "value": proxy, })
response = self._post(self.rest_url + "/session",
data=json.dumps(params),
params={"expand": "user"})
# If authentication failed for any reason return None
if not response.ok:
return None
# Otherwise return the user object
return response.json()
def validate_session(self, token, remote="127.0.0.1", proxy=None):
"""Validate a session token.
Validate a previously acquired session token against the
Crowd server. This may be a token provided by a user from
a http cookie or by some other means.
Args:
token: The session token.
remote: The remote address of the user.
proxy: Value of X-Forwarded-For server header
Returns:
dict:
A dict mapping of user attributes if the application
authentication was successful. See the Crowd
documentation for the authoritative list of attributes.
None: If authentication failed.
"""
params = {
"validationFactors": [
{"name": "remote_address", "value": remote, },
]
}
if proxy:
params["validation-factors"]["validationFactors"].append({"name": "X-Forwarded-For", "value": proxy, })
url = self.rest_url + "/session/%s" % token
response = self._post(url, data=json.dumps(params), params={"expand": "user"})
# For consistency between methods use None rather than False
# If token validation failed for any reason return None
if not response.ok:
return None
# Otherwise return the user object
return response.json()
def terminate_session(self, token):
"""Terminates the session token, effectively logging out the user
from all crowd-enabled services.
Args:
token: The session token.
Returns:
True: If session terminated
None: If session termination failed
"""
url = self.rest_url + "/session/%s" % token
response = self._delete(url)
# For consistency between methods use None rather than False
# If token validation failed for any reason return None
if not response.ok:
return None
# Otherwise return True
return True
def add_user(self, username, raise_on_error=False, **kwargs):
"""Add a user to the directory
Args:
username: The account username
raise_on_error: optional (default: False)
**kwargs: key-value pairs:
password: mandatory
email: mandatory
first_name: optional
last_name: optional
display_name: optional
active: optional (default True)
Returns:
True: Succeeded
False: If unsuccessful
"""
# Check that mandatory elements have been provided
if 'password' not in kwargs:
raise ValueError("missing password")
if 'email' not in kwargs:
raise ValueError("missing email")
# Populate data with default and mandatory values.
# A KeyError means a mandatory value was not provided,
# so raise a ValueError indicating bad args.
try:
data = {
"name": username,
"first-name": username,
"last-name": username,
"display-name": username,
"email": kwargs["email"],
"password": {"value": kwargs["password"]},
"active": True
}
except KeyError:
return ValueError
# Remove special case 'password'
del(kwargs["password"])
# Put values from kwargs into data
for k, v in kwargs.items():
new_k = k.replace("_", "-")
if new_k not in data:
raise ValueError("invalid argument %s" % k)
data[new_k] = v
response = self._post(self.rest_url + "/user",
data=json.dumps(data))
if response.status_code == 201:
return True
if raise_on_error:
raise RuntimeError(response.json()['message'])
return False
def get_user(self, username):
"""Retrieve information about a user
Returns:
dict: User information
None: If no user or failure occurred
"""
response = self._get(self.rest_url + "/user",
params={"username": username,
"expand": "attributes"})
if not response.ok:
return None
return response.json()
def set_active(self, username, active_state):
"""Set the active state of a user
Args:
username: The account username
active_state: True or False
Returns:
True: If successful
None: If no user or failure occurred
"""
if active_state not in (True, False):
raise ValueError("active_state must be True or False")
user = self.get_user(username)
if user is None:
return None
if user['active'] is active_state:
# Already in desired state
return True
user['active'] = active_state
response = self._put(self.rest_url + "/user",
params={"username": username},
data=json.dumps(user))
if response.status_code == 204:
return True
return None
def set_user_attribute(self, username, attribute, value, raise_on_error=False):
"""Set an attribute on a user
:param username: The username on which to set the attribute
:param attribute: The name of the attribute to set
:param value: The value of the attribute to set
:return: True on success, False on failure.
"""
data = {
'attributes': [
{
'name': attribute,
'values': [
value
]
},
]
}
response = self._post(self.rest_url + "/user/attribute",
params={"username": username,},
data=json.dumps(data))
if response.status_code == 204:
return True
if raise_on_error:
raise RuntimeError(response.json()['message'])
return False
def add_user_to_group(self, username, groupname, raise_on_error=False):
"""Add a user to a group
:param username: The username to assign to the group
:param groupname: The group name into which to assign the user
:return: True on success, False on failure.
"""
data = {
'name': groupname,
}
response = self._post(self.rest_url + "/user/group/direct",
params={"username": username,},
data=json.dumps(data))
if response.status_code == 201:
return True
if raise_on_error:
raise RuntimeError(response.json()['message'])
return False
def remove_user_from_group(self, username, groupname, raise_on_error=False):
"""Remove a user from a group
Attempts to remove a user from a group
Args
username: The username to remove from the group.
groupname: The group name to be removed from the user.
Returns:
True: Succeeded
False: If unsuccessful
"""
response = self._delete(self.rest_url + "/group/user/direct",params={"username": username, "groupname": groupname})
if response.status_code == 204:
return True
if raise_on_error:
raise RuntimeError(response.json()['message'])
return False
def change_password(self, username, newpassword, raise_on_error=False):
"""Change new password for a user
Args:
username: The account username.
newpassword: The account new password.
raise_on_error: optional (default: False)
Returns:
True: Succeeded
False: If unsuccessful
"""
response = self._put(self.rest_url + "/user/password",
data=json.dumps({"value": newpassword}),
params={"username": username})
if response.ok:
return True
if raise_on_error:
raise RuntimeError(response.json()['message'])
return False
def get_groups(self, username):
"""Retrieves a list of group names that have <username> as a direct member.
Returns:
list:
A list of strings of group names.
"""
response = self._get(self.rest_url + "/user/group/direct",
params={"username": username})
if not response.ok:
return None
return [g['name'] for g in response.json()['groups']]
def get_nested_groups(self, username):
"""Retrieve a list of all group names that have <username> as a direct or indirect member.
Args:
username: The account username.
Returns:
list:
A list of strings of group names.
"""
response = self._get(self.rest_url + "/user/group/nested",
params={"username": username})
if not response.ok:
return None
return [g['name'] for g in response.json()['groups']]
def get_nested_group_users(self, groupname):
"""Retrieves a list of all users that directly or indirectly belong to the given groupname.
Args:
groupname: The group name.
Returns:
list:
A list of strings of user names.
"""
response = self._get(self.rest_url + "/group/user/nested",
params={"groupname": groupname,
"start-index": 0,
"max-results": 99999})
if not response.ok:
return None
return [u['name'] for u in response.json()['users']]
def user_exists(self, username):
"""Determines if the user exists.
Args:
username: The user name.
Returns:
bool:
True if the user exists in the Crowd application.
"""
response = self._get(self.rest_url + "/user",
params={"username": username})
if not response.ok:
return None
return True
def get_memberships(self):
"""Fetches all group memberships.
Returns:
dict:
key: group name
value: (array of users, array of groups)
"""
response = self._get_xml(self.rest_url + "/group/membership")
if not response.ok:
return None
xmltree = etree.fromstring(response.content)
memberships = {}
for mg in xmltree.findall('membership'):
# coerce values to unicode in a python 2 and 3 compatible way
group = u'{}'.format(mg.get('group'))
users = [u'{}'.format(u.get('name')) for u in mg.find('users').findall('user')]
groups = [u'{}'.format(g.get('name')) for g in mg.find('groups').findall('group')]
memberships[group] = {u'users': users, u'groups': groups}
return memberships
def search(self, entity_type, property_name, search_string, start_index=0, max_results=99999):
"""Performs a user search using the Crowd search API.
https://developer.atlassian.com/display/CROWDDEV/Crowd+REST+Resources#CrowdRESTResources-SearchResource
Args:
entity_type: 'user' or 'group'
property_name: eg. 'email', 'name'
search_string: the string to search for.
start_index: starting index of the results (default: 0)
max_results: maximum number of results returned (default: 99999)
Returns:
json results:
Returns search results.
"""
params = {
"entity-type": entity_type,
"expand": entity_type,
"property-search-restriction": {
"property": {"name": property_name, "type": "STRING"},
"match-mode": "CONTAINS",
"value": search_string,
}
}
params = {
'entity-type': entity_type,
'expand': entity_type,
'start-index': start_index,
'max-results': max_results
}
# Construct XML payload of the form:
# <property-search-restriction>
# <property>
# <name>email</name>
# <type>STRING</type>
# </property>
# <match-mode>EXACTLY_MATCHES</match-mode>
# <value>bob@example.net</value>
# </property-search-restriction>
root = etree.Element('property-search-restriction')
property_ = etree.Element('property')
prop_name = etree.Element('name')
prop_name.text = property_name
property_.append(prop_name)
prop_type = etree.Element('type')
prop_type.text = 'STRING'
property_.append(prop_type)
root.append(property_)
match_mode = etree.Element('match-mode')
match_mode.text = 'CONTAINS'
root.append(match_mode)
value = etree.Element('value')
value.text = search_string
root.append(value)
# Construct the XML payload expected by search API
payload = '<?xml version="1.0" encoding="UTF-8"?>\n' + etree.tostring(root).decode('utf-8')
# We're sending XML but would like a JSON response
session = self._build_session(content_type='xml')
session.headers.update({'Accept': 'application/json'})
response = session.post(self.rest_url + "/search", params=params, data=payload, timeout=self.timeout)
if not response.ok:
return None
return response.json()
|
pycontribs/python-crowd | crowd.py | CrowdServer.get_nested_groups | python | def get_nested_groups(self, username):
response = self._get(self.rest_url + "/user/group/nested",
params={"username": username})
if not response.ok:
return None
return [g['name'] for g in response.json()['groups']] | Retrieve a list of all group names that have <username> as a direct or indirect member.
Args:
username: The account username.
Returns:
list:
A list of strings of group names. | train | https://github.com/pycontribs/python-crowd/blob/a075e45774dd5baecf0217843cda747084268e32/crowd.py#L569-L587 | [
"def _get(self, *args, **kwargs):\n \"\"\"Wrapper around Requests for GET requests\n\n Returns:\n Response:\n A Requests Response object\n \"\"\"\n\n if 'timeout' not in kwargs:\n kwargs['timeout'] = self.timeout\n\n req = self.session.get(*args, **kwargs)\n return req\n"
... | class CrowdServer(object):
"""Crowd server authentication object.
This is a Crowd authentication class to be configured for a
particular application (app_name) to authenticate users
against a Crowd server (crowd_url).
This module uses the Crowd JSON API for talking to Crowd.
An application account must be configured in the Crowd server
and permitted to authenticate users against one or more user
directories prior to using this module.
Please see the Crowd documentation for information about
configuring additional applications to talk to Crowd.
The ``ssl_verify`` parameter controls how and if certificates are verified.
If ``True``, the SSL certificate will be verified.
A CA_BUNDLE path can also be provided.
The ``client_cert`` tuple (cert,key) specifies a SSL client certificate and key files.
"""
def __init__(self, crowd_url, app_name, app_pass, ssl_verify=True,
timeout=None, client_cert=None):
self.crowd_url = crowd_url
self.app_name = app_name
self.app_pass = app_pass
self.rest_url = crowd_url.rstrip("/") + "/rest/usermanagement/1"
self.ssl_verify = ssl_verify
self.client_cert = client_cert
self.timeout = timeout
self.session = self._build_session(content_type='json')
self.session_xml = self._build_session(content_type='xml')
def __str__(self):
return "Crowd Server at %s" % self.crowd_url
def __repr__(self):
return "<CrowdServer('%s', '%s', '%s')>" % \
(self.crowd_url, self.app_name, self.app_pass)
def _build_session(self, content_type='json'):
headers = {
'Content-Type': 'application/{}'.format(content_type),
'Accept': 'application/{}'.format(content_type),
}
session = requests.Session()
session.verify = self.ssl_verify
session.cert = self.client_cert
session.auth = requests.auth.HTTPBasicAuth(self.app_name, self.app_pass)
session.headers.update(headers)
return session
def _get(self, *args, **kwargs):
"""Wrapper around Requests for GET requests
Returns:
Response:
A Requests Response object
"""
if 'timeout' not in kwargs:
kwargs['timeout'] = self.timeout
req = self.session.get(*args, **kwargs)
return req
def _get_xml(self, *args, **kwargs):
"""Wrapper around Requests for GET XML requests
Returns:
Response:
A Requests Response object
"""
req = self.session_xml.get(*args, **kwargs)
return req
def _post(self, *args, **kwargs):
"""Wrapper around Requests for POST requests
Returns:
Response:
A Requests Response object
"""
if 'timeout' not in kwargs:
kwargs['timeout'] = self.timeout
req = self.session.post(*args, **kwargs)
return req
def _post_xml(self, *args, **kwargs):
"""Wrapper around Requests for POST requests
Returns:
Response:
A Requests Response object
"""
if 'timeout' not in kwargs:
kwargs['timeout'] = self.timeout
req = self.session_xml.post(*args, **kwargs)
return req
def _put(self, *args, **kwargs):
"""Wrapper around Requests for PUT requests
Returns:
Response:
A Requests Response object
"""
if 'timeout' not in kwargs:
kwargs['timeout'] = self.timeout
req = self.session.put(*args, **kwargs)
return req
def _delete(self, *args, **kwargs):
"""Wrapper around Requests for DELETE requests
Returns:
Response:
A Requests Response object
"""
if 'timeout' not in kwargs:
kwargs['timeout'] = self.timeout
req = self.session.delete(*args, **kwargs)
return req
def auth_ping(self):
"""Test that application can authenticate to Crowd.
Attempts to authenticate the application user against
the Crowd server. In order for user authentication to
work, an application must be able to authenticate.
Returns:
bool:
True if the application authentication succeeded.
"""
url = self.rest_url + "/non-existent/location"
response = self._get(url)
if response.status_code == 401:
return False
elif response.status_code == 404:
return True
else:
# An error encountered - problem with the Crowd server?
return False
def auth_user(self, username, password):
"""Authenticate a user account against the Crowd server.
Attempts to authenticate the user against the Crowd server.
Args:
username: The account username.
password: The account password.
Returns:
dict:
A dict mapping of user attributes if the application
authentication was successful. See the Crowd documentation
for the authoritative list of attributes.
None: If authentication failed.
"""
response = self._post(self.rest_url + "/authentication",
data=json.dumps({"value": password}),
params={"username": username})
# If authentication failed for any reason return None
if not response.ok:
return None
# ...otherwise return a dictionary of user attributes
return response.json()
def get_session(self, username, password, remote="127.0.0.1", proxy=None):
"""Create a session for a user.
Attempts to create a user session on the Crowd server.
Args:
username: The account username.
password: The account password.
remote:
The remote address of the user. This can be used
to create multiple concurrent sessions for a user.
The host you run this program on may need to be configured
in Crowd as a trusted proxy for this to work.
proxy: Value of X-Forwarded-For server header.
Returns:
dict:
A dict mapping of user attributes if the application
authentication was successful. See the Crowd
documentation for the authoritative list of attributes.
None: If authentication failed.
"""
params = {
"username": username,
"password": password,
"validation-factors": {
"validationFactors": [
{"name": "remote_address", "value": remote, },
]
}
}
if proxy:
params["validation-factors"]["validationFactors"].append({"name": "X-Forwarded-For", "value": proxy, })
response = self._post(self.rest_url + "/session",
data=json.dumps(params),
params={"expand": "user"})
# If authentication failed for any reason return None
if not response.ok:
return None
# Otherwise return the user object
return response.json()
def validate_session(self, token, remote="127.0.0.1", proxy=None):
"""Validate a session token.
Validate a previously acquired session token against the
Crowd server. This may be a token provided by a user from
a http cookie or by some other means.
Args:
token: The session token.
remote: The remote address of the user.
proxy: Value of X-Forwarded-For server header
Returns:
dict:
A dict mapping of user attributes if the application
authentication was successful. See the Crowd
documentation for the authoritative list of attributes.
None: If authentication failed.
"""
params = {
"validationFactors": [
{"name": "remote_address", "value": remote, },
]
}
if proxy:
params["validation-factors"]["validationFactors"].append({"name": "X-Forwarded-For", "value": proxy, })
url = self.rest_url + "/session/%s" % token
response = self._post(url, data=json.dumps(params), params={"expand": "user"})
# For consistency between methods use None rather than False
# If token validation failed for any reason return None
if not response.ok:
return None
# Otherwise return the user object
return response.json()
def terminate_session(self, token):
"""Terminates the session token, effectively logging out the user
from all crowd-enabled services.
Args:
token: The session token.
Returns:
True: If session terminated
None: If session termination failed
"""
url = self.rest_url + "/session/%s" % token
response = self._delete(url)
# For consistency between methods use None rather than False
# If token validation failed for any reason return None
if not response.ok:
return None
# Otherwise return True
return True
def add_user(self, username, raise_on_error=False, **kwargs):
"""Add a user to the directory
Args:
username: The account username
raise_on_error: optional (default: False)
**kwargs: key-value pairs:
password: mandatory
email: mandatory
first_name: optional
last_name: optional
display_name: optional
active: optional (default True)
Returns:
True: Succeeded
False: If unsuccessful
"""
# Check that mandatory elements have been provided
if 'password' not in kwargs:
raise ValueError("missing password")
if 'email' not in kwargs:
raise ValueError("missing email")
# Populate data with default and mandatory values.
# A KeyError means a mandatory value was not provided,
# so raise a ValueError indicating bad args.
try:
data = {
"name": username,
"first-name": username,
"last-name": username,
"display-name": username,
"email": kwargs["email"],
"password": {"value": kwargs["password"]},
"active": True
}
except KeyError:
return ValueError
# Remove special case 'password'
del(kwargs["password"])
# Put values from kwargs into data
for k, v in kwargs.items():
new_k = k.replace("_", "-")
if new_k not in data:
raise ValueError("invalid argument %s" % k)
data[new_k] = v
response = self._post(self.rest_url + "/user",
data=json.dumps(data))
if response.status_code == 201:
return True
if raise_on_error:
raise RuntimeError(response.json()['message'])
return False
def get_user(self, username):
"""Retrieve information about a user
Returns:
dict: User information
None: If no user or failure occurred
"""
response = self._get(self.rest_url + "/user",
params={"username": username,
"expand": "attributes"})
if not response.ok:
return None
return response.json()
def set_active(self, username, active_state):
"""Set the active state of a user
Args:
username: The account username
active_state: True or False
Returns:
True: If successful
None: If no user or failure occurred
"""
if active_state not in (True, False):
raise ValueError("active_state must be True or False")
user = self.get_user(username)
if user is None:
return None
if user['active'] is active_state:
# Already in desired state
return True
user['active'] = active_state
response = self._put(self.rest_url + "/user",
params={"username": username},
data=json.dumps(user))
if response.status_code == 204:
return True
return None
def set_user_attribute(self, username, attribute, value, raise_on_error=False):
"""Set an attribute on a user
:param username: The username on which to set the attribute
:param attribute: The name of the attribute to set
:param value: The value of the attribute to set
:return: True on success, False on failure.
"""
data = {
'attributes': [
{
'name': attribute,
'values': [
value
]
},
]
}
response = self._post(self.rest_url + "/user/attribute",
params={"username": username,},
data=json.dumps(data))
if response.status_code == 204:
return True
if raise_on_error:
raise RuntimeError(response.json()['message'])
return False
def add_user_to_group(self, username, groupname, raise_on_error=False):
"""Add a user to a group
:param username: The username to assign to the group
:param groupname: The group name into which to assign the user
:return: True on success, False on failure.
"""
data = {
'name': groupname,
}
response = self._post(self.rest_url + "/user/group/direct",
params={"username": username,},
data=json.dumps(data))
if response.status_code == 201:
return True
if raise_on_error:
raise RuntimeError(response.json()['message'])
return False
def remove_user_from_group(self, username, groupname, raise_on_error=False):
"""Remove a user from a group
Attempts to remove a user from a group
Args
username: The username to remove from the group.
groupname: The group name to be removed from the user.
Returns:
True: Succeeded
False: If unsuccessful
"""
response = self._delete(self.rest_url + "/group/user/direct",params={"username": username, "groupname": groupname})
if response.status_code == 204:
return True
if raise_on_error:
raise RuntimeError(response.json()['message'])
return False
def change_password(self, username, newpassword, raise_on_error=False):
"""Change new password for a user
Args:
username: The account username.
newpassword: The account new password.
raise_on_error: optional (default: False)
Returns:
True: Succeeded
False: If unsuccessful
"""
response = self._put(self.rest_url + "/user/password",
data=json.dumps({"value": newpassword}),
params={"username": username})
if response.ok:
return True
if raise_on_error:
raise RuntimeError(response.json()['message'])
return False
def send_password_reset_link(self, username):
"""Sends the user a password reset link (by email)
Args:
username: The account username.
Returns:
True: Succeeded
False: If unsuccessful
"""
response = self._post(self.rest_url + "/user/mail/password",
params={"username": username})
if response.ok:
return True
return False
def get_groups(self, username):
"""Retrieves a list of group names that have <username> as a direct member.
Returns:
list:
A list of strings of group names.
"""
response = self._get(self.rest_url + "/user/group/direct",
params={"username": username})
if not response.ok:
return None
return [g['name'] for g in response.json()['groups']]
def get_nested_group_users(self, groupname):
"""Retrieves a list of all users that directly or indirectly belong to the given groupname.
Args:
groupname: The group name.
Returns:
list:
A list of strings of user names.
"""
response = self._get(self.rest_url + "/group/user/nested",
params={"groupname": groupname,
"start-index": 0,
"max-results": 99999})
if not response.ok:
return None
return [u['name'] for u in response.json()['users']]
def user_exists(self, username):
"""Determines if the user exists.
Args:
username: The user name.
Returns:
bool:
True if the user exists in the Crowd application.
"""
response = self._get(self.rest_url + "/user",
params={"username": username})
if not response.ok:
return None
return True
def get_memberships(self):
"""Fetches all group memberships.
Returns:
dict:
key: group name
value: (array of users, array of groups)
"""
response = self._get_xml(self.rest_url + "/group/membership")
if not response.ok:
return None
xmltree = etree.fromstring(response.content)
memberships = {}
for mg in xmltree.findall('membership'):
# coerce values to unicode in a python 2 and 3 compatible way
group = u'{}'.format(mg.get('group'))
users = [u'{}'.format(u.get('name')) for u in mg.find('users').findall('user')]
groups = [u'{}'.format(g.get('name')) for g in mg.find('groups').findall('group')]
memberships[group] = {u'users': users, u'groups': groups}
return memberships
def search(self, entity_type, property_name, search_string, start_index=0, max_results=99999):
"""Performs a user search using the Crowd search API.
https://developer.atlassian.com/display/CROWDDEV/Crowd+REST+Resources#CrowdRESTResources-SearchResource
Args:
entity_type: 'user' or 'group'
property_name: eg. 'email', 'name'
search_string: the string to search for.
start_index: starting index of the results (default: 0)
max_results: maximum number of results returned (default: 99999)
Returns:
json results:
Returns search results.
"""
params = {
"entity-type": entity_type,
"expand": entity_type,
"property-search-restriction": {
"property": {"name": property_name, "type": "STRING"},
"match-mode": "CONTAINS",
"value": search_string,
}
}
params = {
'entity-type': entity_type,
'expand': entity_type,
'start-index': start_index,
'max-results': max_results
}
# Construct XML payload of the form:
# <property-search-restriction>
# <property>
# <name>email</name>
# <type>STRING</type>
# </property>
# <match-mode>EXACTLY_MATCHES</match-mode>
# <value>bob@example.net</value>
# </property-search-restriction>
root = etree.Element('property-search-restriction')
property_ = etree.Element('property')
prop_name = etree.Element('name')
prop_name.text = property_name
property_.append(prop_name)
prop_type = etree.Element('type')
prop_type.text = 'STRING'
property_.append(prop_type)
root.append(property_)
match_mode = etree.Element('match-mode')
match_mode.text = 'CONTAINS'
root.append(match_mode)
value = etree.Element('value')
value.text = search_string
root.append(value)
# Construct the XML payload expected by search API
payload = '<?xml version="1.0" encoding="UTF-8"?>\n' + etree.tostring(root).decode('utf-8')
# We're sending XML but would like a JSON response
session = self._build_session(content_type='xml')
session.headers.update({'Accept': 'application/json'})
response = session.post(self.rest_url + "/search", params=params, data=payload, timeout=self.timeout)
if not response.ok:
return None
return response.json()
|
pycontribs/python-crowd | crowd.py | CrowdServer.get_nested_group_users | python | def get_nested_group_users(self, groupname):
response = self._get(self.rest_url + "/group/user/nested",
params={"groupname": groupname,
"start-index": 0,
"max-results": 99999})
if not response.ok:
return None
return [u['name'] for u in response.json()['users']] | Retrieves a list of all users that directly or indirectly belong to the given groupname.
Args:
groupname: The group name.
Returns:
list:
A list of strings of user names. | train | https://github.com/pycontribs/python-crowd/blob/a075e45774dd5baecf0217843cda747084268e32/crowd.py#L589-L609 | [
"def _get(self, *args, **kwargs):\n \"\"\"Wrapper around Requests for GET requests\n\n Returns:\n Response:\n A Requests Response object\n \"\"\"\n\n if 'timeout' not in kwargs:\n kwargs['timeout'] = self.timeout\n\n req = self.session.get(*args, **kwargs)\n return req\n"
... | class CrowdServer(object):
"""Crowd server authentication object.
This is a Crowd authentication class to be configured for a
particular application (app_name) to authenticate users
against a Crowd server (crowd_url).
This module uses the Crowd JSON API for talking to Crowd.
An application account must be configured in the Crowd server
and permitted to authenticate users against one or more user
directories prior to using this module.
Please see the Crowd documentation for information about
configuring additional applications to talk to Crowd.
The ``ssl_verify`` parameter controls how and if certificates are verified.
If ``True``, the SSL certificate will be verified.
A CA_BUNDLE path can also be provided.
The ``client_cert`` tuple (cert,key) specifies a SSL client certificate and key files.
"""
def __init__(self, crowd_url, app_name, app_pass, ssl_verify=True,
timeout=None, client_cert=None):
self.crowd_url = crowd_url
self.app_name = app_name
self.app_pass = app_pass
self.rest_url = crowd_url.rstrip("/") + "/rest/usermanagement/1"
self.ssl_verify = ssl_verify
self.client_cert = client_cert
self.timeout = timeout
self.session = self._build_session(content_type='json')
self.session_xml = self._build_session(content_type='xml')
def __str__(self):
return "Crowd Server at %s" % self.crowd_url
def __repr__(self):
return "<CrowdServer('%s', '%s', '%s')>" % \
(self.crowd_url, self.app_name, self.app_pass)
def _build_session(self, content_type='json'):
headers = {
'Content-Type': 'application/{}'.format(content_type),
'Accept': 'application/{}'.format(content_type),
}
session = requests.Session()
session.verify = self.ssl_verify
session.cert = self.client_cert
session.auth = requests.auth.HTTPBasicAuth(self.app_name, self.app_pass)
session.headers.update(headers)
return session
def _get(self, *args, **kwargs):
"""Wrapper around Requests for GET requests
Returns:
Response:
A Requests Response object
"""
if 'timeout' not in kwargs:
kwargs['timeout'] = self.timeout
req = self.session.get(*args, **kwargs)
return req
def _get_xml(self, *args, **kwargs):
"""Wrapper around Requests for GET XML requests
Returns:
Response:
A Requests Response object
"""
req = self.session_xml.get(*args, **kwargs)
return req
def _post(self, *args, **kwargs):
"""Wrapper around Requests for POST requests
Returns:
Response:
A Requests Response object
"""
if 'timeout' not in kwargs:
kwargs['timeout'] = self.timeout
req = self.session.post(*args, **kwargs)
return req
def _post_xml(self, *args, **kwargs):
"""Wrapper around Requests for POST requests
Returns:
Response:
A Requests Response object
"""
if 'timeout' not in kwargs:
kwargs['timeout'] = self.timeout
req = self.session_xml.post(*args, **kwargs)
return req
def _put(self, *args, **kwargs):
"""Wrapper around Requests for PUT requests
Returns:
Response:
A Requests Response object
"""
if 'timeout' not in kwargs:
kwargs['timeout'] = self.timeout
req = self.session.put(*args, **kwargs)
return req
def _delete(self, *args, **kwargs):
"""Wrapper around Requests for DELETE requests
Returns:
Response:
A Requests Response object
"""
if 'timeout' not in kwargs:
kwargs['timeout'] = self.timeout
req = self.session.delete(*args, **kwargs)
return req
def auth_ping(self):
"""Test that application can authenticate to Crowd.
Attempts to authenticate the application user against
the Crowd server. In order for user authentication to
work, an application must be able to authenticate.
Returns:
bool:
True if the application authentication succeeded.
"""
url = self.rest_url + "/non-existent/location"
response = self._get(url)
if response.status_code == 401:
return False
elif response.status_code == 404:
return True
else:
# An error encountered - problem with the Crowd server?
return False
def auth_user(self, username, password):
"""Authenticate a user account against the Crowd server.
Attempts to authenticate the user against the Crowd server.
Args:
username: The account username.
password: The account password.
Returns:
dict:
A dict mapping of user attributes if the application
authentication was successful. See the Crowd documentation
for the authoritative list of attributes.
None: If authentication failed.
"""
response = self._post(self.rest_url + "/authentication",
data=json.dumps({"value": password}),
params={"username": username})
# If authentication failed for any reason return None
if not response.ok:
return None
# ...otherwise return a dictionary of user attributes
return response.json()
def get_session(self, username, password, remote="127.0.0.1", proxy=None):
"""Create a session for a user.
Attempts to create a user session on the Crowd server.
Args:
username: The account username.
password: The account password.
remote:
The remote address of the user. This can be used
to create multiple concurrent sessions for a user.
The host you run this program on may need to be configured
in Crowd as a trusted proxy for this to work.
proxy: Value of X-Forwarded-For server header.
Returns:
dict:
A dict mapping of user attributes if the application
authentication was successful. See the Crowd
documentation for the authoritative list of attributes.
None: If authentication failed.
"""
params = {
"username": username,
"password": password,
"validation-factors": {
"validationFactors": [
{"name": "remote_address", "value": remote, },
]
}
}
if proxy:
params["validation-factors"]["validationFactors"].append({"name": "X-Forwarded-For", "value": proxy, })
response = self._post(self.rest_url + "/session",
data=json.dumps(params),
params={"expand": "user"})
# If authentication failed for any reason return None
if not response.ok:
return None
# Otherwise return the user object
return response.json()
def validate_session(self, token, remote="127.0.0.1", proxy=None):
"""Validate a session token.
Validate a previously acquired session token against the
Crowd server. This may be a token provided by a user from
a http cookie or by some other means.
Args:
token: The session token.
remote: The remote address of the user.
proxy: Value of X-Forwarded-For server header
Returns:
dict:
A dict mapping of user attributes if the application
authentication was successful. See the Crowd
documentation for the authoritative list of attributes.
None: If authentication failed.
"""
params = {
"validationFactors": [
{"name": "remote_address", "value": remote, },
]
}
if proxy:
params["validation-factors"]["validationFactors"].append({"name": "X-Forwarded-For", "value": proxy, })
url = self.rest_url + "/session/%s" % token
response = self._post(url, data=json.dumps(params), params={"expand": "user"})
# For consistency between methods use None rather than False
# If token validation failed for any reason return None
if not response.ok:
return None
# Otherwise return the user object
return response.json()
def terminate_session(self, token):
"""Terminates the session token, effectively logging out the user
from all crowd-enabled services.
Args:
token: The session token.
Returns:
True: If session terminated
None: If session termination failed
"""
url = self.rest_url + "/session/%s" % token
response = self._delete(url)
# For consistency between methods use None rather than False
# If token validation failed for any reason return None
if not response.ok:
return None
# Otherwise return True
return True
def add_user(self, username, raise_on_error=False, **kwargs):
"""Add a user to the directory
Args:
username: The account username
raise_on_error: optional (default: False)
**kwargs: key-value pairs:
password: mandatory
email: mandatory
first_name: optional
last_name: optional
display_name: optional
active: optional (default True)
Returns:
True: Succeeded
False: If unsuccessful
"""
# Check that mandatory elements have been provided
if 'password' not in kwargs:
raise ValueError("missing password")
if 'email' not in kwargs:
raise ValueError("missing email")
# Populate data with default and mandatory values.
# A KeyError means a mandatory value was not provided,
# so raise a ValueError indicating bad args.
try:
data = {
"name": username,
"first-name": username,
"last-name": username,
"display-name": username,
"email": kwargs["email"],
"password": {"value": kwargs["password"]},
"active": True
}
except KeyError:
return ValueError
# Remove special case 'password'
del(kwargs["password"])
# Put values from kwargs into data
for k, v in kwargs.items():
new_k = k.replace("_", "-")
if new_k not in data:
raise ValueError("invalid argument %s" % k)
data[new_k] = v
response = self._post(self.rest_url + "/user",
data=json.dumps(data))
if response.status_code == 201:
return True
if raise_on_error:
raise RuntimeError(response.json()['message'])
return False
def get_user(self, username):
"""Retrieve information about a user
Returns:
dict: User information
None: If no user or failure occurred
"""
response = self._get(self.rest_url + "/user",
params={"username": username,
"expand": "attributes"})
if not response.ok:
return None
return response.json()
def set_active(self, username, active_state):
"""Set the active state of a user
Args:
username: The account username
active_state: True or False
Returns:
True: If successful
None: If no user or failure occurred
"""
if active_state not in (True, False):
raise ValueError("active_state must be True or False")
user = self.get_user(username)
if user is None:
return None
if user['active'] is active_state:
# Already in desired state
return True
user['active'] = active_state
response = self._put(self.rest_url + "/user",
params={"username": username},
data=json.dumps(user))
if response.status_code == 204:
return True
return None
def set_user_attribute(self, username, attribute, value, raise_on_error=False):
"""Set an attribute on a user
:param username: The username on which to set the attribute
:param attribute: The name of the attribute to set
:param value: The value of the attribute to set
:return: True on success, False on failure.
"""
data = {
'attributes': [
{
'name': attribute,
'values': [
value
]
},
]
}
response = self._post(self.rest_url + "/user/attribute",
params={"username": username,},
data=json.dumps(data))
if response.status_code == 204:
return True
if raise_on_error:
raise RuntimeError(response.json()['message'])
return False
def add_user_to_group(self, username, groupname, raise_on_error=False):
"""Add a user to a group
:param username: The username to assign to the group
:param groupname: The group name into which to assign the user
:return: True on success, False on failure.
"""
data = {
'name': groupname,
}
response = self._post(self.rest_url + "/user/group/direct",
params={"username": username,},
data=json.dumps(data))
if response.status_code == 201:
return True
if raise_on_error:
raise RuntimeError(response.json()['message'])
return False
def remove_user_from_group(self, username, groupname, raise_on_error=False):
"""Remove a user from a group
Attempts to remove a user from a group
Args
username: The username to remove from the group.
groupname: The group name to be removed from the user.
Returns:
True: Succeeded
False: If unsuccessful
"""
response = self._delete(self.rest_url + "/group/user/direct",params={"username": username, "groupname": groupname})
if response.status_code == 204:
return True
if raise_on_error:
raise RuntimeError(response.json()['message'])
return False
def change_password(self, username, newpassword, raise_on_error=False):
"""Change new password for a user
Args:
username: The account username.
newpassword: The account new password.
raise_on_error: optional (default: False)
Returns:
True: Succeeded
False: If unsuccessful
"""
response = self._put(self.rest_url + "/user/password",
data=json.dumps({"value": newpassword}),
params={"username": username})
if response.ok:
return True
if raise_on_error:
raise RuntimeError(response.json()['message'])
return False
def send_password_reset_link(self, username):
"""Sends the user a password reset link (by email)
Args:
username: The account username.
Returns:
True: Succeeded
False: If unsuccessful
"""
response = self._post(self.rest_url + "/user/mail/password",
params={"username": username})
if response.ok:
return True
return False
def get_groups(self, username):
"""Retrieves a list of group names that have <username> as a direct member.
Returns:
list:
A list of strings of group names.
"""
response = self._get(self.rest_url + "/user/group/direct",
params={"username": username})
if not response.ok:
return None
return [g['name'] for g in response.json()['groups']]
def get_nested_groups(self, username):
"""Retrieve a list of all group names that have <username> as a direct or indirect member.
Args:
username: The account username.
Returns:
list:
A list of strings of group names.
"""
response = self._get(self.rest_url + "/user/group/nested",
params={"username": username})
if not response.ok:
return None
return [g['name'] for g in response.json()['groups']]
def user_exists(self, username):
"""Determines if the user exists.
Args:
username: The user name.
Returns:
bool:
True if the user exists in the Crowd application.
"""
response = self._get(self.rest_url + "/user",
params={"username": username})
if not response.ok:
return None
return True
def get_memberships(self):
"""Fetches all group memberships.
Returns:
dict:
key: group name
value: (array of users, array of groups)
"""
response = self._get_xml(self.rest_url + "/group/membership")
if not response.ok:
return None
xmltree = etree.fromstring(response.content)
memberships = {}
for mg in xmltree.findall('membership'):
# coerce values to unicode in a python 2 and 3 compatible way
group = u'{}'.format(mg.get('group'))
users = [u'{}'.format(u.get('name')) for u in mg.find('users').findall('user')]
groups = [u'{}'.format(g.get('name')) for g in mg.find('groups').findall('group')]
memberships[group] = {u'users': users, u'groups': groups}
return memberships
def search(self, entity_type, property_name, search_string, start_index=0, max_results=99999):
"""Performs a user search using the Crowd search API.
https://developer.atlassian.com/display/CROWDDEV/Crowd+REST+Resources#CrowdRESTResources-SearchResource
Args:
entity_type: 'user' or 'group'
property_name: eg. 'email', 'name'
search_string: the string to search for.
start_index: starting index of the results (default: 0)
max_results: maximum number of results returned (default: 99999)
Returns:
json results:
Returns search results.
"""
params = {
"entity-type": entity_type,
"expand": entity_type,
"property-search-restriction": {
"property": {"name": property_name, "type": "STRING"},
"match-mode": "CONTAINS",
"value": search_string,
}
}
params = {
'entity-type': entity_type,
'expand': entity_type,
'start-index': start_index,
'max-results': max_results
}
# Construct XML payload of the form:
# <property-search-restriction>
# <property>
# <name>email</name>
# <type>STRING</type>
# </property>
# <match-mode>EXACTLY_MATCHES</match-mode>
# <value>bob@example.net</value>
# </property-search-restriction>
root = etree.Element('property-search-restriction')
property_ = etree.Element('property')
prop_name = etree.Element('name')
prop_name.text = property_name
property_.append(prop_name)
prop_type = etree.Element('type')
prop_type.text = 'STRING'
property_.append(prop_type)
root.append(property_)
match_mode = etree.Element('match-mode')
match_mode.text = 'CONTAINS'
root.append(match_mode)
value = etree.Element('value')
value.text = search_string
root.append(value)
# Construct the XML payload expected by search API
payload = '<?xml version="1.0" encoding="UTF-8"?>\n' + etree.tostring(root).decode('utf-8')
# We're sending XML but would like a JSON response
session = self._build_session(content_type='xml')
session.headers.update({'Accept': 'application/json'})
response = session.post(self.rest_url + "/search", params=params, data=payload, timeout=self.timeout)
if not response.ok:
return None
return response.json()
|
pycontribs/python-crowd | crowd.py | CrowdServer.user_exists | python | def user_exists(self, username):
response = self._get(self.rest_url + "/user",
params={"username": username})
if not response.ok:
return None
return True | Determines if the user exists.
Args:
username: The user name.
Returns:
bool:
True if the user exists in the Crowd application. | train | https://github.com/pycontribs/python-crowd/blob/a075e45774dd5baecf0217843cda747084268e32/crowd.py#L611-L629 | [
"def _get(self, *args, **kwargs):\n \"\"\"Wrapper around Requests for GET requests\n\n Returns:\n Response:\n A Requests Response object\n \"\"\"\n\n if 'timeout' not in kwargs:\n kwargs['timeout'] = self.timeout\n\n req = self.session.get(*args, **kwargs)\n return req\n"
... | class CrowdServer(object):
"""Crowd server authentication object.
This is a Crowd authentication class to be configured for a
particular application (app_name) to authenticate users
against a Crowd server (crowd_url).
This module uses the Crowd JSON API for talking to Crowd.
An application account must be configured in the Crowd server
and permitted to authenticate users against one or more user
directories prior to using this module.
Please see the Crowd documentation for information about
configuring additional applications to talk to Crowd.
The ``ssl_verify`` parameter controls how and if certificates are verified.
If ``True``, the SSL certificate will be verified.
A CA_BUNDLE path can also be provided.
The ``client_cert`` tuple (cert,key) specifies a SSL client certificate and key files.
"""
def __init__(self, crowd_url, app_name, app_pass, ssl_verify=True,
timeout=None, client_cert=None):
self.crowd_url = crowd_url
self.app_name = app_name
self.app_pass = app_pass
self.rest_url = crowd_url.rstrip("/") + "/rest/usermanagement/1"
self.ssl_verify = ssl_verify
self.client_cert = client_cert
self.timeout = timeout
self.session = self._build_session(content_type='json')
self.session_xml = self._build_session(content_type='xml')
def __str__(self):
return "Crowd Server at %s" % self.crowd_url
def __repr__(self):
return "<CrowdServer('%s', '%s', '%s')>" % \
(self.crowd_url, self.app_name, self.app_pass)
def _build_session(self, content_type='json'):
headers = {
'Content-Type': 'application/{}'.format(content_type),
'Accept': 'application/{}'.format(content_type),
}
session = requests.Session()
session.verify = self.ssl_verify
session.cert = self.client_cert
session.auth = requests.auth.HTTPBasicAuth(self.app_name, self.app_pass)
session.headers.update(headers)
return session
def _get(self, *args, **kwargs):
"""Wrapper around Requests for GET requests
Returns:
Response:
A Requests Response object
"""
if 'timeout' not in kwargs:
kwargs['timeout'] = self.timeout
req = self.session.get(*args, **kwargs)
return req
def _get_xml(self, *args, **kwargs):
"""Wrapper around Requests for GET XML requests
Returns:
Response:
A Requests Response object
"""
req = self.session_xml.get(*args, **kwargs)
return req
def _post(self, *args, **kwargs):
"""Wrapper around Requests for POST requests
Returns:
Response:
A Requests Response object
"""
if 'timeout' not in kwargs:
kwargs['timeout'] = self.timeout
req = self.session.post(*args, **kwargs)
return req
def _post_xml(self, *args, **kwargs):
"""Wrapper around Requests for POST requests
Returns:
Response:
A Requests Response object
"""
if 'timeout' not in kwargs:
kwargs['timeout'] = self.timeout
req = self.session_xml.post(*args, **kwargs)
return req
def _put(self, *args, **kwargs):
"""Wrapper around Requests for PUT requests
Returns:
Response:
A Requests Response object
"""
if 'timeout' not in kwargs:
kwargs['timeout'] = self.timeout
req = self.session.put(*args, **kwargs)
return req
def _delete(self, *args, **kwargs):
"""Wrapper around Requests for DELETE requests
Returns:
Response:
A Requests Response object
"""
if 'timeout' not in kwargs:
kwargs['timeout'] = self.timeout
req = self.session.delete(*args, **kwargs)
return req
def auth_ping(self):
"""Test that application can authenticate to Crowd.
Attempts to authenticate the application user against
the Crowd server. In order for user authentication to
work, an application must be able to authenticate.
Returns:
bool:
True if the application authentication succeeded.
"""
url = self.rest_url + "/non-existent/location"
response = self._get(url)
if response.status_code == 401:
return False
elif response.status_code == 404:
return True
else:
# An error encountered - problem with the Crowd server?
return False
def auth_user(self, username, password):
"""Authenticate a user account against the Crowd server.
Attempts to authenticate the user against the Crowd server.
Args:
username: The account username.
password: The account password.
Returns:
dict:
A dict mapping of user attributes if the application
authentication was successful. See the Crowd documentation
for the authoritative list of attributes.
None: If authentication failed.
"""
response = self._post(self.rest_url + "/authentication",
data=json.dumps({"value": password}),
params={"username": username})
# If authentication failed for any reason return None
if not response.ok:
return None
# ...otherwise return a dictionary of user attributes
return response.json()
def get_session(self, username, password, remote="127.0.0.1", proxy=None):
"""Create a session for a user.
Attempts to create a user session on the Crowd server.
Args:
username: The account username.
password: The account password.
remote:
The remote address of the user. This can be used
to create multiple concurrent sessions for a user.
The host you run this program on may need to be configured
in Crowd as a trusted proxy for this to work.
proxy: Value of X-Forwarded-For server header.
Returns:
dict:
A dict mapping of user attributes if the application
authentication was successful. See the Crowd
documentation for the authoritative list of attributes.
None: If authentication failed.
"""
params = {
"username": username,
"password": password,
"validation-factors": {
"validationFactors": [
{"name": "remote_address", "value": remote, },
]
}
}
if proxy:
params["validation-factors"]["validationFactors"].append({"name": "X-Forwarded-For", "value": proxy, })
response = self._post(self.rest_url + "/session",
data=json.dumps(params),
params={"expand": "user"})
# If authentication failed for any reason return None
if not response.ok:
return None
# Otherwise return the user object
return response.json()
def validate_session(self, token, remote="127.0.0.1", proxy=None):
"""Validate a session token.
Validate a previously acquired session token against the
Crowd server. This may be a token provided by a user from
a http cookie or by some other means.
Args:
token: The session token.
remote: The remote address of the user.
proxy: Value of X-Forwarded-For server header
Returns:
dict:
A dict mapping of user attributes if the application
authentication was successful. See the Crowd
documentation for the authoritative list of attributes.
None: If authentication failed.
"""
params = {
"validationFactors": [
{"name": "remote_address", "value": remote, },
]
}
if proxy:
params["validation-factors"]["validationFactors"].append({"name": "X-Forwarded-For", "value": proxy, })
url = self.rest_url + "/session/%s" % token
response = self._post(url, data=json.dumps(params), params={"expand": "user"})
# For consistency between methods use None rather than False
# If token validation failed for any reason return None
if not response.ok:
return None
# Otherwise return the user object
return response.json()
def terminate_session(self, token):
"""Terminates the session token, effectively logging out the user
from all crowd-enabled services.
Args:
token: The session token.
Returns:
True: If session terminated
None: If session termination failed
"""
url = self.rest_url + "/session/%s" % token
response = self._delete(url)
# For consistency between methods use None rather than False
# If token validation failed for any reason return None
if not response.ok:
return None
# Otherwise return True
return True
def add_user(self, username, raise_on_error=False, **kwargs):
"""Add a user to the directory
Args:
username: The account username
raise_on_error: optional (default: False)
**kwargs: key-value pairs:
password: mandatory
email: mandatory
first_name: optional
last_name: optional
display_name: optional
active: optional (default True)
Returns:
True: Succeeded
False: If unsuccessful
"""
# Check that mandatory elements have been provided
if 'password' not in kwargs:
raise ValueError("missing password")
if 'email' not in kwargs:
raise ValueError("missing email")
# Populate data with default and mandatory values.
# A KeyError means a mandatory value was not provided,
# so raise a ValueError indicating bad args.
try:
data = {
"name": username,
"first-name": username,
"last-name": username,
"display-name": username,
"email": kwargs["email"],
"password": {"value": kwargs["password"]},
"active": True
}
except KeyError:
return ValueError
# Remove special case 'password'
del(kwargs["password"])
# Put values from kwargs into data
for k, v in kwargs.items():
new_k = k.replace("_", "-")
if new_k not in data:
raise ValueError("invalid argument %s" % k)
data[new_k] = v
response = self._post(self.rest_url + "/user",
data=json.dumps(data))
if response.status_code == 201:
return True
if raise_on_error:
raise RuntimeError(response.json()['message'])
return False
def get_user(self, username):
"""Retrieve information about a user
Returns:
dict: User information
None: If no user or failure occurred
"""
response = self._get(self.rest_url + "/user",
params={"username": username,
"expand": "attributes"})
if not response.ok:
return None
return response.json()
def set_active(self, username, active_state):
"""Set the active state of a user
Args:
username: The account username
active_state: True or False
Returns:
True: If successful
None: If no user or failure occurred
"""
if active_state not in (True, False):
raise ValueError("active_state must be True or False")
user = self.get_user(username)
if user is None:
return None
if user['active'] is active_state:
# Already in desired state
return True
user['active'] = active_state
response = self._put(self.rest_url + "/user",
params={"username": username},
data=json.dumps(user))
if response.status_code == 204:
return True
return None
def set_user_attribute(self, username, attribute, value, raise_on_error=False):
"""Set an attribute on a user
:param username: The username on which to set the attribute
:param attribute: The name of the attribute to set
:param value: The value of the attribute to set
:return: True on success, False on failure.
"""
data = {
'attributes': [
{
'name': attribute,
'values': [
value
]
},
]
}
response = self._post(self.rest_url + "/user/attribute",
params={"username": username,},
data=json.dumps(data))
if response.status_code == 204:
return True
if raise_on_error:
raise RuntimeError(response.json()['message'])
return False
def add_user_to_group(self, username, groupname, raise_on_error=False):
"""Add a user to a group
:param username: The username to assign to the group
:param groupname: The group name into which to assign the user
:return: True on success, False on failure.
"""
data = {
'name': groupname,
}
response = self._post(self.rest_url + "/user/group/direct",
params={"username": username,},
data=json.dumps(data))
if response.status_code == 201:
return True
if raise_on_error:
raise RuntimeError(response.json()['message'])
return False
def remove_user_from_group(self, username, groupname, raise_on_error=False):
"""Remove a user from a group
Attempts to remove a user from a group
Args
username: The username to remove from the group.
groupname: The group name to be removed from the user.
Returns:
True: Succeeded
False: If unsuccessful
"""
response = self._delete(self.rest_url + "/group/user/direct",params={"username": username, "groupname": groupname})
if response.status_code == 204:
return True
if raise_on_error:
raise RuntimeError(response.json()['message'])
return False
def change_password(self, username, newpassword, raise_on_error=False):
"""Change new password for a user
Args:
username: The account username.
newpassword: The account new password.
raise_on_error: optional (default: False)
Returns:
True: Succeeded
False: If unsuccessful
"""
response = self._put(self.rest_url + "/user/password",
data=json.dumps({"value": newpassword}),
params={"username": username})
if response.ok:
return True
if raise_on_error:
raise RuntimeError(response.json()['message'])
return False
def send_password_reset_link(self, username):
"""Sends the user a password reset link (by email)
Args:
username: The account username.
Returns:
True: Succeeded
False: If unsuccessful
"""
response = self._post(self.rest_url + "/user/mail/password",
params={"username": username})
if response.ok:
return True
return False
def get_groups(self, username):
"""Retrieves a list of group names that have <username> as a direct member.
Returns:
list:
A list of strings of group names.
"""
response = self._get(self.rest_url + "/user/group/direct",
params={"username": username})
if not response.ok:
return None
return [g['name'] for g in response.json()['groups']]
def get_nested_groups(self, username):
"""Retrieve a list of all group names that have <username> as a direct or indirect member.
Args:
username: The account username.
Returns:
list:
A list of strings of group names.
"""
response = self._get(self.rest_url + "/user/group/nested",
params={"username": username})
if not response.ok:
return None
return [g['name'] for g in response.json()['groups']]
def get_nested_group_users(self, groupname):
"""Retrieves a list of all users that directly or indirectly belong to the given groupname.
Args:
groupname: The group name.
Returns:
list:
A list of strings of user names.
"""
response = self._get(self.rest_url + "/group/user/nested",
params={"groupname": groupname,
"start-index": 0,
"max-results": 99999})
if not response.ok:
return None
return [u['name'] for u in response.json()['users']]
def get_memberships(self):
"""Fetches all group memberships.
Returns:
dict:
key: group name
value: (array of users, array of groups)
"""
response = self._get_xml(self.rest_url + "/group/membership")
if not response.ok:
return None
xmltree = etree.fromstring(response.content)
memberships = {}
for mg in xmltree.findall('membership'):
# coerce values to unicode in a python 2 and 3 compatible way
group = u'{}'.format(mg.get('group'))
users = [u'{}'.format(u.get('name')) for u in mg.find('users').findall('user')]
groups = [u'{}'.format(g.get('name')) for g in mg.find('groups').findall('group')]
memberships[group] = {u'users': users, u'groups': groups}
return memberships
def search(self, entity_type, property_name, search_string, start_index=0, max_results=99999):
"""Performs a user search using the Crowd search API.
https://developer.atlassian.com/display/CROWDDEV/Crowd+REST+Resources#CrowdRESTResources-SearchResource
Args:
entity_type: 'user' or 'group'
property_name: eg. 'email', 'name'
search_string: the string to search for.
start_index: starting index of the results (default: 0)
max_results: maximum number of results returned (default: 99999)
Returns:
json results:
Returns search results.
"""
params = {
"entity-type": entity_type,
"expand": entity_type,
"property-search-restriction": {
"property": {"name": property_name, "type": "STRING"},
"match-mode": "CONTAINS",
"value": search_string,
}
}
params = {
'entity-type': entity_type,
'expand': entity_type,
'start-index': start_index,
'max-results': max_results
}
# Construct XML payload of the form:
# <property-search-restriction>
# <property>
# <name>email</name>
# <type>STRING</type>
# </property>
# <match-mode>EXACTLY_MATCHES</match-mode>
# <value>bob@example.net</value>
# </property-search-restriction>
root = etree.Element('property-search-restriction')
property_ = etree.Element('property')
prop_name = etree.Element('name')
prop_name.text = property_name
property_.append(prop_name)
prop_type = etree.Element('type')
prop_type.text = 'STRING'
property_.append(prop_type)
root.append(property_)
match_mode = etree.Element('match-mode')
match_mode.text = 'CONTAINS'
root.append(match_mode)
value = etree.Element('value')
value.text = search_string
root.append(value)
# Construct the XML payload expected by search API
payload = '<?xml version="1.0" encoding="UTF-8"?>\n' + etree.tostring(root).decode('utf-8')
# We're sending XML but would like a JSON response
session = self._build_session(content_type='xml')
session.headers.update({'Accept': 'application/json'})
response = session.post(self.rest_url + "/search", params=params, data=payload, timeout=self.timeout)
if not response.ok:
return None
return response.json()
|
pycontribs/python-crowd | crowd.py | CrowdServer.get_memberships | python | def get_memberships(self):
response = self._get_xml(self.rest_url + "/group/membership")
if not response.ok:
return None
xmltree = etree.fromstring(response.content)
memberships = {}
for mg in xmltree.findall('membership'):
# coerce values to unicode in a python 2 and 3 compatible way
group = u'{}'.format(mg.get('group'))
users = [u'{}'.format(u.get('name')) for u in mg.find('users').findall('user')]
groups = [u'{}'.format(g.get('name')) for g in mg.find('groups').findall('group')]
memberships[group] = {u'users': users, u'groups': groups}
return memberships | Fetches all group memberships.
Returns:
dict:
key: group name
value: (array of users, array of groups) | train | https://github.com/pycontribs/python-crowd/blob/a075e45774dd5baecf0217843cda747084268e32/crowd.py#L631-L653 | [
"def _get_xml(self, *args, **kwargs):\n \"\"\"Wrapper around Requests for GET XML requests\n\n Returns:\n Response:\n A Requests Response object\n \"\"\"\n req = self.session_xml.get(*args, **kwargs)\n return req\n"
] | class CrowdServer(object):
"""Crowd server authentication object.
This is a Crowd authentication class to be configured for a
particular application (app_name) to authenticate users
against a Crowd server (crowd_url).
This module uses the Crowd JSON API for talking to Crowd.
An application account must be configured in the Crowd server
and permitted to authenticate users against one or more user
directories prior to using this module.
Please see the Crowd documentation for information about
configuring additional applications to talk to Crowd.
The ``ssl_verify`` parameter controls how and if certificates are verified.
If ``True``, the SSL certificate will be verified.
A CA_BUNDLE path can also be provided.
The ``client_cert`` tuple (cert,key) specifies a SSL client certificate and key files.
"""
def __init__(self, crowd_url, app_name, app_pass, ssl_verify=True,
timeout=None, client_cert=None):
self.crowd_url = crowd_url
self.app_name = app_name
self.app_pass = app_pass
self.rest_url = crowd_url.rstrip("/") + "/rest/usermanagement/1"
self.ssl_verify = ssl_verify
self.client_cert = client_cert
self.timeout = timeout
self.session = self._build_session(content_type='json')
self.session_xml = self._build_session(content_type='xml')
def __str__(self):
return "Crowd Server at %s" % self.crowd_url
def __repr__(self):
return "<CrowdServer('%s', '%s', '%s')>" % \
(self.crowd_url, self.app_name, self.app_pass)
def _build_session(self, content_type='json'):
headers = {
'Content-Type': 'application/{}'.format(content_type),
'Accept': 'application/{}'.format(content_type),
}
session = requests.Session()
session.verify = self.ssl_verify
session.cert = self.client_cert
session.auth = requests.auth.HTTPBasicAuth(self.app_name, self.app_pass)
session.headers.update(headers)
return session
def _get(self, *args, **kwargs):
"""Wrapper around Requests for GET requests
Returns:
Response:
A Requests Response object
"""
if 'timeout' not in kwargs:
kwargs['timeout'] = self.timeout
req = self.session.get(*args, **kwargs)
return req
def _get_xml(self, *args, **kwargs):
"""Wrapper around Requests for GET XML requests
Returns:
Response:
A Requests Response object
"""
req = self.session_xml.get(*args, **kwargs)
return req
def _post(self, *args, **kwargs):
"""Wrapper around Requests for POST requests
Returns:
Response:
A Requests Response object
"""
if 'timeout' not in kwargs:
kwargs['timeout'] = self.timeout
req = self.session.post(*args, **kwargs)
return req
def _post_xml(self, *args, **kwargs):
"""Wrapper around Requests for POST requests
Returns:
Response:
A Requests Response object
"""
if 'timeout' not in kwargs:
kwargs['timeout'] = self.timeout
req = self.session_xml.post(*args, **kwargs)
return req
def _put(self, *args, **kwargs):
"""Wrapper around Requests for PUT requests
Returns:
Response:
A Requests Response object
"""
if 'timeout' not in kwargs:
kwargs['timeout'] = self.timeout
req = self.session.put(*args, **kwargs)
return req
def _delete(self, *args, **kwargs):
"""Wrapper around Requests for DELETE requests
Returns:
Response:
A Requests Response object
"""
if 'timeout' not in kwargs:
kwargs['timeout'] = self.timeout
req = self.session.delete(*args, **kwargs)
return req
def auth_ping(self):
"""Test that application can authenticate to Crowd.
Attempts to authenticate the application user against
the Crowd server. In order for user authentication to
work, an application must be able to authenticate.
Returns:
bool:
True if the application authentication succeeded.
"""
url = self.rest_url + "/non-existent/location"
response = self._get(url)
if response.status_code == 401:
return False
elif response.status_code == 404:
return True
else:
# An error encountered - problem with the Crowd server?
return False
def auth_user(self, username, password):
"""Authenticate a user account against the Crowd server.
Attempts to authenticate the user against the Crowd server.
Args:
username: The account username.
password: The account password.
Returns:
dict:
A dict mapping of user attributes if the application
authentication was successful. See the Crowd documentation
for the authoritative list of attributes.
None: If authentication failed.
"""
response = self._post(self.rest_url + "/authentication",
data=json.dumps({"value": password}),
params={"username": username})
# If authentication failed for any reason return None
if not response.ok:
return None
# ...otherwise return a dictionary of user attributes
return response.json()
def get_session(self, username, password, remote="127.0.0.1", proxy=None):
"""Create a session for a user.
Attempts to create a user session on the Crowd server.
Args:
username: The account username.
password: The account password.
remote:
The remote address of the user. This can be used
to create multiple concurrent sessions for a user.
The host you run this program on may need to be configured
in Crowd as a trusted proxy for this to work.
proxy: Value of X-Forwarded-For server header.
Returns:
dict:
A dict mapping of user attributes if the application
authentication was successful. See the Crowd
documentation for the authoritative list of attributes.
None: If authentication failed.
"""
params = {
"username": username,
"password": password,
"validation-factors": {
"validationFactors": [
{"name": "remote_address", "value": remote, },
]
}
}
if proxy:
params["validation-factors"]["validationFactors"].append({"name": "X-Forwarded-For", "value": proxy, })
response = self._post(self.rest_url + "/session",
data=json.dumps(params),
params={"expand": "user"})
# If authentication failed for any reason return None
if not response.ok:
return None
# Otherwise return the user object
return response.json()
def validate_session(self, token, remote="127.0.0.1", proxy=None):
"""Validate a session token.
Validate a previously acquired session token against the
Crowd server. This may be a token provided by a user from
a http cookie or by some other means.
Args:
token: The session token.
remote: The remote address of the user.
proxy: Value of X-Forwarded-For server header
Returns:
dict:
A dict mapping of user attributes if the application
authentication was successful. See the Crowd
documentation for the authoritative list of attributes.
None: If authentication failed.
"""
params = {
"validationFactors": [
{"name": "remote_address", "value": remote, },
]
}
if proxy:
params["validation-factors"]["validationFactors"].append({"name": "X-Forwarded-For", "value": proxy, })
url = self.rest_url + "/session/%s" % token
response = self._post(url, data=json.dumps(params), params={"expand": "user"})
# For consistency between methods use None rather than False
# If token validation failed for any reason return None
if not response.ok:
return None
# Otherwise return the user object
return response.json()
def terminate_session(self, token):
"""Terminates the session token, effectively logging out the user
from all crowd-enabled services.
Args:
token: The session token.
Returns:
True: If session terminated
None: If session termination failed
"""
url = self.rest_url + "/session/%s" % token
response = self._delete(url)
# For consistency between methods use None rather than False
# If token validation failed for any reason return None
if not response.ok:
return None
# Otherwise return True
return True
def add_user(self, username, raise_on_error=False, **kwargs):
"""Add a user to the directory
Args:
username: The account username
raise_on_error: optional (default: False)
**kwargs: key-value pairs:
password: mandatory
email: mandatory
first_name: optional
last_name: optional
display_name: optional
active: optional (default True)
Returns:
True: Succeeded
False: If unsuccessful
"""
# Check that mandatory elements have been provided
if 'password' not in kwargs:
raise ValueError("missing password")
if 'email' not in kwargs:
raise ValueError("missing email")
# Populate data with default and mandatory values.
# A KeyError means a mandatory value was not provided,
# so raise a ValueError indicating bad args.
try:
data = {
"name": username,
"first-name": username,
"last-name": username,
"display-name": username,
"email": kwargs["email"],
"password": {"value": kwargs["password"]},
"active": True
}
except KeyError:
return ValueError
# Remove special case 'password'
del(kwargs["password"])
# Put values from kwargs into data
for k, v in kwargs.items():
new_k = k.replace("_", "-")
if new_k not in data:
raise ValueError("invalid argument %s" % k)
data[new_k] = v
response = self._post(self.rest_url + "/user",
data=json.dumps(data))
if response.status_code == 201:
return True
if raise_on_error:
raise RuntimeError(response.json()['message'])
return False
def get_user(self, username):
"""Retrieve information about a user
Returns:
dict: User information
None: If no user or failure occurred
"""
response = self._get(self.rest_url + "/user",
params={"username": username,
"expand": "attributes"})
if not response.ok:
return None
return response.json()
def set_active(self, username, active_state):
"""Set the active state of a user
Args:
username: The account username
active_state: True or False
Returns:
True: If successful
None: If no user or failure occurred
"""
if active_state not in (True, False):
raise ValueError("active_state must be True or False")
user = self.get_user(username)
if user is None:
return None
if user['active'] is active_state:
# Already in desired state
return True
user['active'] = active_state
response = self._put(self.rest_url + "/user",
params={"username": username},
data=json.dumps(user))
if response.status_code == 204:
return True
return None
def set_user_attribute(self, username, attribute, value, raise_on_error=False):
"""Set an attribute on a user
:param username: The username on which to set the attribute
:param attribute: The name of the attribute to set
:param value: The value of the attribute to set
:return: True on success, False on failure.
"""
data = {
'attributes': [
{
'name': attribute,
'values': [
value
]
},
]
}
response = self._post(self.rest_url + "/user/attribute",
params={"username": username,},
data=json.dumps(data))
if response.status_code == 204:
return True
if raise_on_error:
raise RuntimeError(response.json()['message'])
return False
def add_user_to_group(self, username, groupname, raise_on_error=False):
"""Add a user to a group
:param username: The username to assign to the group
:param groupname: The group name into which to assign the user
:return: True on success, False on failure.
"""
data = {
'name': groupname,
}
response = self._post(self.rest_url + "/user/group/direct",
params={"username": username,},
data=json.dumps(data))
if response.status_code == 201:
return True
if raise_on_error:
raise RuntimeError(response.json()['message'])
return False
def remove_user_from_group(self, username, groupname, raise_on_error=False):
"""Remove a user from a group
Attempts to remove a user from a group
Args
username: The username to remove from the group.
groupname: The group name to be removed from the user.
Returns:
True: Succeeded
False: If unsuccessful
"""
response = self._delete(self.rest_url + "/group/user/direct",params={"username": username, "groupname": groupname})
if response.status_code == 204:
return True
if raise_on_error:
raise RuntimeError(response.json()['message'])
return False
def change_password(self, username, newpassword, raise_on_error=False):
"""Change new password for a user
Args:
username: The account username.
newpassword: The account new password.
raise_on_error: optional (default: False)
Returns:
True: Succeeded
False: If unsuccessful
"""
response = self._put(self.rest_url + "/user/password",
data=json.dumps({"value": newpassword}),
params={"username": username})
if response.ok:
return True
if raise_on_error:
raise RuntimeError(response.json()['message'])
return False
def send_password_reset_link(self, username):
"""Sends the user a password reset link (by email)
Args:
username: The account username.
Returns:
True: Succeeded
False: If unsuccessful
"""
response = self._post(self.rest_url + "/user/mail/password",
params={"username": username})
if response.ok:
return True
return False
def get_groups(self, username):
"""Retrieves a list of group names that have <username> as a direct member.
Returns:
list:
A list of strings of group names.
"""
response = self._get(self.rest_url + "/user/group/direct",
params={"username": username})
if not response.ok:
return None
return [g['name'] for g in response.json()['groups']]
def get_nested_groups(self, username):
"""Retrieve a list of all group names that have <username> as a direct or indirect member.
Args:
username: The account username.
Returns:
list:
A list of strings of group names.
"""
response = self._get(self.rest_url + "/user/group/nested",
params={"username": username})
if not response.ok:
return None
return [g['name'] for g in response.json()['groups']]
def get_nested_group_users(self, groupname):
"""Retrieves a list of all users that directly or indirectly belong to the given groupname.
Args:
groupname: The group name.
Returns:
list:
A list of strings of user names.
"""
response = self._get(self.rest_url + "/group/user/nested",
params={"groupname": groupname,
"start-index": 0,
"max-results": 99999})
if not response.ok:
return None
return [u['name'] for u in response.json()['users']]
def user_exists(self, username):
"""Determines if the user exists.
Args:
username: The user name.
Returns:
bool:
True if the user exists in the Crowd application.
"""
response = self._get(self.rest_url + "/user",
params={"username": username})
if not response.ok:
return None
return True
def search(self, entity_type, property_name, search_string, start_index=0, max_results=99999):
"""Performs a user search using the Crowd search API.
https://developer.atlassian.com/display/CROWDDEV/Crowd+REST+Resources#CrowdRESTResources-SearchResource
Args:
entity_type: 'user' or 'group'
property_name: eg. 'email', 'name'
search_string: the string to search for.
start_index: starting index of the results (default: 0)
max_results: maximum number of results returned (default: 99999)
Returns:
json results:
Returns search results.
"""
params = {
"entity-type": entity_type,
"expand": entity_type,
"property-search-restriction": {
"property": {"name": property_name, "type": "STRING"},
"match-mode": "CONTAINS",
"value": search_string,
}
}
params = {
'entity-type': entity_type,
'expand': entity_type,
'start-index': start_index,
'max-results': max_results
}
# Construct XML payload of the form:
# <property-search-restriction>
# <property>
# <name>email</name>
# <type>STRING</type>
# </property>
# <match-mode>EXACTLY_MATCHES</match-mode>
# <value>bob@example.net</value>
# </property-search-restriction>
root = etree.Element('property-search-restriction')
property_ = etree.Element('property')
prop_name = etree.Element('name')
prop_name.text = property_name
property_.append(prop_name)
prop_type = etree.Element('type')
prop_type.text = 'STRING'
property_.append(prop_type)
root.append(property_)
match_mode = etree.Element('match-mode')
match_mode.text = 'CONTAINS'
root.append(match_mode)
value = etree.Element('value')
value.text = search_string
root.append(value)
# Construct the XML payload expected by search API
payload = '<?xml version="1.0" encoding="UTF-8"?>\n' + etree.tostring(root).decode('utf-8')
# We're sending XML but would like a JSON response
session = self._build_session(content_type='xml')
session.headers.update({'Accept': 'application/json'})
response = session.post(self.rest_url + "/search", params=params, data=payload, timeout=self.timeout)
if not response.ok:
return None
return response.json()
|
pycontribs/python-crowd | crowd.py | CrowdServer.search | python | def search(self, entity_type, property_name, search_string, start_index=0, max_results=99999):
params = {
"entity-type": entity_type,
"expand": entity_type,
"property-search-restriction": {
"property": {"name": property_name, "type": "STRING"},
"match-mode": "CONTAINS",
"value": search_string,
}
}
params = {
'entity-type': entity_type,
'expand': entity_type,
'start-index': start_index,
'max-results': max_results
}
# Construct XML payload of the form:
# <property-search-restriction>
# <property>
# <name>email</name>
# <type>STRING</type>
# </property>
# <match-mode>EXACTLY_MATCHES</match-mode>
# <value>bob@example.net</value>
# </property-search-restriction>
root = etree.Element('property-search-restriction')
property_ = etree.Element('property')
prop_name = etree.Element('name')
prop_name.text = property_name
property_.append(prop_name)
prop_type = etree.Element('type')
prop_type.text = 'STRING'
property_.append(prop_type)
root.append(property_)
match_mode = etree.Element('match-mode')
match_mode.text = 'CONTAINS'
root.append(match_mode)
value = etree.Element('value')
value.text = search_string
root.append(value)
# Construct the XML payload expected by search API
payload = '<?xml version="1.0" encoding="UTF-8"?>\n' + etree.tostring(root).decode('utf-8')
# We're sending XML but would like a JSON response
session = self._build_session(content_type='xml')
session.headers.update({'Accept': 'application/json'})
response = session.post(self.rest_url + "/search", params=params, data=payload, timeout=self.timeout)
if not response.ok:
return None
return response.json() | Performs a user search using the Crowd search API.
https://developer.atlassian.com/display/CROWDDEV/Crowd+REST+Resources#CrowdRESTResources-SearchResource
Args:
entity_type: 'user' or 'group'
property_name: eg. 'email', 'name'
search_string: the string to search for.
start_index: starting index of the results (default: 0)
max_results: maximum number of results returned (default: 99999)
Returns:
json results:
Returns search results. | train | https://github.com/pycontribs/python-crowd/blob/a075e45774dd5baecf0217843cda747084268e32/crowd.py#L655-L728 | [
"def _build_session(self, content_type='json'):\n headers = {\n 'Content-Type': 'application/{}'.format(content_type),\n 'Accept': 'application/{}'.format(content_type),\n }\n session = requests.Session()\n session.verify = self.ssl_verify\n session.cert = self.client_cert\n session.... | class CrowdServer(object):
"""Crowd server authentication object.
This is a Crowd authentication class to be configured for a
particular application (app_name) to authenticate users
against a Crowd server (crowd_url).
This module uses the Crowd JSON API for talking to Crowd.
An application account must be configured in the Crowd server
and permitted to authenticate users against one or more user
directories prior to using this module.
Please see the Crowd documentation for information about
configuring additional applications to talk to Crowd.
The ``ssl_verify`` parameter controls how and if certificates are verified.
If ``True``, the SSL certificate will be verified.
A CA_BUNDLE path can also be provided.
The ``client_cert`` tuple (cert,key) specifies a SSL client certificate and key files.
"""
def __init__(self, crowd_url, app_name, app_pass, ssl_verify=True,
timeout=None, client_cert=None):
self.crowd_url = crowd_url
self.app_name = app_name
self.app_pass = app_pass
self.rest_url = crowd_url.rstrip("/") + "/rest/usermanagement/1"
self.ssl_verify = ssl_verify
self.client_cert = client_cert
self.timeout = timeout
self.session = self._build_session(content_type='json')
self.session_xml = self._build_session(content_type='xml')
def __str__(self):
return "Crowd Server at %s" % self.crowd_url
def __repr__(self):
return "<CrowdServer('%s', '%s', '%s')>" % \
(self.crowd_url, self.app_name, self.app_pass)
def _build_session(self, content_type='json'):
headers = {
'Content-Type': 'application/{}'.format(content_type),
'Accept': 'application/{}'.format(content_type),
}
session = requests.Session()
session.verify = self.ssl_verify
session.cert = self.client_cert
session.auth = requests.auth.HTTPBasicAuth(self.app_name, self.app_pass)
session.headers.update(headers)
return session
def _get(self, *args, **kwargs):
"""Wrapper around Requests for GET requests
Returns:
Response:
A Requests Response object
"""
if 'timeout' not in kwargs:
kwargs['timeout'] = self.timeout
req = self.session.get(*args, **kwargs)
return req
def _get_xml(self, *args, **kwargs):
"""Wrapper around Requests for GET XML requests
Returns:
Response:
A Requests Response object
"""
req = self.session_xml.get(*args, **kwargs)
return req
def _post(self, *args, **kwargs):
"""Wrapper around Requests for POST requests
Returns:
Response:
A Requests Response object
"""
if 'timeout' not in kwargs:
kwargs['timeout'] = self.timeout
req = self.session.post(*args, **kwargs)
return req
def _post_xml(self, *args, **kwargs):
"""Wrapper around Requests for POST requests
Returns:
Response:
A Requests Response object
"""
if 'timeout' not in kwargs:
kwargs['timeout'] = self.timeout
req = self.session_xml.post(*args, **kwargs)
return req
def _put(self, *args, **kwargs):
"""Wrapper around Requests for PUT requests
Returns:
Response:
A Requests Response object
"""
if 'timeout' not in kwargs:
kwargs['timeout'] = self.timeout
req = self.session.put(*args, **kwargs)
return req
def _delete(self, *args, **kwargs):
"""Wrapper around Requests for DELETE requests
Returns:
Response:
A Requests Response object
"""
if 'timeout' not in kwargs:
kwargs['timeout'] = self.timeout
req = self.session.delete(*args, **kwargs)
return req
def auth_ping(self):
"""Test that application can authenticate to Crowd.
Attempts to authenticate the application user against
the Crowd server. In order for user authentication to
work, an application must be able to authenticate.
Returns:
bool:
True if the application authentication succeeded.
"""
url = self.rest_url + "/non-existent/location"
response = self._get(url)
if response.status_code == 401:
return False
elif response.status_code == 404:
return True
else:
# An error encountered - problem with the Crowd server?
return False
def auth_user(self, username, password):
"""Authenticate a user account against the Crowd server.
Attempts to authenticate the user against the Crowd server.
Args:
username: The account username.
password: The account password.
Returns:
dict:
A dict mapping of user attributes if the application
authentication was successful. See the Crowd documentation
for the authoritative list of attributes.
None: If authentication failed.
"""
response = self._post(self.rest_url + "/authentication",
data=json.dumps({"value": password}),
params={"username": username})
# If authentication failed for any reason return None
if not response.ok:
return None
# ...otherwise return a dictionary of user attributes
return response.json()
def get_session(self, username, password, remote="127.0.0.1", proxy=None):
"""Create a session for a user.
Attempts to create a user session on the Crowd server.
Args:
username: The account username.
password: The account password.
remote:
The remote address of the user. This can be used
to create multiple concurrent sessions for a user.
The host you run this program on may need to be configured
in Crowd as a trusted proxy for this to work.
proxy: Value of X-Forwarded-For server header.
Returns:
dict:
A dict mapping of user attributes if the application
authentication was successful. See the Crowd
documentation for the authoritative list of attributes.
None: If authentication failed.
"""
params = {
"username": username,
"password": password,
"validation-factors": {
"validationFactors": [
{"name": "remote_address", "value": remote, },
]
}
}
if proxy:
params["validation-factors"]["validationFactors"].append({"name": "X-Forwarded-For", "value": proxy, })
response = self._post(self.rest_url + "/session",
data=json.dumps(params),
params={"expand": "user"})
# If authentication failed for any reason return None
if not response.ok:
return None
# Otherwise return the user object
return response.json()
def validate_session(self, token, remote="127.0.0.1", proxy=None):
"""Validate a session token.
Validate a previously acquired session token against the
Crowd server. This may be a token provided by a user from
a http cookie or by some other means.
Args:
token: The session token.
remote: The remote address of the user.
proxy: Value of X-Forwarded-For server header
Returns:
dict:
A dict mapping of user attributes if the application
authentication was successful. See the Crowd
documentation for the authoritative list of attributes.
None: If authentication failed.
"""
params = {
"validationFactors": [
{"name": "remote_address", "value": remote, },
]
}
if proxy:
params["validation-factors"]["validationFactors"].append({"name": "X-Forwarded-For", "value": proxy, })
url = self.rest_url + "/session/%s" % token
response = self._post(url, data=json.dumps(params), params={"expand": "user"})
# For consistency between methods use None rather than False
# If token validation failed for any reason return None
if not response.ok:
return None
# Otherwise return the user object
return response.json()
def terminate_session(self, token):
"""Terminates the session token, effectively logging out the user
from all crowd-enabled services.
Args:
token: The session token.
Returns:
True: If session terminated
None: If session termination failed
"""
url = self.rest_url + "/session/%s" % token
response = self._delete(url)
# For consistency between methods use None rather than False
# If token validation failed for any reason return None
if not response.ok:
return None
# Otherwise return True
return True
def add_user(self, username, raise_on_error=False, **kwargs):
"""Add a user to the directory
Args:
username: The account username
raise_on_error: optional (default: False)
**kwargs: key-value pairs:
password: mandatory
email: mandatory
first_name: optional
last_name: optional
display_name: optional
active: optional (default True)
Returns:
True: Succeeded
False: If unsuccessful
"""
# Check that mandatory elements have been provided
if 'password' not in kwargs:
raise ValueError("missing password")
if 'email' not in kwargs:
raise ValueError("missing email")
# Populate data with default and mandatory values.
# A KeyError means a mandatory value was not provided,
# so raise a ValueError indicating bad args.
try:
data = {
"name": username,
"first-name": username,
"last-name": username,
"display-name": username,
"email": kwargs["email"],
"password": {"value": kwargs["password"]},
"active": True
}
except KeyError:
return ValueError
# Remove special case 'password'
del(kwargs["password"])
# Put values from kwargs into data
for k, v in kwargs.items():
new_k = k.replace("_", "-")
if new_k not in data:
raise ValueError("invalid argument %s" % k)
data[new_k] = v
response = self._post(self.rest_url + "/user",
data=json.dumps(data))
if response.status_code == 201:
return True
if raise_on_error:
raise RuntimeError(response.json()['message'])
return False
def get_user(self, username):
"""Retrieve information about a user
Returns:
dict: User information
None: If no user or failure occurred
"""
response = self._get(self.rest_url + "/user",
params={"username": username,
"expand": "attributes"})
if not response.ok:
return None
return response.json()
def set_active(self, username, active_state):
"""Set the active state of a user
Args:
username: The account username
active_state: True or False
Returns:
True: If successful
None: If no user or failure occurred
"""
if active_state not in (True, False):
raise ValueError("active_state must be True or False")
user = self.get_user(username)
if user is None:
return None
if user['active'] is active_state:
# Already in desired state
return True
user['active'] = active_state
response = self._put(self.rest_url + "/user",
params={"username": username},
data=json.dumps(user))
if response.status_code == 204:
return True
return None
def set_user_attribute(self, username, attribute, value, raise_on_error=False):
"""Set an attribute on a user
:param username: The username on which to set the attribute
:param attribute: The name of the attribute to set
:param value: The value of the attribute to set
:return: True on success, False on failure.
"""
data = {
'attributes': [
{
'name': attribute,
'values': [
value
]
},
]
}
response = self._post(self.rest_url + "/user/attribute",
params={"username": username,},
data=json.dumps(data))
if response.status_code == 204:
return True
if raise_on_error:
raise RuntimeError(response.json()['message'])
return False
def add_user_to_group(self, username, groupname, raise_on_error=False):
"""Add a user to a group
:param username: The username to assign to the group
:param groupname: The group name into which to assign the user
:return: True on success, False on failure.
"""
data = {
'name': groupname,
}
response = self._post(self.rest_url + "/user/group/direct",
params={"username": username,},
data=json.dumps(data))
if response.status_code == 201:
return True
if raise_on_error:
raise RuntimeError(response.json()['message'])
return False
def remove_user_from_group(self, username, groupname, raise_on_error=False):
"""Remove a user from a group
Attempts to remove a user from a group
Args
username: The username to remove from the group.
groupname: The group name to be removed from the user.
Returns:
True: Succeeded
False: If unsuccessful
"""
response = self._delete(self.rest_url + "/group/user/direct",params={"username": username, "groupname": groupname})
if response.status_code == 204:
return True
if raise_on_error:
raise RuntimeError(response.json()['message'])
return False
def change_password(self, username, newpassword, raise_on_error=False):
"""Change new password for a user
Args:
username: The account username.
newpassword: The account new password.
raise_on_error: optional (default: False)
Returns:
True: Succeeded
False: If unsuccessful
"""
response = self._put(self.rest_url + "/user/password",
data=json.dumps({"value": newpassword}),
params={"username": username})
if response.ok:
return True
if raise_on_error:
raise RuntimeError(response.json()['message'])
return False
def send_password_reset_link(self, username):
"""Sends the user a password reset link (by email)
Args:
username: The account username.
Returns:
True: Succeeded
False: If unsuccessful
"""
response = self._post(self.rest_url + "/user/mail/password",
params={"username": username})
if response.ok:
return True
return False
def get_groups(self, username):
"""Retrieves a list of group names that have <username> as a direct member.
Returns:
list:
A list of strings of group names.
"""
response = self._get(self.rest_url + "/user/group/direct",
params={"username": username})
if not response.ok:
return None
return [g['name'] for g in response.json()['groups']]
def get_nested_groups(self, username):
"""Retrieve a list of all group names that have <username> as a direct or indirect member.
Args:
username: The account username.
Returns:
list:
A list of strings of group names.
"""
response = self._get(self.rest_url + "/user/group/nested",
params={"username": username})
if not response.ok:
return None
return [g['name'] for g in response.json()['groups']]
def get_nested_group_users(self, groupname):
"""Retrieves a list of all users that directly or indirectly belong to the given groupname.
Args:
groupname: The group name.
Returns:
list:
A list of strings of user names.
"""
response = self._get(self.rest_url + "/group/user/nested",
params={"groupname": groupname,
"start-index": 0,
"max-results": 99999})
if not response.ok:
return None
return [u['name'] for u in response.json()['users']]
def user_exists(self, username):
"""Determines if the user exists.
Args:
username: The user name.
Returns:
bool:
True if the user exists in the Crowd application.
"""
response = self._get(self.rest_url + "/user",
params={"username": username})
if not response.ok:
return None
return True
def get_memberships(self):
"""Fetches all group memberships.
Returns:
dict:
key: group name
value: (array of users, array of groups)
"""
response = self._get_xml(self.rest_url + "/group/membership")
if not response.ok:
return None
xmltree = etree.fromstring(response.content)
memberships = {}
for mg in xmltree.findall('membership'):
# coerce values to unicode in a python 2 and 3 compatible way
group = u'{}'.format(mg.get('group'))
users = [u'{}'.format(u.get('name')) for u in mg.find('users').findall('user')]
groups = [u'{}'.format(g.get('name')) for g in mg.find('groups').findall('group')]
memberships[group] = {u'users': users, u'groups': groups}
return memberships
|
aconrad/pycobertura | pycobertura/cobertura.py | Cobertura.line_rate | python | def line_rate(self, filename=None):
if filename is None:
el = self.xml
else:
el = self._get_class_element_by_filename(filename)
return float(el.attrib['line-rate']) | Return the global line rate of the coverage report. If the
`filename` file is given, return the line rate of the file. | train | https://github.com/aconrad/pycobertura/blob/26e472f1424f5cd499c42232dc5ee12e4042806f/pycobertura/cobertura.py#L93-L103 | null | class Cobertura(object):
"""
An XML Cobertura parser.
"""
def __init__(self, report, source=None, source_prefix=None):
"""
Initialize a Cobertura report given a coverage report `report`. It can
be either a file object or the path to an XML file that is in the
Cobertura format.
The optional argument `source` is the location of the source code
provided as a directory path or a file object zip archive containing
the source code.
The optional argument `source_prefix` will be used to lookup source
files if a zip archive is provided and will be prepended to filenames
found in the coverage report.
"""
self.xml = ET.parse(report).getroot()
if source is None:
if isinstance(report, basestring):
# get the directory in which the coverage file lives
source = os.path.dirname(report)
self.filesystem = DirectoryFileSystem(
source, source_prefix=source_prefix
)
elif zipfile.is_zipfile(source):
self.filesystem = ZipFileSystem(
source, source_prefix=source_prefix
)
else:
self.filesystem = DirectoryFileSystem(
source, source_prefix=source_prefix
)
@memoize
def _get_class_element_by_filename(self, filename):
syntax = "./packages//class[@filename='%s'][1]" % (
filename
)
return self.xml.xpath(syntax)[0]
@memoize
def _get_lines_by_filename(self, filename):
el = self._get_class_element_by_filename(filename)
return el.xpath('./lines/line')
@property
def version(self):
"""Return the version number of the coverage report."""
return self.xml.attrib['version']
def branch_rate(self, filename=None):
"""
Return the global branch rate of the coverage report. If the
`filename` file is given, return the branch rate of the file.
"""
if filename is None:
el = self.xml
else:
el = self._get_class_element_by_filename(filename)
return float(el.attrib['branch-rate'])
@memoize
def missed_statements(self, filename):
"""
Return a list of uncovered line numbers for each of the missed
statements found for the file `filename`.
"""
el = self._get_class_element_by_filename(filename)
lines = el.xpath('./lines/line[@hits=0]')
return [int(l.attrib['number']) for l in lines]
@memoize
def hit_statements(self, filename):
"""
Return a list of covered line numbers for each of the hit statements
found for the file `filename`.
"""
el = self._get_class_element_by_filename(filename)
lines = el.xpath('./lines/line[@hits>0]')
return [int(l.attrib['number']) for l in lines]
def line_statuses(self, filename):
"""
Return a list of tuples `(lineno, status)` of all the lines found in
the Cobertura report for the given file `filename` where `lineno` is
the line number and `status` is coverage status of the line which can
be either `True` (line hit) or `False` (line miss).
"""
line_elements = self._get_lines_by_filename(filename)
lines_w_status = []
for line in line_elements:
lineno = int(line.attrib['number'])
status = line.attrib['hits'] != '0'
lines_w_status.append((lineno, status))
return lines_w_status
def missed_lines(self, filename):
"""
Return a list of extrapolated uncovered line numbers for the
file `filename` according to `Cobertura.line_statuses`.
"""
statuses = self.line_statuses(filename)
statuses = extrapolate_coverage(statuses)
return [lno for lno, status in statuses if status is False]
@memoize
def file_source(self, filename):
"""
Return a list of namedtuple `Line` for each line of code found in the
source file with the given `filename`.
"""
lines = []
try:
with self.filesystem.open(filename) as f:
line_statuses = dict(self.line_statuses(filename))
for lineno, source in enumerate(f, start=1):
line_status = line_statuses.get(lineno)
line = Line(lineno, source, line_status, None)
lines.append(line)
except self.filesystem.FileNotFound as file_not_found:
lines.append(
Line(0, '%s not found' % file_not_found.path, None, None)
)
return lines
def total_misses(self, filename=None):
"""
Return the total number of uncovered statements for the file
`filename`. If `filename` is not given, return the total
number of uncovered statements for all files.
"""
if filename is not None:
return len(self.missed_statements(filename))
total = 0
for filename in self.files():
total += len(self.missed_statements(filename))
return total
def total_hits(self, filename=None):
"""
Return the total number of covered statements for the file
`filename`. If `filename` is not given, return the total
number of covered statements for all files.
"""
if filename is not None:
return len(self.hit_statements(filename))
total = 0
for filename in self.files():
total += len(self.hit_statements(filename))
return total
def total_statements(self, filename=None):
"""
Return the total number of statements for the file
`filename`. If `filename` is not given, return the total
number of statements for all files.
"""
if filename is not None:
statements = self._get_lines_by_filename(filename)
return len(statements)
total = 0
for filename in self.files():
statements = self._get_lines_by_filename(filename)
total += len(statements)
return total
@memoize
def files(self):
"""
Return the list of available files in the coverage report.
"""
# maybe replace with a trie at some point? see has_file FIXME
already_seen = set()
filenames = []
for el in self.xml.xpath("//class"):
filename = el.attrib['filename']
if filename in already_seen:
continue
already_seen.add(filename)
filenames.append(filename)
return filenames
def has_file(self, filename):
"""
Return `True` if the file `filename` is present in the report, return
`False` otherwise.
"""
# FIXME: this will lookup a list which is slow, make it O(1)
return filename in self.files()
@memoize
def source_lines(self, filename):
"""
Return a list for source lines of file `filename`.
"""
with self.filesystem.open(filename) as f:
return f.readlines()
@memoize
def packages(self):
"""
Return the list of available packages in the coverage report.
"""
return [el.attrib['name'] for el in self.xml.xpath("//package")]
|
aconrad/pycobertura | pycobertura/cobertura.py | Cobertura.branch_rate | python | def branch_rate(self, filename=None):
if filename is None:
el = self.xml
else:
el = self._get_class_element_by_filename(filename)
return float(el.attrib['branch-rate']) | Return the global branch rate of the coverage report. If the
`filename` file is given, return the branch rate of the file. | train | https://github.com/aconrad/pycobertura/blob/26e472f1424f5cd499c42232dc5ee12e4042806f/pycobertura/cobertura.py#L105-L115 | null | class Cobertura(object):
"""
An XML Cobertura parser.
"""
def __init__(self, report, source=None, source_prefix=None):
"""
Initialize a Cobertura report given a coverage report `report`. It can
be either a file object or the path to an XML file that is in the
Cobertura format.
The optional argument `source` is the location of the source code
provided as a directory path or a file object zip archive containing
the source code.
The optional argument `source_prefix` will be used to lookup source
files if a zip archive is provided and will be prepended to filenames
found in the coverage report.
"""
self.xml = ET.parse(report).getroot()
if source is None:
if isinstance(report, basestring):
# get the directory in which the coverage file lives
source = os.path.dirname(report)
self.filesystem = DirectoryFileSystem(
source, source_prefix=source_prefix
)
elif zipfile.is_zipfile(source):
self.filesystem = ZipFileSystem(
source, source_prefix=source_prefix
)
else:
self.filesystem = DirectoryFileSystem(
source, source_prefix=source_prefix
)
@memoize
def _get_class_element_by_filename(self, filename):
syntax = "./packages//class[@filename='%s'][1]" % (
filename
)
return self.xml.xpath(syntax)[0]
@memoize
def _get_lines_by_filename(self, filename):
el = self._get_class_element_by_filename(filename)
return el.xpath('./lines/line')
@property
def version(self):
"""Return the version number of the coverage report."""
return self.xml.attrib['version']
def line_rate(self, filename=None):
"""
Return the global line rate of the coverage report. If the
`filename` file is given, return the line rate of the file.
"""
if filename is None:
el = self.xml
else:
el = self._get_class_element_by_filename(filename)
return float(el.attrib['line-rate'])
@memoize
def missed_statements(self, filename):
"""
Return a list of uncovered line numbers for each of the missed
statements found for the file `filename`.
"""
el = self._get_class_element_by_filename(filename)
lines = el.xpath('./lines/line[@hits=0]')
return [int(l.attrib['number']) for l in lines]
@memoize
def hit_statements(self, filename):
"""
Return a list of covered line numbers for each of the hit statements
found for the file `filename`.
"""
el = self._get_class_element_by_filename(filename)
lines = el.xpath('./lines/line[@hits>0]')
return [int(l.attrib['number']) for l in lines]
def line_statuses(self, filename):
"""
Return a list of tuples `(lineno, status)` of all the lines found in
the Cobertura report for the given file `filename` where `lineno` is
the line number and `status` is coverage status of the line which can
be either `True` (line hit) or `False` (line miss).
"""
line_elements = self._get_lines_by_filename(filename)
lines_w_status = []
for line in line_elements:
lineno = int(line.attrib['number'])
status = line.attrib['hits'] != '0'
lines_w_status.append((lineno, status))
return lines_w_status
def missed_lines(self, filename):
"""
Return a list of extrapolated uncovered line numbers for the
file `filename` according to `Cobertura.line_statuses`.
"""
statuses = self.line_statuses(filename)
statuses = extrapolate_coverage(statuses)
return [lno for lno, status in statuses if status is False]
@memoize
def file_source(self, filename):
"""
Return a list of namedtuple `Line` for each line of code found in the
source file with the given `filename`.
"""
lines = []
try:
with self.filesystem.open(filename) as f:
line_statuses = dict(self.line_statuses(filename))
for lineno, source in enumerate(f, start=1):
line_status = line_statuses.get(lineno)
line = Line(lineno, source, line_status, None)
lines.append(line)
except self.filesystem.FileNotFound as file_not_found:
lines.append(
Line(0, '%s not found' % file_not_found.path, None, None)
)
return lines
def total_misses(self, filename=None):
"""
Return the total number of uncovered statements for the file
`filename`. If `filename` is not given, return the total
number of uncovered statements for all files.
"""
if filename is not None:
return len(self.missed_statements(filename))
total = 0
for filename in self.files():
total += len(self.missed_statements(filename))
return total
def total_hits(self, filename=None):
"""
Return the total number of covered statements for the file
`filename`. If `filename` is not given, return the total
number of covered statements for all files.
"""
if filename is not None:
return len(self.hit_statements(filename))
total = 0
for filename in self.files():
total += len(self.hit_statements(filename))
return total
def total_statements(self, filename=None):
"""
Return the total number of statements for the file
`filename`. If `filename` is not given, return the total
number of statements for all files.
"""
if filename is not None:
statements = self._get_lines_by_filename(filename)
return len(statements)
total = 0
for filename in self.files():
statements = self._get_lines_by_filename(filename)
total += len(statements)
return total
@memoize
def files(self):
"""
Return the list of available files in the coverage report.
"""
# maybe replace with a trie at some point? see has_file FIXME
already_seen = set()
filenames = []
for el in self.xml.xpath("//class"):
filename = el.attrib['filename']
if filename in already_seen:
continue
already_seen.add(filename)
filenames.append(filename)
return filenames
def has_file(self, filename):
"""
Return `True` if the file `filename` is present in the report, return
`False` otherwise.
"""
# FIXME: this will lookup a list which is slow, make it O(1)
return filename in self.files()
@memoize
def source_lines(self, filename):
"""
Return a list for source lines of file `filename`.
"""
with self.filesystem.open(filename) as f:
return f.readlines()
@memoize
def packages(self):
"""
Return the list of available packages in the coverage report.
"""
return [el.attrib['name'] for el in self.xml.xpath("//package")]
|
aconrad/pycobertura | pycobertura/cobertura.py | Cobertura.missed_statements | python | def missed_statements(self, filename):
el = self._get_class_element_by_filename(filename)
lines = el.xpath('./lines/line[@hits=0]')
return [int(l.attrib['number']) for l in lines] | Return a list of uncovered line numbers for each of the missed
statements found for the file `filename`. | train | https://github.com/aconrad/pycobertura/blob/26e472f1424f5cd499c42232dc5ee12e4042806f/pycobertura/cobertura.py#L118-L125 | null | class Cobertura(object):
"""
An XML Cobertura parser.
"""
def __init__(self, report, source=None, source_prefix=None):
"""
Initialize a Cobertura report given a coverage report `report`. It can
be either a file object or the path to an XML file that is in the
Cobertura format.
The optional argument `source` is the location of the source code
provided as a directory path or a file object zip archive containing
the source code.
The optional argument `source_prefix` will be used to lookup source
files if a zip archive is provided and will be prepended to filenames
found in the coverage report.
"""
self.xml = ET.parse(report).getroot()
if source is None:
if isinstance(report, basestring):
# get the directory in which the coverage file lives
source = os.path.dirname(report)
self.filesystem = DirectoryFileSystem(
source, source_prefix=source_prefix
)
elif zipfile.is_zipfile(source):
self.filesystem = ZipFileSystem(
source, source_prefix=source_prefix
)
else:
self.filesystem = DirectoryFileSystem(
source, source_prefix=source_prefix
)
@memoize
def _get_class_element_by_filename(self, filename):
syntax = "./packages//class[@filename='%s'][1]" % (
filename
)
return self.xml.xpath(syntax)[0]
@memoize
def _get_lines_by_filename(self, filename):
el = self._get_class_element_by_filename(filename)
return el.xpath('./lines/line')
@property
def version(self):
"""Return the version number of the coverage report."""
return self.xml.attrib['version']
def line_rate(self, filename=None):
"""
Return the global line rate of the coverage report. If the
`filename` file is given, return the line rate of the file.
"""
if filename is None:
el = self.xml
else:
el = self._get_class_element_by_filename(filename)
return float(el.attrib['line-rate'])
def branch_rate(self, filename=None):
"""
Return the global branch rate of the coverage report. If the
`filename` file is given, return the branch rate of the file.
"""
if filename is None:
el = self.xml
else:
el = self._get_class_element_by_filename(filename)
return float(el.attrib['branch-rate'])
@memoize
@memoize
def hit_statements(self, filename):
"""
Return a list of covered line numbers for each of the hit statements
found for the file `filename`.
"""
el = self._get_class_element_by_filename(filename)
lines = el.xpath('./lines/line[@hits>0]')
return [int(l.attrib['number']) for l in lines]
def line_statuses(self, filename):
"""
Return a list of tuples `(lineno, status)` of all the lines found in
the Cobertura report for the given file `filename` where `lineno` is
the line number and `status` is coverage status of the line which can
be either `True` (line hit) or `False` (line miss).
"""
line_elements = self._get_lines_by_filename(filename)
lines_w_status = []
for line in line_elements:
lineno = int(line.attrib['number'])
status = line.attrib['hits'] != '0'
lines_w_status.append((lineno, status))
return lines_w_status
def missed_lines(self, filename):
"""
Return a list of extrapolated uncovered line numbers for the
file `filename` according to `Cobertura.line_statuses`.
"""
statuses = self.line_statuses(filename)
statuses = extrapolate_coverage(statuses)
return [lno for lno, status in statuses if status is False]
@memoize
def file_source(self, filename):
"""
Return a list of namedtuple `Line` for each line of code found in the
source file with the given `filename`.
"""
lines = []
try:
with self.filesystem.open(filename) as f:
line_statuses = dict(self.line_statuses(filename))
for lineno, source in enumerate(f, start=1):
line_status = line_statuses.get(lineno)
line = Line(lineno, source, line_status, None)
lines.append(line)
except self.filesystem.FileNotFound as file_not_found:
lines.append(
Line(0, '%s not found' % file_not_found.path, None, None)
)
return lines
def total_misses(self, filename=None):
"""
Return the total number of uncovered statements for the file
`filename`. If `filename` is not given, return the total
number of uncovered statements for all files.
"""
if filename is not None:
return len(self.missed_statements(filename))
total = 0
for filename in self.files():
total += len(self.missed_statements(filename))
return total
def total_hits(self, filename=None):
"""
Return the total number of covered statements for the file
`filename`. If `filename` is not given, return the total
number of covered statements for all files.
"""
if filename is not None:
return len(self.hit_statements(filename))
total = 0
for filename in self.files():
total += len(self.hit_statements(filename))
return total
def total_statements(self, filename=None):
"""
Return the total number of statements for the file
`filename`. If `filename` is not given, return the total
number of statements for all files.
"""
if filename is not None:
statements = self._get_lines_by_filename(filename)
return len(statements)
total = 0
for filename in self.files():
statements = self._get_lines_by_filename(filename)
total += len(statements)
return total
@memoize
def files(self):
"""
Return the list of available files in the coverage report.
"""
# maybe replace with a trie at some point? see has_file FIXME
already_seen = set()
filenames = []
for el in self.xml.xpath("//class"):
filename = el.attrib['filename']
if filename in already_seen:
continue
already_seen.add(filename)
filenames.append(filename)
return filenames
def has_file(self, filename):
"""
Return `True` if the file `filename` is present in the report, return
`False` otherwise.
"""
# FIXME: this will lookup a list which is slow, make it O(1)
return filename in self.files()
@memoize
def source_lines(self, filename):
"""
Return a list for source lines of file `filename`.
"""
with self.filesystem.open(filename) as f:
return f.readlines()
@memoize
def packages(self):
"""
Return the list of available packages in the coverage report.
"""
return [el.attrib['name'] for el in self.xml.xpath("//package")]
|
aconrad/pycobertura | pycobertura/cobertura.py | Cobertura.line_statuses | python | def line_statuses(self, filename):
line_elements = self._get_lines_by_filename(filename)
lines_w_status = []
for line in line_elements:
lineno = int(line.attrib['number'])
status = line.attrib['hits'] != '0'
lines_w_status.append((lineno, status))
return lines_w_status | Return a list of tuples `(lineno, status)` of all the lines found in
the Cobertura report for the given file `filename` where `lineno` is
the line number and `status` is coverage status of the line which can
be either `True` (line hit) or `False` (line miss). | train | https://github.com/aconrad/pycobertura/blob/26e472f1424f5cd499c42232dc5ee12e4042806f/pycobertura/cobertura.py#L137-L152 | null | class Cobertura(object):
"""
An XML Cobertura parser.
"""
def __init__(self, report, source=None, source_prefix=None):
"""
Initialize a Cobertura report given a coverage report `report`. It can
be either a file object or the path to an XML file that is in the
Cobertura format.
The optional argument `source` is the location of the source code
provided as a directory path or a file object zip archive containing
the source code.
The optional argument `source_prefix` will be used to lookup source
files if a zip archive is provided and will be prepended to filenames
found in the coverage report.
"""
self.xml = ET.parse(report).getroot()
if source is None:
if isinstance(report, basestring):
# get the directory in which the coverage file lives
source = os.path.dirname(report)
self.filesystem = DirectoryFileSystem(
source, source_prefix=source_prefix
)
elif zipfile.is_zipfile(source):
self.filesystem = ZipFileSystem(
source, source_prefix=source_prefix
)
else:
self.filesystem = DirectoryFileSystem(
source, source_prefix=source_prefix
)
@memoize
def _get_class_element_by_filename(self, filename):
syntax = "./packages//class[@filename='%s'][1]" % (
filename
)
return self.xml.xpath(syntax)[0]
@memoize
def _get_lines_by_filename(self, filename):
el = self._get_class_element_by_filename(filename)
return el.xpath('./lines/line')
@property
def version(self):
"""Return the version number of the coverage report."""
return self.xml.attrib['version']
def line_rate(self, filename=None):
"""
Return the global line rate of the coverage report. If the
`filename` file is given, return the line rate of the file.
"""
if filename is None:
el = self.xml
else:
el = self._get_class_element_by_filename(filename)
return float(el.attrib['line-rate'])
def branch_rate(self, filename=None):
"""
Return the global branch rate of the coverage report. If the
`filename` file is given, return the branch rate of the file.
"""
if filename is None:
el = self.xml
else:
el = self._get_class_element_by_filename(filename)
return float(el.attrib['branch-rate'])
@memoize
def missed_statements(self, filename):
"""
Return a list of uncovered line numbers for each of the missed
statements found for the file `filename`.
"""
el = self._get_class_element_by_filename(filename)
lines = el.xpath('./lines/line[@hits=0]')
return [int(l.attrib['number']) for l in lines]
@memoize
def hit_statements(self, filename):
"""
Return a list of covered line numbers for each of the hit statements
found for the file `filename`.
"""
el = self._get_class_element_by_filename(filename)
lines = el.xpath('./lines/line[@hits>0]')
return [int(l.attrib['number']) for l in lines]
def missed_lines(self, filename):
"""
Return a list of extrapolated uncovered line numbers for the
file `filename` according to `Cobertura.line_statuses`.
"""
statuses = self.line_statuses(filename)
statuses = extrapolate_coverage(statuses)
return [lno for lno, status in statuses if status is False]
@memoize
def file_source(self, filename):
"""
Return a list of namedtuple `Line` for each line of code found in the
source file with the given `filename`.
"""
lines = []
try:
with self.filesystem.open(filename) as f:
line_statuses = dict(self.line_statuses(filename))
for lineno, source in enumerate(f, start=1):
line_status = line_statuses.get(lineno)
line = Line(lineno, source, line_status, None)
lines.append(line)
except self.filesystem.FileNotFound as file_not_found:
lines.append(
Line(0, '%s not found' % file_not_found.path, None, None)
)
return lines
def total_misses(self, filename=None):
"""
Return the total number of uncovered statements for the file
`filename`. If `filename` is not given, return the total
number of uncovered statements for all files.
"""
if filename is not None:
return len(self.missed_statements(filename))
total = 0
for filename in self.files():
total += len(self.missed_statements(filename))
return total
def total_hits(self, filename=None):
"""
Return the total number of covered statements for the file
`filename`. If `filename` is not given, return the total
number of covered statements for all files.
"""
if filename is not None:
return len(self.hit_statements(filename))
total = 0
for filename in self.files():
total += len(self.hit_statements(filename))
return total
def total_statements(self, filename=None):
"""
Return the total number of statements for the file
`filename`. If `filename` is not given, return the total
number of statements for all files.
"""
if filename is not None:
statements = self._get_lines_by_filename(filename)
return len(statements)
total = 0
for filename in self.files():
statements = self._get_lines_by_filename(filename)
total += len(statements)
return total
@memoize
def files(self):
"""
Return the list of available files in the coverage report.
"""
# maybe replace with a trie at some point? see has_file FIXME
already_seen = set()
filenames = []
for el in self.xml.xpath("//class"):
filename = el.attrib['filename']
if filename in already_seen:
continue
already_seen.add(filename)
filenames.append(filename)
return filenames
def has_file(self, filename):
"""
Return `True` if the file `filename` is present in the report, return
`False` otherwise.
"""
# FIXME: this will lookup a list which is slow, make it O(1)
return filename in self.files()
@memoize
def source_lines(self, filename):
"""
Return a list for source lines of file `filename`.
"""
with self.filesystem.open(filename) as f:
return f.readlines()
@memoize
def packages(self):
"""
Return the list of available packages in the coverage report.
"""
return [el.attrib['name'] for el in self.xml.xpath("//package")]
|
aconrad/pycobertura | pycobertura/cobertura.py | Cobertura.missed_lines | python | def missed_lines(self, filename):
statuses = self.line_statuses(filename)
statuses = extrapolate_coverage(statuses)
return [lno for lno, status in statuses if status is False] | Return a list of extrapolated uncovered line numbers for the
file `filename` according to `Cobertura.line_statuses`. | train | https://github.com/aconrad/pycobertura/blob/26e472f1424f5cd499c42232dc5ee12e4042806f/pycobertura/cobertura.py#L154-L161 | [
"def extrapolate_coverage(lines_w_status):\n \"\"\"\n Given the following input:\n\n >>> lines_w_status = [\n (1, True),\n (4, True),\n (7, False),\n (9, False),\n ]\n\n Return expanded lines with their extrapolated line status.\n\n >>> extrapolate_coverage(lines_w_stat... | class Cobertura(object):
"""
An XML Cobertura parser.
"""
def __init__(self, report, source=None, source_prefix=None):
"""
Initialize a Cobertura report given a coverage report `report`. It can
be either a file object or the path to an XML file that is in the
Cobertura format.
The optional argument `source` is the location of the source code
provided as a directory path or a file object zip archive containing
the source code.
The optional argument `source_prefix` will be used to lookup source
files if a zip archive is provided and will be prepended to filenames
found in the coverage report.
"""
self.xml = ET.parse(report).getroot()
if source is None:
if isinstance(report, basestring):
# get the directory in which the coverage file lives
source = os.path.dirname(report)
self.filesystem = DirectoryFileSystem(
source, source_prefix=source_prefix
)
elif zipfile.is_zipfile(source):
self.filesystem = ZipFileSystem(
source, source_prefix=source_prefix
)
else:
self.filesystem = DirectoryFileSystem(
source, source_prefix=source_prefix
)
@memoize
def _get_class_element_by_filename(self, filename):
syntax = "./packages//class[@filename='%s'][1]" % (
filename
)
return self.xml.xpath(syntax)[0]
@memoize
def _get_lines_by_filename(self, filename):
el = self._get_class_element_by_filename(filename)
return el.xpath('./lines/line')
@property
def version(self):
"""Return the version number of the coverage report."""
return self.xml.attrib['version']
def line_rate(self, filename=None):
"""
Return the global line rate of the coverage report. If the
`filename` file is given, return the line rate of the file.
"""
if filename is None:
el = self.xml
else:
el = self._get_class_element_by_filename(filename)
return float(el.attrib['line-rate'])
def branch_rate(self, filename=None):
"""
Return the global branch rate of the coverage report. If the
`filename` file is given, return the branch rate of the file.
"""
if filename is None:
el = self.xml
else:
el = self._get_class_element_by_filename(filename)
return float(el.attrib['branch-rate'])
@memoize
def missed_statements(self, filename):
"""
Return a list of uncovered line numbers for each of the missed
statements found for the file `filename`.
"""
el = self._get_class_element_by_filename(filename)
lines = el.xpath('./lines/line[@hits=0]')
return [int(l.attrib['number']) for l in lines]
@memoize
def hit_statements(self, filename):
"""
Return a list of covered line numbers for each of the hit statements
found for the file `filename`.
"""
el = self._get_class_element_by_filename(filename)
lines = el.xpath('./lines/line[@hits>0]')
return [int(l.attrib['number']) for l in lines]
def line_statuses(self, filename):
"""
Return a list of tuples `(lineno, status)` of all the lines found in
the Cobertura report for the given file `filename` where `lineno` is
the line number and `status` is coverage status of the line which can
be either `True` (line hit) or `False` (line miss).
"""
line_elements = self._get_lines_by_filename(filename)
lines_w_status = []
for line in line_elements:
lineno = int(line.attrib['number'])
status = line.attrib['hits'] != '0'
lines_w_status.append((lineno, status))
return lines_w_status
@memoize
def file_source(self, filename):
"""
Return a list of namedtuple `Line` for each line of code found in the
source file with the given `filename`.
"""
lines = []
try:
with self.filesystem.open(filename) as f:
line_statuses = dict(self.line_statuses(filename))
for lineno, source in enumerate(f, start=1):
line_status = line_statuses.get(lineno)
line = Line(lineno, source, line_status, None)
lines.append(line)
except self.filesystem.FileNotFound as file_not_found:
lines.append(
Line(0, '%s not found' % file_not_found.path, None, None)
)
return lines
def total_misses(self, filename=None):
"""
Return the total number of uncovered statements for the file
`filename`. If `filename` is not given, return the total
number of uncovered statements for all files.
"""
if filename is not None:
return len(self.missed_statements(filename))
total = 0
for filename in self.files():
total += len(self.missed_statements(filename))
return total
def total_hits(self, filename=None):
"""
Return the total number of covered statements for the file
`filename`. If `filename` is not given, return the total
number of covered statements for all files.
"""
if filename is not None:
return len(self.hit_statements(filename))
total = 0
for filename in self.files():
total += len(self.hit_statements(filename))
return total
def total_statements(self, filename=None):
"""
Return the total number of statements for the file
`filename`. If `filename` is not given, return the total
number of statements for all files.
"""
if filename is not None:
statements = self._get_lines_by_filename(filename)
return len(statements)
total = 0
for filename in self.files():
statements = self._get_lines_by_filename(filename)
total += len(statements)
return total
@memoize
def files(self):
"""
Return the list of available files in the coverage report.
"""
# maybe replace with a trie at some point? see has_file FIXME
already_seen = set()
filenames = []
for el in self.xml.xpath("//class"):
filename = el.attrib['filename']
if filename in already_seen:
continue
already_seen.add(filename)
filenames.append(filename)
return filenames
def has_file(self, filename):
"""
Return `True` if the file `filename` is present in the report, return
`False` otherwise.
"""
# FIXME: this will lookup a list which is slow, make it O(1)
return filename in self.files()
@memoize
def source_lines(self, filename):
"""
Return a list for source lines of file `filename`.
"""
with self.filesystem.open(filename) as f:
return f.readlines()
@memoize
def packages(self):
"""
Return the list of available packages in the coverage report.
"""
return [el.attrib['name'] for el in self.xml.xpath("//package")]
|
aconrad/pycobertura | pycobertura/cobertura.py | Cobertura.file_source | python | def file_source(self, filename):
lines = []
try:
with self.filesystem.open(filename) as f:
line_statuses = dict(self.line_statuses(filename))
for lineno, source in enumerate(f, start=1):
line_status = line_statuses.get(lineno)
line = Line(lineno, source, line_status, None)
lines.append(line)
except self.filesystem.FileNotFound as file_not_found:
lines.append(
Line(0, '%s not found' % file_not_found.path, None, None)
)
return lines | Return a list of namedtuple `Line` for each line of code found in the
source file with the given `filename`. | train | https://github.com/aconrad/pycobertura/blob/26e472f1424f5cd499c42232dc5ee12e4042806f/pycobertura/cobertura.py#L164-L183 | [
"def line_statuses(self, filename):\n \"\"\"\n Return a list of tuples `(lineno, status)` of all the lines found in\n the Cobertura report for the given file `filename` where `lineno` is\n the line number and `status` is coverage status of the line which can\n be either `True` (line hit) or `False` (... | class Cobertura(object):
"""
An XML Cobertura parser.
"""
def __init__(self, report, source=None, source_prefix=None):
"""
Initialize a Cobertura report given a coverage report `report`. It can
be either a file object or the path to an XML file that is in the
Cobertura format.
The optional argument `source` is the location of the source code
provided as a directory path or a file object zip archive containing
the source code.
The optional argument `source_prefix` will be used to lookup source
files if a zip archive is provided and will be prepended to filenames
found in the coverage report.
"""
self.xml = ET.parse(report).getroot()
if source is None:
if isinstance(report, basestring):
# get the directory in which the coverage file lives
source = os.path.dirname(report)
self.filesystem = DirectoryFileSystem(
source, source_prefix=source_prefix
)
elif zipfile.is_zipfile(source):
self.filesystem = ZipFileSystem(
source, source_prefix=source_prefix
)
else:
self.filesystem = DirectoryFileSystem(
source, source_prefix=source_prefix
)
@memoize
def _get_class_element_by_filename(self, filename):
syntax = "./packages//class[@filename='%s'][1]" % (
filename
)
return self.xml.xpath(syntax)[0]
@memoize
def _get_lines_by_filename(self, filename):
el = self._get_class_element_by_filename(filename)
return el.xpath('./lines/line')
@property
def version(self):
"""Return the version number of the coverage report."""
return self.xml.attrib['version']
def line_rate(self, filename=None):
"""
Return the global line rate of the coverage report. If the
`filename` file is given, return the line rate of the file.
"""
if filename is None:
el = self.xml
else:
el = self._get_class_element_by_filename(filename)
return float(el.attrib['line-rate'])
def branch_rate(self, filename=None):
"""
Return the global branch rate of the coverage report. If the
`filename` file is given, return the branch rate of the file.
"""
if filename is None:
el = self.xml
else:
el = self._get_class_element_by_filename(filename)
return float(el.attrib['branch-rate'])
@memoize
def missed_statements(self, filename):
"""
Return a list of uncovered line numbers for each of the missed
statements found for the file `filename`.
"""
el = self._get_class_element_by_filename(filename)
lines = el.xpath('./lines/line[@hits=0]')
return [int(l.attrib['number']) for l in lines]
@memoize
def hit_statements(self, filename):
"""
Return a list of covered line numbers for each of the hit statements
found for the file `filename`.
"""
el = self._get_class_element_by_filename(filename)
lines = el.xpath('./lines/line[@hits>0]')
return [int(l.attrib['number']) for l in lines]
def line_statuses(self, filename):
"""
Return a list of tuples `(lineno, status)` of all the lines found in
the Cobertura report for the given file `filename` where `lineno` is
the line number and `status` is coverage status of the line which can
be either `True` (line hit) or `False` (line miss).
"""
line_elements = self._get_lines_by_filename(filename)
lines_w_status = []
for line in line_elements:
lineno = int(line.attrib['number'])
status = line.attrib['hits'] != '0'
lines_w_status.append((lineno, status))
return lines_w_status
def missed_lines(self, filename):
"""
Return a list of extrapolated uncovered line numbers for the
file `filename` according to `Cobertura.line_statuses`.
"""
statuses = self.line_statuses(filename)
statuses = extrapolate_coverage(statuses)
return [lno for lno, status in statuses if status is False]
@memoize
def total_misses(self, filename=None):
"""
Return the total number of uncovered statements for the file
`filename`. If `filename` is not given, return the total
number of uncovered statements for all files.
"""
if filename is not None:
return len(self.missed_statements(filename))
total = 0
for filename in self.files():
total += len(self.missed_statements(filename))
return total
def total_hits(self, filename=None):
"""
Return the total number of covered statements for the file
`filename`. If `filename` is not given, return the total
number of covered statements for all files.
"""
if filename is not None:
return len(self.hit_statements(filename))
total = 0
for filename in self.files():
total += len(self.hit_statements(filename))
return total
def total_statements(self, filename=None):
"""
Return the total number of statements for the file
`filename`. If `filename` is not given, return the total
number of statements for all files.
"""
if filename is not None:
statements = self._get_lines_by_filename(filename)
return len(statements)
total = 0
for filename in self.files():
statements = self._get_lines_by_filename(filename)
total += len(statements)
return total
@memoize
def files(self):
"""
Return the list of available files in the coverage report.
"""
# maybe replace with a trie at some point? see has_file FIXME
already_seen = set()
filenames = []
for el in self.xml.xpath("//class"):
filename = el.attrib['filename']
if filename in already_seen:
continue
already_seen.add(filename)
filenames.append(filename)
return filenames
def has_file(self, filename):
"""
Return `True` if the file `filename` is present in the report, return
`False` otherwise.
"""
# FIXME: this will lookup a list which is slow, make it O(1)
return filename in self.files()
@memoize
def source_lines(self, filename):
"""
Return a list for source lines of file `filename`.
"""
with self.filesystem.open(filename) as f:
return f.readlines()
@memoize
def packages(self):
"""
Return the list of available packages in the coverage report.
"""
return [el.attrib['name'] for el in self.xml.xpath("//package")]
|
aconrad/pycobertura | pycobertura/cobertura.py | Cobertura.total_misses | python | def total_misses(self, filename=None):
if filename is not None:
return len(self.missed_statements(filename))
total = 0
for filename in self.files():
total += len(self.missed_statements(filename))
return total | Return the total number of uncovered statements for the file
`filename`. If `filename` is not given, return the total
number of uncovered statements for all files. | train | https://github.com/aconrad/pycobertura/blob/26e472f1424f5cd499c42232dc5ee12e4042806f/pycobertura/cobertura.py#L185-L198 | null | class Cobertura(object):
"""
An XML Cobertura parser.
"""
def __init__(self, report, source=None, source_prefix=None):
"""
Initialize a Cobertura report given a coverage report `report`. It can
be either a file object or the path to an XML file that is in the
Cobertura format.
The optional argument `source` is the location of the source code
provided as a directory path or a file object zip archive containing
the source code.
The optional argument `source_prefix` will be used to lookup source
files if a zip archive is provided and will be prepended to filenames
found in the coverage report.
"""
self.xml = ET.parse(report).getroot()
if source is None:
if isinstance(report, basestring):
# get the directory in which the coverage file lives
source = os.path.dirname(report)
self.filesystem = DirectoryFileSystem(
source, source_prefix=source_prefix
)
elif zipfile.is_zipfile(source):
self.filesystem = ZipFileSystem(
source, source_prefix=source_prefix
)
else:
self.filesystem = DirectoryFileSystem(
source, source_prefix=source_prefix
)
@memoize
def _get_class_element_by_filename(self, filename):
syntax = "./packages//class[@filename='%s'][1]" % (
filename
)
return self.xml.xpath(syntax)[0]
@memoize
def _get_lines_by_filename(self, filename):
el = self._get_class_element_by_filename(filename)
return el.xpath('./lines/line')
@property
def version(self):
"""Return the version number of the coverage report."""
return self.xml.attrib['version']
def line_rate(self, filename=None):
"""
Return the global line rate of the coverage report. If the
`filename` file is given, return the line rate of the file.
"""
if filename is None:
el = self.xml
else:
el = self._get_class_element_by_filename(filename)
return float(el.attrib['line-rate'])
def branch_rate(self, filename=None):
"""
Return the global branch rate of the coverage report. If the
`filename` file is given, return the branch rate of the file.
"""
if filename is None:
el = self.xml
else:
el = self._get_class_element_by_filename(filename)
return float(el.attrib['branch-rate'])
@memoize
def missed_statements(self, filename):
"""
Return a list of uncovered line numbers for each of the missed
statements found for the file `filename`.
"""
el = self._get_class_element_by_filename(filename)
lines = el.xpath('./lines/line[@hits=0]')
return [int(l.attrib['number']) for l in lines]
@memoize
def hit_statements(self, filename):
"""
Return a list of covered line numbers for each of the hit statements
found for the file `filename`.
"""
el = self._get_class_element_by_filename(filename)
lines = el.xpath('./lines/line[@hits>0]')
return [int(l.attrib['number']) for l in lines]
def line_statuses(self, filename):
"""
Return a list of tuples `(lineno, status)` of all the lines found in
the Cobertura report for the given file `filename` where `lineno` is
the line number and `status` is coverage status of the line which can
be either `True` (line hit) or `False` (line miss).
"""
line_elements = self._get_lines_by_filename(filename)
lines_w_status = []
for line in line_elements:
lineno = int(line.attrib['number'])
status = line.attrib['hits'] != '0'
lines_w_status.append((lineno, status))
return lines_w_status
def missed_lines(self, filename):
"""
Return a list of extrapolated uncovered line numbers for the
file `filename` according to `Cobertura.line_statuses`.
"""
statuses = self.line_statuses(filename)
statuses = extrapolate_coverage(statuses)
return [lno for lno, status in statuses if status is False]
@memoize
def file_source(self, filename):
"""
Return a list of namedtuple `Line` for each line of code found in the
source file with the given `filename`.
"""
lines = []
try:
with self.filesystem.open(filename) as f:
line_statuses = dict(self.line_statuses(filename))
for lineno, source in enumerate(f, start=1):
line_status = line_statuses.get(lineno)
line = Line(lineno, source, line_status, None)
lines.append(line)
except self.filesystem.FileNotFound as file_not_found:
lines.append(
Line(0, '%s not found' % file_not_found.path, None, None)
)
return lines
def total_hits(self, filename=None):
"""
Return the total number of covered statements for the file
`filename`. If `filename` is not given, return the total
number of covered statements for all files.
"""
if filename is not None:
return len(self.hit_statements(filename))
total = 0
for filename in self.files():
total += len(self.hit_statements(filename))
return total
def total_statements(self, filename=None):
"""
Return the total number of statements for the file
`filename`. If `filename` is not given, return the total
number of statements for all files.
"""
if filename is not None:
statements = self._get_lines_by_filename(filename)
return len(statements)
total = 0
for filename in self.files():
statements = self._get_lines_by_filename(filename)
total += len(statements)
return total
@memoize
def files(self):
"""
Return the list of available files in the coverage report.
"""
# maybe replace with a trie at some point? see has_file FIXME
already_seen = set()
filenames = []
for el in self.xml.xpath("//class"):
filename = el.attrib['filename']
if filename in already_seen:
continue
already_seen.add(filename)
filenames.append(filename)
return filenames
def has_file(self, filename):
"""
Return `True` if the file `filename` is present in the report, return
`False` otherwise.
"""
# FIXME: this will lookup a list which is slow, make it O(1)
return filename in self.files()
@memoize
def source_lines(self, filename):
"""
Return a list for source lines of file `filename`.
"""
with self.filesystem.open(filename) as f:
return f.readlines()
@memoize
def packages(self):
"""
Return the list of available packages in the coverage report.
"""
return [el.attrib['name'] for el in self.xml.xpath("//package")]
|
aconrad/pycobertura | pycobertura/cobertura.py | Cobertura.total_hits | python | def total_hits(self, filename=None):
if filename is not None:
return len(self.hit_statements(filename))
total = 0
for filename in self.files():
total += len(self.hit_statements(filename))
return total | Return the total number of covered statements for the file
`filename`. If `filename` is not given, return the total
number of covered statements for all files. | train | https://github.com/aconrad/pycobertura/blob/26e472f1424f5cd499c42232dc5ee12e4042806f/pycobertura/cobertura.py#L200-L213 | null | class Cobertura(object):
"""
An XML Cobertura parser.
"""
def __init__(self, report, source=None, source_prefix=None):
"""
Initialize a Cobertura report given a coverage report `report`. It can
be either a file object or the path to an XML file that is in the
Cobertura format.
The optional argument `source` is the location of the source code
provided as a directory path or a file object zip archive containing
the source code.
The optional argument `source_prefix` will be used to lookup source
files if a zip archive is provided and will be prepended to filenames
found in the coverage report.
"""
self.xml = ET.parse(report).getroot()
if source is None:
if isinstance(report, basestring):
# get the directory in which the coverage file lives
source = os.path.dirname(report)
self.filesystem = DirectoryFileSystem(
source, source_prefix=source_prefix
)
elif zipfile.is_zipfile(source):
self.filesystem = ZipFileSystem(
source, source_prefix=source_prefix
)
else:
self.filesystem = DirectoryFileSystem(
source, source_prefix=source_prefix
)
@memoize
def _get_class_element_by_filename(self, filename):
syntax = "./packages//class[@filename='%s'][1]" % (
filename
)
return self.xml.xpath(syntax)[0]
@memoize
def _get_lines_by_filename(self, filename):
el = self._get_class_element_by_filename(filename)
return el.xpath('./lines/line')
@property
def version(self):
"""Return the version number of the coverage report."""
return self.xml.attrib['version']
def line_rate(self, filename=None):
"""
Return the global line rate of the coverage report. If the
`filename` file is given, return the line rate of the file.
"""
if filename is None:
el = self.xml
else:
el = self._get_class_element_by_filename(filename)
return float(el.attrib['line-rate'])
def branch_rate(self, filename=None):
"""
Return the global branch rate of the coverage report. If the
`filename` file is given, return the branch rate of the file.
"""
if filename is None:
el = self.xml
else:
el = self._get_class_element_by_filename(filename)
return float(el.attrib['branch-rate'])
@memoize
def missed_statements(self, filename):
"""
Return a list of uncovered line numbers for each of the missed
statements found for the file `filename`.
"""
el = self._get_class_element_by_filename(filename)
lines = el.xpath('./lines/line[@hits=0]')
return [int(l.attrib['number']) for l in lines]
@memoize
def hit_statements(self, filename):
"""
Return a list of covered line numbers for each of the hit statements
found for the file `filename`.
"""
el = self._get_class_element_by_filename(filename)
lines = el.xpath('./lines/line[@hits>0]')
return [int(l.attrib['number']) for l in lines]
def line_statuses(self, filename):
"""
Return a list of tuples `(lineno, status)` of all the lines found in
the Cobertura report for the given file `filename` where `lineno` is
the line number and `status` is coverage status of the line which can
be either `True` (line hit) or `False` (line miss).
"""
line_elements = self._get_lines_by_filename(filename)
lines_w_status = []
for line in line_elements:
lineno = int(line.attrib['number'])
status = line.attrib['hits'] != '0'
lines_w_status.append((lineno, status))
return lines_w_status
def missed_lines(self, filename):
"""
Return a list of extrapolated uncovered line numbers for the
file `filename` according to `Cobertura.line_statuses`.
"""
statuses = self.line_statuses(filename)
statuses = extrapolate_coverage(statuses)
return [lno for lno, status in statuses if status is False]
@memoize
def file_source(self, filename):
"""
Return a list of namedtuple `Line` for each line of code found in the
source file with the given `filename`.
"""
lines = []
try:
with self.filesystem.open(filename) as f:
line_statuses = dict(self.line_statuses(filename))
for lineno, source in enumerate(f, start=1):
line_status = line_statuses.get(lineno)
line = Line(lineno, source, line_status, None)
lines.append(line)
except self.filesystem.FileNotFound as file_not_found:
lines.append(
Line(0, '%s not found' % file_not_found.path, None, None)
)
return lines
def total_misses(self, filename=None):
"""
Return the total number of uncovered statements for the file
`filename`. If `filename` is not given, return the total
number of uncovered statements for all files.
"""
if filename is not None:
return len(self.missed_statements(filename))
total = 0
for filename in self.files():
total += len(self.missed_statements(filename))
return total
def total_statements(self, filename=None):
"""
Return the total number of statements for the file
`filename`. If `filename` is not given, return the total
number of statements for all files.
"""
if filename is not None:
statements = self._get_lines_by_filename(filename)
return len(statements)
total = 0
for filename in self.files():
statements = self._get_lines_by_filename(filename)
total += len(statements)
return total
@memoize
def files(self):
"""
Return the list of available files in the coverage report.
"""
# maybe replace with a trie at some point? see has_file FIXME
already_seen = set()
filenames = []
for el in self.xml.xpath("//class"):
filename = el.attrib['filename']
if filename in already_seen:
continue
already_seen.add(filename)
filenames.append(filename)
return filenames
def has_file(self, filename):
"""
Return `True` if the file `filename` is present in the report, return
`False` otherwise.
"""
# FIXME: this will lookup a list which is slow, make it O(1)
return filename in self.files()
@memoize
def source_lines(self, filename):
"""
Return a list for source lines of file `filename`.
"""
with self.filesystem.open(filename) as f:
return f.readlines()
@memoize
def packages(self):
"""
Return the list of available packages in the coverage report.
"""
return [el.attrib['name'] for el in self.xml.xpath("//package")]
|
aconrad/pycobertura | pycobertura/cobertura.py | Cobertura.total_statements | python | def total_statements(self, filename=None):
if filename is not None:
statements = self._get_lines_by_filename(filename)
return len(statements)
total = 0
for filename in self.files():
statements = self._get_lines_by_filename(filename)
total += len(statements)
return total | Return the total number of statements for the file
`filename`. If `filename` is not given, return the total
number of statements for all files. | train | https://github.com/aconrad/pycobertura/blob/26e472f1424f5cd499c42232dc5ee12e4042806f/pycobertura/cobertura.py#L215-L230 | null | class Cobertura(object):
"""
An XML Cobertura parser.
"""
def __init__(self, report, source=None, source_prefix=None):
"""
Initialize a Cobertura report given a coverage report `report`. It can
be either a file object or the path to an XML file that is in the
Cobertura format.
The optional argument `source` is the location of the source code
provided as a directory path or a file object zip archive containing
the source code.
The optional argument `source_prefix` will be used to lookup source
files if a zip archive is provided and will be prepended to filenames
found in the coverage report.
"""
self.xml = ET.parse(report).getroot()
if source is None:
if isinstance(report, basestring):
# get the directory in which the coverage file lives
source = os.path.dirname(report)
self.filesystem = DirectoryFileSystem(
source, source_prefix=source_prefix
)
elif zipfile.is_zipfile(source):
self.filesystem = ZipFileSystem(
source, source_prefix=source_prefix
)
else:
self.filesystem = DirectoryFileSystem(
source, source_prefix=source_prefix
)
@memoize
def _get_class_element_by_filename(self, filename):
syntax = "./packages//class[@filename='%s'][1]" % (
filename
)
return self.xml.xpath(syntax)[0]
@memoize
def _get_lines_by_filename(self, filename):
el = self._get_class_element_by_filename(filename)
return el.xpath('./lines/line')
@property
def version(self):
"""Return the version number of the coverage report."""
return self.xml.attrib['version']
def line_rate(self, filename=None):
"""
Return the global line rate of the coverage report. If the
`filename` file is given, return the line rate of the file.
"""
if filename is None:
el = self.xml
else:
el = self._get_class_element_by_filename(filename)
return float(el.attrib['line-rate'])
def branch_rate(self, filename=None):
"""
Return the global branch rate of the coverage report. If the
`filename` file is given, return the branch rate of the file.
"""
if filename is None:
el = self.xml
else:
el = self._get_class_element_by_filename(filename)
return float(el.attrib['branch-rate'])
@memoize
def missed_statements(self, filename):
"""
Return a list of uncovered line numbers for each of the missed
statements found for the file `filename`.
"""
el = self._get_class_element_by_filename(filename)
lines = el.xpath('./lines/line[@hits=0]')
return [int(l.attrib['number']) for l in lines]
@memoize
def hit_statements(self, filename):
"""
Return a list of covered line numbers for each of the hit statements
found for the file `filename`.
"""
el = self._get_class_element_by_filename(filename)
lines = el.xpath('./lines/line[@hits>0]')
return [int(l.attrib['number']) for l in lines]
def line_statuses(self, filename):
"""
Return a list of tuples `(lineno, status)` of all the lines found in
the Cobertura report for the given file `filename` where `lineno` is
the line number and `status` is coverage status of the line which can
be either `True` (line hit) or `False` (line miss).
"""
line_elements = self._get_lines_by_filename(filename)
lines_w_status = []
for line in line_elements:
lineno = int(line.attrib['number'])
status = line.attrib['hits'] != '0'
lines_w_status.append((lineno, status))
return lines_w_status
def missed_lines(self, filename):
"""
Return a list of extrapolated uncovered line numbers for the
file `filename` according to `Cobertura.line_statuses`.
"""
statuses = self.line_statuses(filename)
statuses = extrapolate_coverage(statuses)
return [lno for lno, status in statuses if status is False]
@memoize
def file_source(self, filename):
"""
Return a list of namedtuple `Line` for each line of code found in the
source file with the given `filename`.
"""
lines = []
try:
with self.filesystem.open(filename) as f:
line_statuses = dict(self.line_statuses(filename))
for lineno, source in enumerate(f, start=1):
line_status = line_statuses.get(lineno)
line = Line(lineno, source, line_status, None)
lines.append(line)
except self.filesystem.FileNotFound as file_not_found:
lines.append(
Line(0, '%s not found' % file_not_found.path, None, None)
)
return lines
def total_misses(self, filename=None):
"""
Return the total number of uncovered statements for the file
`filename`. If `filename` is not given, return the total
number of uncovered statements for all files.
"""
if filename is not None:
return len(self.missed_statements(filename))
total = 0
for filename in self.files():
total += len(self.missed_statements(filename))
return total
def total_hits(self, filename=None):
"""
Return the total number of covered statements for the file
`filename`. If `filename` is not given, return the total
number of covered statements for all files.
"""
if filename is not None:
return len(self.hit_statements(filename))
total = 0
for filename in self.files():
total += len(self.hit_statements(filename))
return total
@memoize
def files(self):
"""
Return the list of available files in the coverage report.
"""
# maybe replace with a trie at some point? see has_file FIXME
already_seen = set()
filenames = []
for el in self.xml.xpath("//class"):
filename = el.attrib['filename']
if filename in already_seen:
continue
already_seen.add(filename)
filenames.append(filename)
return filenames
def has_file(self, filename):
"""
Return `True` if the file `filename` is present in the report, return
`False` otherwise.
"""
# FIXME: this will lookup a list which is slow, make it O(1)
return filename in self.files()
@memoize
def source_lines(self, filename):
"""
Return a list for source lines of file `filename`.
"""
with self.filesystem.open(filename) as f:
return f.readlines()
@memoize
def packages(self):
"""
Return the list of available packages in the coverage report.
"""
return [el.attrib['name'] for el in self.xml.xpath("//package")]
|
aconrad/pycobertura | pycobertura/cobertura.py | Cobertura.files | python | def files(self):
# maybe replace with a trie at some point? see has_file FIXME
already_seen = set()
filenames = []
for el in self.xml.xpath("//class"):
filename = el.attrib['filename']
if filename in already_seen:
continue
already_seen.add(filename)
filenames.append(filename)
return filenames | Return the list of available files in the coverage report. | train | https://github.com/aconrad/pycobertura/blob/26e472f1424f5cd499c42232dc5ee12e4042806f/pycobertura/cobertura.py#L233-L248 | null | class Cobertura(object):
"""
An XML Cobertura parser.
"""
def __init__(self, report, source=None, source_prefix=None):
"""
Initialize a Cobertura report given a coverage report `report`. It can
be either a file object or the path to an XML file that is in the
Cobertura format.
The optional argument `source` is the location of the source code
provided as a directory path or a file object zip archive containing
the source code.
The optional argument `source_prefix` will be used to lookup source
files if a zip archive is provided and will be prepended to filenames
found in the coverage report.
"""
self.xml = ET.parse(report).getroot()
if source is None:
if isinstance(report, basestring):
# get the directory in which the coverage file lives
source = os.path.dirname(report)
self.filesystem = DirectoryFileSystem(
source, source_prefix=source_prefix
)
elif zipfile.is_zipfile(source):
self.filesystem = ZipFileSystem(
source, source_prefix=source_prefix
)
else:
self.filesystem = DirectoryFileSystem(
source, source_prefix=source_prefix
)
@memoize
def _get_class_element_by_filename(self, filename):
syntax = "./packages//class[@filename='%s'][1]" % (
filename
)
return self.xml.xpath(syntax)[0]
@memoize
def _get_lines_by_filename(self, filename):
el = self._get_class_element_by_filename(filename)
return el.xpath('./lines/line')
@property
def version(self):
"""Return the version number of the coverage report."""
return self.xml.attrib['version']
def line_rate(self, filename=None):
"""
Return the global line rate of the coverage report. If the
`filename` file is given, return the line rate of the file.
"""
if filename is None:
el = self.xml
else:
el = self._get_class_element_by_filename(filename)
return float(el.attrib['line-rate'])
def branch_rate(self, filename=None):
"""
Return the global branch rate of the coverage report. If the
`filename` file is given, return the branch rate of the file.
"""
if filename is None:
el = self.xml
else:
el = self._get_class_element_by_filename(filename)
return float(el.attrib['branch-rate'])
@memoize
def missed_statements(self, filename):
"""
Return a list of uncovered line numbers for each of the missed
statements found for the file `filename`.
"""
el = self._get_class_element_by_filename(filename)
lines = el.xpath('./lines/line[@hits=0]')
return [int(l.attrib['number']) for l in lines]
@memoize
def hit_statements(self, filename):
"""
Return a list of covered line numbers for each of the hit statements
found for the file `filename`.
"""
el = self._get_class_element_by_filename(filename)
lines = el.xpath('./lines/line[@hits>0]')
return [int(l.attrib['number']) for l in lines]
def line_statuses(self, filename):
"""
Return a list of tuples `(lineno, status)` of all the lines found in
the Cobertura report for the given file `filename` where `lineno` is
the line number and `status` is coverage status of the line which can
be either `True` (line hit) or `False` (line miss).
"""
line_elements = self._get_lines_by_filename(filename)
lines_w_status = []
for line in line_elements:
lineno = int(line.attrib['number'])
status = line.attrib['hits'] != '0'
lines_w_status.append((lineno, status))
return lines_w_status
def missed_lines(self, filename):
"""
Return a list of extrapolated uncovered line numbers for the
file `filename` according to `Cobertura.line_statuses`.
"""
statuses = self.line_statuses(filename)
statuses = extrapolate_coverage(statuses)
return [lno for lno, status in statuses if status is False]
@memoize
def file_source(self, filename):
"""
Return a list of namedtuple `Line` for each line of code found in the
source file with the given `filename`.
"""
lines = []
try:
with self.filesystem.open(filename) as f:
line_statuses = dict(self.line_statuses(filename))
for lineno, source in enumerate(f, start=1):
line_status = line_statuses.get(lineno)
line = Line(lineno, source, line_status, None)
lines.append(line)
except self.filesystem.FileNotFound as file_not_found:
lines.append(
Line(0, '%s not found' % file_not_found.path, None, None)
)
return lines
def total_misses(self, filename=None):
"""
Return the total number of uncovered statements for the file
`filename`. If `filename` is not given, return the total
number of uncovered statements for all files.
"""
if filename is not None:
return len(self.missed_statements(filename))
total = 0
for filename in self.files():
total += len(self.missed_statements(filename))
return total
def total_hits(self, filename=None):
"""
Return the total number of covered statements for the file
`filename`. If `filename` is not given, return the total
number of covered statements for all files.
"""
if filename is not None:
return len(self.hit_statements(filename))
total = 0
for filename in self.files():
total += len(self.hit_statements(filename))
return total
def total_statements(self, filename=None):
"""
Return the total number of statements for the file
`filename`. If `filename` is not given, return the total
number of statements for all files.
"""
if filename is not None:
statements = self._get_lines_by_filename(filename)
return len(statements)
total = 0
for filename in self.files():
statements = self._get_lines_by_filename(filename)
total += len(statements)
return total
@memoize
def has_file(self, filename):
"""
Return `True` if the file `filename` is present in the report, return
`False` otherwise.
"""
# FIXME: this will lookup a list which is slow, make it O(1)
return filename in self.files()
@memoize
def source_lines(self, filename):
"""
Return a list for source lines of file `filename`.
"""
with self.filesystem.open(filename) as f:
return f.readlines()
@memoize
def packages(self):
"""
Return the list of available packages in the coverage report.
"""
return [el.attrib['name'] for el in self.xml.xpath("//package")]
|
aconrad/pycobertura | pycobertura/cobertura.py | Cobertura.source_lines | python | def source_lines(self, filename):
with self.filesystem.open(filename) as f:
return f.readlines() | Return a list for source lines of file `filename`. | train | https://github.com/aconrad/pycobertura/blob/26e472f1424f5cd499c42232dc5ee12e4042806f/pycobertura/cobertura.py#L259-L264 | null | class Cobertura(object):
"""
An XML Cobertura parser.
"""
def __init__(self, report, source=None, source_prefix=None):
"""
Initialize a Cobertura report given a coverage report `report`. It can
be either a file object or the path to an XML file that is in the
Cobertura format.
The optional argument `source` is the location of the source code
provided as a directory path or a file object zip archive containing
the source code.
The optional argument `source_prefix` will be used to lookup source
files if a zip archive is provided and will be prepended to filenames
found in the coverage report.
"""
self.xml = ET.parse(report).getroot()
if source is None:
if isinstance(report, basestring):
# get the directory in which the coverage file lives
source = os.path.dirname(report)
self.filesystem = DirectoryFileSystem(
source, source_prefix=source_prefix
)
elif zipfile.is_zipfile(source):
self.filesystem = ZipFileSystem(
source, source_prefix=source_prefix
)
else:
self.filesystem = DirectoryFileSystem(
source, source_prefix=source_prefix
)
@memoize
def _get_class_element_by_filename(self, filename):
syntax = "./packages//class[@filename='%s'][1]" % (
filename
)
return self.xml.xpath(syntax)[0]
@memoize
def _get_lines_by_filename(self, filename):
el = self._get_class_element_by_filename(filename)
return el.xpath('./lines/line')
@property
def version(self):
"""Return the version number of the coverage report."""
return self.xml.attrib['version']
def line_rate(self, filename=None):
"""
Return the global line rate of the coverage report. If the
`filename` file is given, return the line rate of the file.
"""
if filename is None:
el = self.xml
else:
el = self._get_class_element_by_filename(filename)
return float(el.attrib['line-rate'])
def branch_rate(self, filename=None):
"""
Return the global branch rate of the coverage report. If the
`filename` file is given, return the branch rate of the file.
"""
if filename is None:
el = self.xml
else:
el = self._get_class_element_by_filename(filename)
return float(el.attrib['branch-rate'])
@memoize
def missed_statements(self, filename):
"""
Return a list of uncovered line numbers for each of the missed
statements found for the file `filename`.
"""
el = self._get_class_element_by_filename(filename)
lines = el.xpath('./lines/line[@hits=0]')
return [int(l.attrib['number']) for l in lines]
@memoize
def hit_statements(self, filename):
"""
Return a list of covered line numbers for each of the hit statements
found for the file `filename`.
"""
el = self._get_class_element_by_filename(filename)
lines = el.xpath('./lines/line[@hits>0]')
return [int(l.attrib['number']) for l in lines]
def line_statuses(self, filename):
"""
Return a list of tuples `(lineno, status)` of all the lines found in
the Cobertura report for the given file `filename` where `lineno` is
the line number and `status` is coverage status of the line which can
be either `True` (line hit) or `False` (line miss).
"""
line_elements = self._get_lines_by_filename(filename)
lines_w_status = []
for line in line_elements:
lineno = int(line.attrib['number'])
status = line.attrib['hits'] != '0'
lines_w_status.append((lineno, status))
return lines_w_status
def missed_lines(self, filename):
"""
Return a list of extrapolated uncovered line numbers for the
file `filename` according to `Cobertura.line_statuses`.
"""
statuses = self.line_statuses(filename)
statuses = extrapolate_coverage(statuses)
return [lno for lno, status in statuses if status is False]
@memoize
def file_source(self, filename):
"""
Return a list of namedtuple `Line` for each line of code found in the
source file with the given `filename`.
"""
lines = []
try:
with self.filesystem.open(filename) as f:
line_statuses = dict(self.line_statuses(filename))
for lineno, source in enumerate(f, start=1):
line_status = line_statuses.get(lineno)
line = Line(lineno, source, line_status, None)
lines.append(line)
except self.filesystem.FileNotFound as file_not_found:
lines.append(
Line(0, '%s not found' % file_not_found.path, None, None)
)
return lines
def total_misses(self, filename=None):
"""
Return the total number of uncovered statements for the file
`filename`. If `filename` is not given, return the total
number of uncovered statements for all files.
"""
if filename is not None:
return len(self.missed_statements(filename))
total = 0
for filename in self.files():
total += len(self.missed_statements(filename))
return total
def total_hits(self, filename=None):
"""
Return the total number of covered statements for the file
`filename`. If `filename` is not given, return the total
number of covered statements for all files.
"""
if filename is not None:
return len(self.hit_statements(filename))
total = 0
for filename in self.files():
total += len(self.hit_statements(filename))
return total
def total_statements(self, filename=None):
"""
Return the total number of statements for the file
`filename`. If `filename` is not given, return the total
number of statements for all files.
"""
if filename is not None:
statements = self._get_lines_by_filename(filename)
return len(statements)
total = 0
for filename in self.files():
statements = self._get_lines_by_filename(filename)
total += len(statements)
return total
@memoize
def files(self):
"""
Return the list of available files in the coverage report.
"""
# maybe replace with a trie at some point? see has_file FIXME
already_seen = set()
filenames = []
for el in self.xml.xpath("//class"):
filename = el.attrib['filename']
if filename in already_seen:
continue
already_seen.add(filename)
filenames.append(filename)
return filenames
def has_file(self, filename):
"""
Return `True` if the file `filename` is present in the report, return
`False` otherwise.
"""
# FIXME: this will lookup a list which is slow, make it O(1)
return filename in self.files()
@memoize
@memoize
def packages(self):
"""
Return the list of available packages in the coverage report.
"""
return [el.attrib['name'] for el in self.xml.xpath("//package")]
|
aconrad/pycobertura | pycobertura/cobertura.py | CoberturaDiff.has_better_coverage | python | def has_better_coverage(self):
for filename in self.files():
if self.diff_total_misses(filename) > 0:
return False
return True | Return `True` if coverage of has improved, `False` otherwise.
This does not ensure that all changes have been covered. If this is
what you want, use `CoberturaDiff.has_all_changes_covered()` instead. | train | https://github.com/aconrad/pycobertura/blob/26e472f1424f5cd499c42232dc5ee12e4042806f/pycobertura/cobertura.py#L282-L292 | [
"def diff_total_misses(self, filename=None):\n return int(self._diff_attr('total_misses', filename))\n",
"def files(self):\n \"\"\"\n Return `self.cobertura2.files()`.\n \"\"\"\n return self.cobertura2.files()\n"
] | class CoberturaDiff(object):
"""
Diff Cobertura objects.
"""
def __init__(self, cobertura1, cobertura2):
self.cobertura1 = cobertura1
self.cobertura2 = cobertura2
def has_all_changes_covered(self):
"""
Return `True` if all changes have been covered, `False` otherwise.
"""
for filename in self.files():
for hunk in self.file_source_hunks(filename):
for line in hunk:
if line.reason is None:
continue # line untouched
if line.status is False:
return False # line not covered
return True
def _diff_attr(self, attr_name, filename):
"""
Return the difference between
`self.cobertura2.<attr_name>(filename)` and
`self.cobertura1.<attr_name>(filename)`.
This generic method is meant to diff the count of methods that return
counts for a given file `filename`, e.g. `Cobertura.total_statements`,
`Cobertura.total_misses`, ...
The returned count may be a float.
"""
if filename is not None:
files = [filename]
else:
files = self.files()
total_count = 0.0
for filename in files:
if self.cobertura1.has_file(filename):
method = getattr(self.cobertura1, attr_name)
count1 = method(filename)
else:
count1 = 0.0
method = getattr(self.cobertura2, attr_name)
count2 = method(filename)
total_count += count2 - count1
return total_count
def diff_total_statements(self, filename=None):
return int(self._diff_attr('total_statements', filename))
def diff_total_misses(self, filename=None):
return int(self._diff_attr('total_misses', filename))
def diff_total_hits(self, filename=None):
return int(self._diff_attr('total_hits', filename))
def diff_line_rate(self, filename=None):
if filename is not None:
return self._diff_attr('line_rate', filename)
return self.cobertura2.line_rate() - self.cobertura1.line_rate()
def diff_missed_lines(self, filename):
"""
Return a list of 2-element tuples `(lineno, is_new)` for the given
file `filename` where `lineno` is a missed line number and `is_new`
indicates whether the missed line was introduced (True) or removed
(False).
"""
line_changed = []
for line in self.file_source(filename):
if line.status is not None:
is_new = not line.status
line_changed.append((line.number, is_new))
return line_changed
def files(self):
"""
Return `self.cobertura2.files()`.
"""
return self.cobertura2.files()
def file_source(self, filename):
"""
Return a list of namedtuple `Line` for each line of code found in the
given file `filename`.
"""
if self.cobertura1.has_file(filename) and \
self.cobertura1.filesystem.has_file(filename):
lines1 = self.cobertura1.source_lines(filename)
line_statuses1 = dict(self.cobertura1.line_statuses(
filename))
else:
lines1 = []
line_statuses1 = {}
lines2 = self.cobertura2.source_lines(filename)
line_statuses2 = dict(self.cobertura2.line_statuses(filename))
# Build a dict of lineno2 -> lineno1
lineno_map = reconcile_lines(lines2, lines1)
lines = []
for lineno, source in enumerate(lines2, start=1):
status = None
reason = None
if lineno not in lineno_map:
# line was added or removed, just use whatever coverage status
# is available as there is nothing to compare against.
status = line_statuses2.get(lineno)
reason = 'line-edit'
else:
other_lineno = lineno_map[lineno]
line_status1 = line_statuses1.get(other_lineno)
line_status2 = line_statuses2.get(lineno)
if line_status1 is line_status2:
status = None # unchanged
reason = None
elif line_status1 is True and line_status2 is False:
status = False # decreased
reason = 'cov-down'
elif line_status1 is False and line_status2 is True:
status = True # increased
reason = 'cov-up'
line = Line(lineno, source, status, reason)
lines.append(line)
return lines
def file_source_hunks(self, filename):
"""
Like `CoberturaDiff.file_source`, but returns a list of line hunks of
the lines that have changed for the given file `filename`. An empty
list means that the file has no lines that have a change in coverage
status.
"""
lines = self.file_source(filename)
hunks = hunkify_lines(lines)
return hunks
|
aconrad/pycobertura | pycobertura/cobertura.py | CoberturaDiff.has_all_changes_covered | python | def has_all_changes_covered(self):
for filename in self.files():
for hunk in self.file_source_hunks(filename):
for line in hunk:
if line.reason is None:
continue # line untouched
if line.status is False:
return False # line not covered
return True | Return `True` if all changes have been covered, `False` otherwise. | train | https://github.com/aconrad/pycobertura/blob/26e472f1424f5cd499c42232dc5ee12e4042806f/pycobertura/cobertura.py#L294-L305 | [
"def files(self):\n \"\"\"\n Return `self.cobertura2.files()`.\n \"\"\"\n return self.cobertura2.files()\n",
"def file_source_hunks(self, filename):\n \"\"\"\n Like `CoberturaDiff.file_source`, but returns a list of line hunks of\n the lines that have changed for the given file `filename`. An... | class CoberturaDiff(object):
"""
Diff Cobertura objects.
"""
def __init__(self, cobertura1, cobertura2):
self.cobertura1 = cobertura1
self.cobertura2 = cobertura2
def has_better_coverage(self):
"""
Return `True` if coverage of has improved, `False` otherwise.
This does not ensure that all changes have been covered. If this is
what you want, use `CoberturaDiff.has_all_changes_covered()` instead.
"""
for filename in self.files():
if self.diff_total_misses(filename) > 0:
return False
return True
def _diff_attr(self, attr_name, filename):
"""
Return the difference between
`self.cobertura2.<attr_name>(filename)` and
`self.cobertura1.<attr_name>(filename)`.
This generic method is meant to diff the count of methods that return
counts for a given file `filename`, e.g. `Cobertura.total_statements`,
`Cobertura.total_misses`, ...
The returned count may be a float.
"""
if filename is not None:
files = [filename]
else:
files = self.files()
total_count = 0.0
for filename in files:
if self.cobertura1.has_file(filename):
method = getattr(self.cobertura1, attr_name)
count1 = method(filename)
else:
count1 = 0.0
method = getattr(self.cobertura2, attr_name)
count2 = method(filename)
total_count += count2 - count1
return total_count
def diff_total_statements(self, filename=None):
return int(self._diff_attr('total_statements', filename))
def diff_total_misses(self, filename=None):
return int(self._diff_attr('total_misses', filename))
def diff_total_hits(self, filename=None):
return int(self._diff_attr('total_hits', filename))
def diff_line_rate(self, filename=None):
if filename is not None:
return self._diff_attr('line_rate', filename)
return self.cobertura2.line_rate() - self.cobertura1.line_rate()
def diff_missed_lines(self, filename):
"""
Return a list of 2-element tuples `(lineno, is_new)` for the given
file `filename` where `lineno` is a missed line number and `is_new`
indicates whether the missed line was introduced (True) or removed
(False).
"""
line_changed = []
for line in self.file_source(filename):
if line.status is not None:
is_new = not line.status
line_changed.append((line.number, is_new))
return line_changed
def files(self):
"""
Return `self.cobertura2.files()`.
"""
return self.cobertura2.files()
def file_source(self, filename):
"""
Return a list of namedtuple `Line` for each line of code found in the
given file `filename`.
"""
if self.cobertura1.has_file(filename) and \
self.cobertura1.filesystem.has_file(filename):
lines1 = self.cobertura1.source_lines(filename)
line_statuses1 = dict(self.cobertura1.line_statuses(
filename))
else:
lines1 = []
line_statuses1 = {}
lines2 = self.cobertura2.source_lines(filename)
line_statuses2 = dict(self.cobertura2.line_statuses(filename))
# Build a dict of lineno2 -> lineno1
lineno_map = reconcile_lines(lines2, lines1)
lines = []
for lineno, source in enumerate(lines2, start=1):
status = None
reason = None
if lineno not in lineno_map:
# line was added or removed, just use whatever coverage status
# is available as there is nothing to compare against.
status = line_statuses2.get(lineno)
reason = 'line-edit'
else:
other_lineno = lineno_map[lineno]
line_status1 = line_statuses1.get(other_lineno)
line_status2 = line_statuses2.get(lineno)
if line_status1 is line_status2:
status = None # unchanged
reason = None
elif line_status1 is True and line_status2 is False:
status = False # decreased
reason = 'cov-down'
elif line_status1 is False and line_status2 is True:
status = True # increased
reason = 'cov-up'
line = Line(lineno, source, status, reason)
lines.append(line)
return lines
def file_source_hunks(self, filename):
"""
Like `CoberturaDiff.file_source`, but returns a list of line hunks of
the lines that have changed for the given file `filename`. An empty
list means that the file has no lines that have a change in coverage
status.
"""
lines = self.file_source(filename)
hunks = hunkify_lines(lines)
return hunks
|
aconrad/pycobertura | pycobertura/cobertura.py | CoberturaDiff._diff_attr | python | def _diff_attr(self, attr_name, filename):
if filename is not None:
files = [filename]
else:
files = self.files()
total_count = 0.0
for filename in files:
if self.cobertura1.has_file(filename):
method = getattr(self.cobertura1, attr_name)
count1 = method(filename)
else:
count1 = 0.0
method = getattr(self.cobertura2, attr_name)
count2 = method(filename)
total_count += count2 - count1
return total_count | Return the difference between
`self.cobertura2.<attr_name>(filename)` and
`self.cobertura1.<attr_name>(filename)`.
This generic method is meant to diff the count of methods that return
counts for a given file `filename`, e.g. `Cobertura.total_statements`,
`Cobertura.total_misses`, ...
The returned count may be a float. | train | https://github.com/aconrad/pycobertura/blob/26e472f1424f5cd499c42232dc5ee12e4042806f/pycobertura/cobertura.py#L307-L335 | [
"def has_file(self, filename):\n \"\"\"\n Return `True` if the file `filename` is present in the report, return\n `False` otherwise.\n \"\"\"\n # FIXME: this will lookup a list which is slow, make it O(1)\n return filename in self.files()\n",
"def files(self):\n \"\"\"\n Return `self.cober... | class CoberturaDiff(object):
"""
Diff Cobertura objects.
"""
def __init__(self, cobertura1, cobertura2):
self.cobertura1 = cobertura1
self.cobertura2 = cobertura2
def has_better_coverage(self):
"""
Return `True` if coverage of has improved, `False` otherwise.
This does not ensure that all changes have been covered. If this is
what you want, use `CoberturaDiff.has_all_changes_covered()` instead.
"""
for filename in self.files():
if self.diff_total_misses(filename) > 0:
return False
return True
def has_all_changes_covered(self):
"""
Return `True` if all changes have been covered, `False` otherwise.
"""
for filename in self.files():
for hunk in self.file_source_hunks(filename):
for line in hunk:
if line.reason is None:
continue # line untouched
if line.status is False:
return False # line not covered
return True
def diff_total_statements(self, filename=None):
return int(self._diff_attr('total_statements', filename))
def diff_total_misses(self, filename=None):
return int(self._diff_attr('total_misses', filename))
def diff_total_hits(self, filename=None):
return int(self._diff_attr('total_hits', filename))
def diff_line_rate(self, filename=None):
if filename is not None:
return self._diff_attr('line_rate', filename)
return self.cobertura2.line_rate() - self.cobertura1.line_rate()
def diff_missed_lines(self, filename):
"""
Return a list of 2-element tuples `(lineno, is_new)` for the given
file `filename` where `lineno` is a missed line number and `is_new`
indicates whether the missed line was introduced (True) or removed
(False).
"""
line_changed = []
for line in self.file_source(filename):
if line.status is not None:
is_new = not line.status
line_changed.append((line.number, is_new))
return line_changed
def files(self):
"""
Return `self.cobertura2.files()`.
"""
return self.cobertura2.files()
def file_source(self, filename):
"""
Return a list of namedtuple `Line` for each line of code found in the
given file `filename`.
"""
if self.cobertura1.has_file(filename) and \
self.cobertura1.filesystem.has_file(filename):
lines1 = self.cobertura1.source_lines(filename)
line_statuses1 = dict(self.cobertura1.line_statuses(
filename))
else:
lines1 = []
line_statuses1 = {}
lines2 = self.cobertura2.source_lines(filename)
line_statuses2 = dict(self.cobertura2.line_statuses(filename))
# Build a dict of lineno2 -> lineno1
lineno_map = reconcile_lines(lines2, lines1)
lines = []
for lineno, source in enumerate(lines2, start=1):
status = None
reason = None
if lineno not in lineno_map:
# line was added or removed, just use whatever coverage status
# is available as there is nothing to compare against.
status = line_statuses2.get(lineno)
reason = 'line-edit'
else:
other_lineno = lineno_map[lineno]
line_status1 = line_statuses1.get(other_lineno)
line_status2 = line_statuses2.get(lineno)
if line_status1 is line_status2:
status = None # unchanged
reason = None
elif line_status1 is True and line_status2 is False:
status = False # decreased
reason = 'cov-down'
elif line_status1 is False and line_status2 is True:
status = True # increased
reason = 'cov-up'
line = Line(lineno, source, status, reason)
lines.append(line)
return lines
def file_source_hunks(self, filename):
"""
Like `CoberturaDiff.file_source`, but returns a list of line hunks of
the lines that have changed for the given file `filename`. An empty
list means that the file has no lines that have a change in coverage
status.
"""
lines = self.file_source(filename)
hunks = hunkify_lines(lines)
return hunks
|
aconrad/pycobertura | pycobertura/cobertura.py | CoberturaDiff.diff_missed_lines | python | def diff_missed_lines(self, filename):
line_changed = []
for line in self.file_source(filename):
if line.status is not None:
is_new = not line.status
line_changed.append((line.number, is_new))
return line_changed | Return a list of 2-element tuples `(lineno, is_new)` for the given
file `filename` where `lineno` is a missed line number and `is_new`
indicates whether the missed line was introduced (True) or removed
(False). | train | https://github.com/aconrad/pycobertura/blob/26e472f1424f5cd499c42232dc5ee12e4042806f/pycobertura/cobertura.py#L351-L363 | [
"def file_source(self, filename):\n \"\"\"\n Return a list of namedtuple `Line` for each line of code found in the\n given file `filename`.\n\n \"\"\"\n if self.cobertura1.has_file(filename) and \\\n self.cobertura1.filesystem.has_file(filename):\n lines1 = self.cobertura1.source_li... | class CoberturaDiff(object):
"""
Diff Cobertura objects.
"""
def __init__(self, cobertura1, cobertura2):
self.cobertura1 = cobertura1
self.cobertura2 = cobertura2
def has_better_coverage(self):
"""
Return `True` if coverage of has improved, `False` otherwise.
This does not ensure that all changes have been covered. If this is
what you want, use `CoberturaDiff.has_all_changes_covered()` instead.
"""
for filename in self.files():
if self.diff_total_misses(filename) > 0:
return False
return True
def has_all_changes_covered(self):
"""
Return `True` if all changes have been covered, `False` otherwise.
"""
for filename in self.files():
for hunk in self.file_source_hunks(filename):
for line in hunk:
if line.reason is None:
continue # line untouched
if line.status is False:
return False # line not covered
return True
def _diff_attr(self, attr_name, filename):
"""
Return the difference between
`self.cobertura2.<attr_name>(filename)` and
`self.cobertura1.<attr_name>(filename)`.
This generic method is meant to diff the count of methods that return
counts for a given file `filename`, e.g. `Cobertura.total_statements`,
`Cobertura.total_misses`, ...
The returned count may be a float.
"""
if filename is not None:
files = [filename]
else:
files = self.files()
total_count = 0.0
for filename in files:
if self.cobertura1.has_file(filename):
method = getattr(self.cobertura1, attr_name)
count1 = method(filename)
else:
count1 = 0.0
method = getattr(self.cobertura2, attr_name)
count2 = method(filename)
total_count += count2 - count1
return total_count
def diff_total_statements(self, filename=None):
return int(self._diff_attr('total_statements', filename))
def diff_total_misses(self, filename=None):
return int(self._diff_attr('total_misses', filename))
def diff_total_hits(self, filename=None):
return int(self._diff_attr('total_hits', filename))
def diff_line_rate(self, filename=None):
if filename is not None:
return self._diff_attr('line_rate', filename)
return self.cobertura2.line_rate() - self.cobertura1.line_rate()
def files(self):
"""
Return `self.cobertura2.files()`.
"""
return self.cobertura2.files()
def file_source(self, filename):
"""
Return a list of namedtuple `Line` for each line of code found in the
given file `filename`.
"""
if self.cobertura1.has_file(filename) and \
self.cobertura1.filesystem.has_file(filename):
lines1 = self.cobertura1.source_lines(filename)
line_statuses1 = dict(self.cobertura1.line_statuses(
filename))
else:
lines1 = []
line_statuses1 = {}
lines2 = self.cobertura2.source_lines(filename)
line_statuses2 = dict(self.cobertura2.line_statuses(filename))
# Build a dict of lineno2 -> lineno1
lineno_map = reconcile_lines(lines2, lines1)
lines = []
for lineno, source in enumerate(lines2, start=1):
status = None
reason = None
if lineno not in lineno_map:
# line was added or removed, just use whatever coverage status
# is available as there is nothing to compare against.
status = line_statuses2.get(lineno)
reason = 'line-edit'
else:
other_lineno = lineno_map[lineno]
line_status1 = line_statuses1.get(other_lineno)
line_status2 = line_statuses2.get(lineno)
if line_status1 is line_status2:
status = None # unchanged
reason = None
elif line_status1 is True and line_status2 is False:
status = False # decreased
reason = 'cov-down'
elif line_status1 is False and line_status2 is True:
status = True # increased
reason = 'cov-up'
line = Line(lineno, source, status, reason)
lines.append(line)
return lines
def file_source_hunks(self, filename):
"""
Like `CoberturaDiff.file_source`, but returns a list of line hunks of
the lines that have changed for the given file `filename`. An empty
list means that the file has no lines that have a change in coverage
status.
"""
lines = self.file_source(filename)
hunks = hunkify_lines(lines)
return hunks
|
aconrad/pycobertura | pycobertura/cobertura.py | CoberturaDiff.file_source | python | def file_source(self, filename):
if self.cobertura1.has_file(filename) and \
self.cobertura1.filesystem.has_file(filename):
lines1 = self.cobertura1.source_lines(filename)
line_statuses1 = dict(self.cobertura1.line_statuses(
filename))
else:
lines1 = []
line_statuses1 = {}
lines2 = self.cobertura2.source_lines(filename)
line_statuses2 = dict(self.cobertura2.line_statuses(filename))
# Build a dict of lineno2 -> lineno1
lineno_map = reconcile_lines(lines2, lines1)
lines = []
for lineno, source in enumerate(lines2, start=1):
status = None
reason = None
if lineno not in lineno_map:
# line was added or removed, just use whatever coverage status
# is available as there is nothing to compare against.
status = line_statuses2.get(lineno)
reason = 'line-edit'
else:
other_lineno = lineno_map[lineno]
line_status1 = line_statuses1.get(other_lineno)
line_status2 = line_statuses2.get(lineno)
if line_status1 is line_status2:
status = None # unchanged
reason = None
elif line_status1 is True and line_status2 is False:
status = False # decreased
reason = 'cov-down'
elif line_status1 is False and line_status2 is True:
status = True # increased
reason = 'cov-up'
line = Line(lineno, source, status, reason)
lines.append(line)
return lines | Return a list of namedtuple `Line` for each line of code found in the
given file `filename`. | train | https://github.com/aconrad/pycobertura/blob/26e472f1424f5cd499c42232dc5ee12e4042806f/pycobertura/cobertura.py#L371-L418 | [
"def reconcile_lines(lines1, lines2):\n \"\"\"\n Return a dict `{lineno1: lineno2}` which reconciles line numbers `lineno1`\n of list `lines1` to line numbers `lineno2` of list `lines2`. Only lines\n that are common in both sets are present in the dict, lines unique to one\n of the sets are omitted.\... | class CoberturaDiff(object):
"""
Diff Cobertura objects.
"""
def __init__(self, cobertura1, cobertura2):
self.cobertura1 = cobertura1
self.cobertura2 = cobertura2
def has_better_coverage(self):
"""
Return `True` if coverage of has improved, `False` otherwise.
This does not ensure that all changes have been covered. If this is
what you want, use `CoberturaDiff.has_all_changes_covered()` instead.
"""
for filename in self.files():
if self.diff_total_misses(filename) > 0:
return False
return True
def has_all_changes_covered(self):
"""
Return `True` if all changes have been covered, `False` otherwise.
"""
for filename in self.files():
for hunk in self.file_source_hunks(filename):
for line in hunk:
if line.reason is None:
continue # line untouched
if line.status is False:
return False # line not covered
return True
def _diff_attr(self, attr_name, filename):
"""
Return the difference between
`self.cobertura2.<attr_name>(filename)` and
`self.cobertura1.<attr_name>(filename)`.
This generic method is meant to diff the count of methods that return
counts for a given file `filename`, e.g. `Cobertura.total_statements`,
`Cobertura.total_misses`, ...
The returned count may be a float.
"""
if filename is not None:
files = [filename]
else:
files = self.files()
total_count = 0.0
for filename in files:
if self.cobertura1.has_file(filename):
method = getattr(self.cobertura1, attr_name)
count1 = method(filename)
else:
count1 = 0.0
method = getattr(self.cobertura2, attr_name)
count2 = method(filename)
total_count += count2 - count1
return total_count
def diff_total_statements(self, filename=None):
return int(self._diff_attr('total_statements', filename))
def diff_total_misses(self, filename=None):
return int(self._diff_attr('total_misses', filename))
def diff_total_hits(self, filename=None):
return int(self._diff_attr('total_hits', filename))
def diff_line_rate(self, filename=None):
if filename is not None:
return self._diff_attr('line_rate', filename)
return self.cobertura2.line_rate() - self.cobertura1.line_rate()
def diff_missed_lines(self, filename):
"""
Return a list of 2-element tuples `(lineno, is_new)` for the given
file `filename` where `lineno` is a missed line number and `is_new`
indicates whether the missed line was introduced (True) or removed
(False).
"""
line_changed = []
for line in self.file_source(filename):
if line.status is not None:
is_new = not line.status
line_changed.append((line.number, is_new))
return line_changed
def files(self):
"""
Return `self.cobertura2.files()`.
"""
return self.cobertura2.files()
def file_source_hunks(self, filename):
"""
Like `CoberturaDiff.file_source`, but returns a list of line hunks of
the lines that have changed for the given file `filename`. An empty
list means that the file has no lines that have a change in coverage
status.
"""
lines = self.file_source(filename)
hunks = hunkify_lines(lines)
return hunks
|
aconrad/pycobertura | pycobertura/cobertura.py | CoberturaDiff.file_source_hunks | python | def file_source_hunks(self, filename):
lines = self.file_source(filename)
hunks = hunkify_lines(lines)
return hunks | Like `CoberturaDiff.file_source`, but returns a list of line hunks of
the lines that have changed for the given file `filename`. An empty
list means that the file has no lines that have a change in coverage
status. | train | https://github.com/aconrad/pycobertura/blob/26e472f1424f5cd499c42232dc5ee12e4042806f/pycobertura/cobertura.py#L420-L429 | [
"def hunkify_lines(lines, context=3):\n \"\"\"\n Return a list of line hunks given a list of lines `lines`. The number of\n context lines can be control with `context` which will return line hunks\n surrounded with `context` lines before and after the code change.\n \"\"\"\n # Find contiguous line... | class CoberturaDiff(object):
"""
Diff Cobertura objects.
"""
def __init__(self, cobertura1, cobertura2):
self.cobertura1 = cobertura1
self.cobertura2 = cobertura2
def has_better_coverage(self):
"""
Return `True` if coverage of has improved, `False` otherwise.
This does not ensure that all changes have been covered. If this is
what you want, use `CoberturaDiff.has_all_changes_covered()` instead.
"""
for filename in self.files():
if self.diff_total_misses(filename) > 0:
return False
return True
def has_all_changes_covered(self):
"""
Return `True` if all changes have been covered, `False` otherwise.
"""
for filename in self.files():
for hunk in self.file_source_hunks(filename):
for line in hunk:
if line.reason is None:
continue # line untouched
if line.status is False:
return False # line not covered
return True
def _diff_attr(self, attr_name, filename):
"""
Return the difference between
`self.cobertura2.<attr_name>(filename)` and
`self.cobertura1.<attr_name>(filename)`.
This generic method is meant to diff the count of methods that return
counts for a given file `filename`, e.g. `Cobertura.total_statements`,
`Cobertura.total_misses`, ...
The returned count may be a float.
"""
if filename is not None:
files = [filename]
else:
files = self.files()
total_count = 0.0
for filename in files:
if self.cobertura1.has_file(filename):
method = getattr(self.cobertura1, attr_name)
count1 = method(filename)
else:
count1 = 0.0
method = getattr(self.cobertura2, attr_name)
count2 = method(filename)
total_count += count2 - count1
return total_count
def diff_total_statements(self, filename=None):
return int(self._diff_attr('total_statements', filename))
def diff_total_misses(self, filename=None):
return int(self._diff_attr('total_misses', filename))
def diff_total_hits(self, filename=None):
return int(self._diff_attr('total_hits', filename))
def diff_line_rate(self, filename=None):
if filename is not None:
return self._diff_attr('line_rate', filename)
return self.cobertura2.line_rate() - self.cobertura1.line_rate()
def diff_missed_lines(self, filename):
"""
Return a list of 2-element tuples `(lineno, is_new)` for the given
file `filename` where `lineno` is a missed line number and `is_new`
indicates whether the missed line was introduced (True) or removed
(False).
"""
line_changed = []
for line in self.file_source(filename):
if line.status is not None:
is_new = not line.status
line_changed.append((line.number, is_new))
return line_changed
def files(self):
"""
Return `self.cobertura2.files()`.
"""
return self.cobertura2.files()
def file_source(self, filename):
"""
Return a list of namedtuple `Line` for each line of code found in the
given file `filename`.
"""
if self.cobertura1.has_file(filename) and \
self.cobertura1.filesystem.has_file(filename):
lines1 = self.cobertura1.source_lines(filename)
line_statuses1 = dict(self.cobertura1.line_statuses(
filename))
else:
lines1 = []
line_statuses1 = {}
lines2 = self.cobertura2.source_lines(filename)
line_statuses2 = dict(self.cobertura2.line_statuses(filename))
# Build a dict of lineno2 -> lineno1
lineno_map = reconcile_lines(lines2, lines1)
lines = []
for lineno, source in enumerate(lines2, start=1):
status = None
reason = None
if lineno not in lineno_map:
# line was added or removed, just use whatever coverage status
# is available as there is nothing to compare against.
status = line_statuses2.get(lineno)
reason = 'line-edit'
else:
other_lineno = lineno_map[lineno]
line_status1 = line_statuses1.get(other_lineno)
line_status2 = line_statuses2.get(lineno)
if line_status1 is line_status2:
status = None # unchanged
reason = None
elif line_status1 is True and line_status2 is False:
status = False # decreased
reason = 'cov-down'
elif line_status1 is False and line_status2 is True:
status = True # increased
reason = 'cov-up'
line = Line(lineno, source, status, reason)
lines.append(line)
return lines
|
aconrad/pycobertura | pycobertura/utils.py | rangify | python | def rangify(number_list):
if not number_list:
return number_list
ranges = []
range_start = prev_num = number_list[0]
for num in number_list[1:]:
if num != (prev_num + 1):
ranges.append((range_start, prev_num))
range_start = num
prev_num = num
ranges.append((range_start, prev_num))
return ranges | Assumes the list is sorted. | train | https://github.com/aconrad/pycobertura/blob/26e472f1424f5cd499c42232dc5ee12e4042806f/pycobertura/utils.py#L61-L76 | null | import colorama
import difflib
from functools import partial
# Recipe from https://github.com/ActiveState/
# code/recipes/Python/577452_memoize_decorator_instance/recipe-577452.py
class memoize(object):
"""cache the return value of a method
This class is meant to be used as a decorator of methods. The return value
from a given method invocation will be cached on the instance whose method
was invoked. All arguments passed to a method decorated with memoize must
be hashable.
If a memoized method is invoked directly on its class the result will not
be cached. Instead the method will be invoked like a static method:
class Obj(object):
@memoize
def add_to(self, arg):
return self + arg
Obj.add_to(1) # not enough arguments
Obj.add_to(1, 2) # returns 3, result is not cached
"""
def __init__(self, func):
self.func = func
def __get__(self, obj, objtype=None):
if obj is None:
return self.func
return partial(self, obj)
def __call__(self, *args, **kw):
obj = args[0]
try:
cache = obj.__cache
except AttributeError:
cache = obj.__cache = {}
key = (self.func, args[1:], frozenset(kw.items()))
try:
res = cache[key]
except KeyError:
res = cache[key] = self.func(*args, **kw)
return res
def colorize(text, color):
color_code = getattr(colorama.Fore, color.upper())
return '%s%s%s' % (color_code, text, colorama.Fore.RESET)
def red(text):
return colorize(text, 'red')
def green(text):
return colorize(text, 'green')
def extrapolate_coverage(lines_w_status):
"""
Given the following input:
>>> lines_w_status = [
(1, True),
(4, True),
(7, False),
(9, False),
]
Return expanded lines with their extrapolated line status.
>>> extrapolate_coverage(lines_w_status) == [
(1, True),
(2, True),
(3, True),
(4, True),
(5, None),
(6, None),
(7, False),
(8, False),
(9, False),
]
"""
lines = []
prev_lineno = 0
prev_status = True
for lineno, status in lines_w_status:
while (lineno - prev_lineno) > 1:
prev_lineno += 1
if prev_status is status:
lines.append((prev_lineno, status))
else:
lines.append((prev_lineno, None))
lines.append((lineno, status))
prev_lineno = lineno
prev_status = status
return lines
def reconcile_lines(lines1, lines2):
"""
Return a dict `{lineno1: lineno2}` which reconciles line numbers `lineno1`
of list `lines1` to line numbers `lineno2` of list `lines2`. Only lines
that are common in both sets are present in the dict, lines unique to one
of the sets are omitted.
"""
differ = difflib.Differ()
diff = differ.compare(lines1, lines2)
SAME = ' '
ADDED = '+ '
REMOVED = '- '
INFO = '? '
lineno_map = {} # {lineno1: lineno2, ...}
lineno1_offset = 0
lineno2 = 1
for diffline in diff:
if diffline.startswith(INFO):
continue
if diffline.startswith(SAME):
lineno1 = lineno2 + lineno1_offset
lineno_map[lineno1] = lineno2
elif diffline.startswith(ADDED):
lineno1_offset -= 1
elif diffline.startswith(REMOVED):
lineno1_offset += 1
continue
lineno2 += 1
return lineno_map
def hunkify_lines(lines, context=3):
"""
Return a list of line hunks given a list of lines `lines`. The number of
context lines can be control with `context` which will return line hunks
surrounded with `context` lines before and after the code change.
"""
# Find contiguous line changes
ranges = []
range_start = None
for i, line in enumerate(lines):
if line.status is not None:
if range_start is None:
range_start = i
continue
elif range_start is not None:
range_stop = i
ranges.append((range_start, range_stop))
range_start = None
else:
# Append the last range
if range_start is not None:
range_stop = i
ranges.append((range_start, range_stop))
# add context
ranges_w_context = []
for range_start, range_stop in ranges:
range_start = range_start - context
range_start = range_start if range_start >= 0 else 0
range_stop = range_stop + context
ranges_w_context.append((range_start, range_stop))
# merge overlapping hunks
merged_ranges = ranges_w_context[:1]
for range_start, range_stop in ranges_w_context[1:]:
prev_start, prev_stop = merged_ranges[-1]
if range_start <= prev_stop:
range_start = prev_start
merged_ranges[-1] = (range_start, range_stop)
else:
merged_ranges.append((range_start, range_stop))
# build final hunks
hunks = []
for range_start, range_stop in merged_ranges:
hunk = lines[range_start:range_stop]
hunks.append(hunk)
return hunks
|
aconrad/pycobertura | pycobertura/utils.py | extrapolate_coverage | python | def extrapolate_coverage(lines_w_status):
lines = []
prev_lineno = 0
prev_status = True
for lineno, status in lines_w_status:
while (lineno - prev_lineno) > 1:
prev_lineno += 1
if prev_status is status:
lines.append((prev_lineno, status))
else:
lines.append((prev_lineno, None))
lines.append((lineno, status))
prev_lineno = lineno
prev_status = status
return lines | Given the following input:
>>> lines_w_status = [
(1, True),
(4, True),
(7, False),
(9, False),
]
Return expanded lines with their extrapolated line status.
>>> extrapolate_coverage(lines_w_status) == [
(1, True),
(2, True),
(3, True),
(4, True),
(5, None),
(6, None),
(7, False),
(8, False),
(9, False),
] | train | https://github.com/aconrad/pycobertura/blob/26e472f1424f5cd499c42232dc5ee12e4042806f/pycobertura/utils.py#L79-L120 | null | import colorama
import difflib
from functools import partial
# Recipe from https://github.com/ActiveState/
# code/recipes/Python/577452_memoize_decorator_instance/recipe-577452.py
class memoize(object):
"""cache the return value of a method
This class is meant to be used as a decorator of methods. The return value
from a given method invocation will be cached on the instance whose method
was invoked. All arguments passed to a method decorated with memoize must
be hashable.
If a memoized method is invoked directly on its class the result will not
be cached. Instead the method will be invoked like a static method:
class Obj(object):
@memoize
def add_to(self, arg):
return self + arg
Obj.add_to(1) # not enough arguments
Obj.add_to(1, 2) # returns 3, result is not cached
"""
def __init__(self, func):
self.func = func
def __get__(self, obj, objtype=None):
if obj is None:
return self.func
return partial(self, obj)
def __call__(self, *args, **kw):
obj = args[0]
try:
cache = obj.__cache
except AttributeError:
cache = obj.__cache = {}
key = (self.func, args[1:], frozenset(kw.items()))
try:
res = cache[key]
except KeyError:
res = cache[key] = self.func(*args, **kw)
return res
def colorize(text, color):
color_code = getattr(colorama.Fore, color.upper())
return '%s%s%s' % (color_code, text, colorama.Fore.RESET)
def red(text):
return colorize(text, 'red')
def green(text):
return colorize(text, 'green')
def rangify(number_list):
"""Assumes the list is sorted."""
if not number_list:
return number_list
ranges = []
range_start = prev_num = number_list[0]
for num in number_list[1:]:
if num != (prev_num + 1):
ranges.append((range_start, prev_num))
range_start = num
prev_num = num
ranges.append((range_start, prev_num))
return ranges
def reconcile_lines(lines1, lines2):
"""
Return a dict `{lineno1: lineno2}` which reconciles line numbers `lineno1`
of list `lines1` to line numbers `lineno2` of list `lines2`. Only lines
that are common in both sets are present in the dict, lines unique to one
of the sets are omitted.
"""
differ = difflib.Differ()
diff = differ.compare(lines1, lines2)
SAME = ' '
ADDED = '+ '
REMOVED = '- '
INFO = '? '
lineno_map = {} # {lineno1: lineno2, ...}
lineno1_offset = 0
lineno2 = 1
for diffline in diff:
if diffline.startswith(INFO):
continue
if diffline.startswith(SAME):
lineno1 = lineno2 + lineno1_offset
lineno_map[lineno1] = lineno2
elif diffline.startswith(ADDED):
lineno1_offset -= 1
elif diffline.startswith(REMOVED):
lineno1_offset += 1
continue
lineno2 += 1
return lineno_map
def hunkify_lines(lines, context=3):
"""
Return a list of line hunks given a list of lines `lines`. The number of
context lines can be control with `context` which will return line hunks
surrounded with `context` lines before and after the code change.
"""
# Find contiguous line changes
ranges = []
range_start = None
for i, line in enumerate(lines):
if line.status is not None:
if range_start is None:
range_start = i
continue
elif range_start is not None:
range_stop = i
ranges.append((range_start, range_stop))
range_start = None
else:
# Append the last range
if range_start is not None:
range_stop = i
ranges.append((range_start, range_stop))
# add context
ranges_w_context = []
for range_start, range_stop in ranges:
range_start = range_start - context
range_start = range_start if range_start >= 0 else 0
range_stop = range_stop + context
ranges_w_context.append((range_start, range_stop))
# merge overlapping hunks
merged_ranges = ranges_w_context[:1]
for range_start, range_stop in ranges_w_context[1:]:
prev_start, prev_stop = merged_ranges[-1]
if range_start <= prev_stop:
range_start = prev_start
merged_ranges[-1] = (range_start, range_stop)
else:
merged_ranges.append((range_start, range_stop))
# build final hunks
hunks = []
for range_start, range_stop in merged_ranges:
hunk = lines[range_start:range_stop]
hunks.append(hunk)
return hunks
|
aconrad/pycobertura | pycobertura/utils.py | reconcile_lines | python | def reconcile_lines(lines1, lines2):
differ = difflib.Differ()
diff = differ.compare(lines1, lines2)
SAME = ' '
ADDED = '+ '
REMOVED = '- '
INFO = '? '
lineno_map = {} # {lineno1: lineno2, ...}
lineno1_offset = 0
lineno2 = 1
for diffline in diff:
if diffline.startswith(INFO):
continue
if diffline.startswith(SAME):
lineno1 = lineno2 + lineno1_offset
lineno_map[lineno1] = lineno2
elif diffline.startswith(ADDED):
lineno1_offset -= 1
elif diffline.startswith(REMOVED):
lineno1_offset += 1
continue
lineno2 += 1
return lineno_map | Return a dict `{lineno1: lineno2}` which reconciles line numbers `lineno1`
of list `lines1` to line numbers `lineno2` of list `lines2`. Only lines
that are common in both sets are present in the dict, lines unique to one
of the sets are omitted. | train | https://github.com/aconrad/pycobertura/blob/26e472f1424f5cd499c42232dc5ee12e4042806f/pycobertura/utils.py#L123-L159 | null | import colorama
import difflib
from functools import partial
# Recipe from https://github.com/ActiveState/
# code/recipes/Python/577452_memoize_decorator_instance/recipe-577452.py
class memoize(object):
"""cache the return value of a method
This class is meant to be used as a decorator of methods. The return value
from a given method invocation will be cached on the instance whose method
was invoked. All arguments passed to a method decorated with memoize must
be hashable.
If a memoized method is invoked directly on its class the result will not
be cached. Instead the method will be invoked like a static method:
class Obj(object):
@memoize
def add_to(self, arg):
return self + arg
Obj.add_to(1) # not enough arguments
Obj.add_to(1, 2) # returns 3, result is not cached
"""
def __init__(self, func):
self.func = func
def __get__(self, obj, objtype=None):
if obj is None:
return self.func
return partial(self, obj)
def __call__(self, *args, **kw):
obj = args[0]
try:
cache = obj.__cache
except AttributeError:
cache = obj.__cache = {}
key = (self.func, args[1:], frozenset(kw.items()))
try:
res = cache[key]
except KeyError:
res = cache[key] = self.func(*args, **kw)
return res
def colorize(text, color):
color_code = getattr(colorama.Fore, color.upper())
return '%s%s%s' % (color_code, text, colorama.Fore.RESET)
def red(text):
return colorize(text, 'red')
def green(text):
return colorize(text, 'green')
def rangify(number_list):
"""Assumes the list is sorted."""
if not number_list:
return number_list
ranges = []
range_start = prev_num = number_list[0]
for num in number_list[1:]:
if num != (prev_num + 1):
ranges.append((range_start, prev_num))
range_start = num
prev_num = num
ranges.append((range_start, prev_num))
return ranges
def extrapolate_coverage(lines_w_status):
"""
Given the following input:
>>> lines_w_status = [
(1, True),
(4, True),
(7, False),
(9, False),
]
Return expanded lines with their extrapolated line status.
>>> extrapolate_coverage(lines_w_status) == [
(1, True),
(2, True),
(3, True),
(4, True),
(5, None),
(6, None),
(7, False),
(8, False),
(9, False),
]
"""
lines = []
prev_lineno = 0
prev_status = True
for lineno, status in lines_w_status:
while (lineno - prev_lineno) > 1:
prev_lineno += 1
if prev_status is status:
lines.append((prev_lineno, status))
else:
lines.append((prev_lineno, None))
lines.append((lineno, status))
prev_lineno = lineno
prev_status = status
return lines
def hunkify_lines(lines, context=3):
"""
Return a list of line hunks given a list of lines `lines`. The number of
context lines can be control with `context` which will return line hunks
surrounded with `context` lines before and after the code change.
"""
# Find contiguous line changes
ranges = []
range_start = None
for i, line in enumerate(lines):
if line.status is not None:
if range_start is None:
range_start = i
continue
elif range_start is not None:
range_stop = i
ranges.append((range_start, range_stop))
range_start = None
else:
# Append the last range
if range_start is not None:
range_stop = i
ranges.append((range_start, range_stop))
# add context
ranges_w_context = []
for range_start, range_stop in ranges:
range_start = range_start - context
range_start = range_start if range_start >= 0 else 0
range_stop = range_stop + context
ranges_w_context.append((range_start, range_stop))
# merge overlapping hunks
merged_ranges = ranges_w_context[:1]
for range_start, range_stop in ranges_w_context[1:]:
prev_start, prev_stop = merged_ranges[-1]
if range_start <= prev_stop:
range_start = prev_start
merged_ranges[-1] = (range_start, range_stop)
else:
merged_ranges.append((range_start, range_stop))
# build final hunks
hunks = []
for range_start, range_stop in merged_ranges:
hunk = lines[range_start:range_stop]
hunks.append(hunk)
return hunks
|
aconrad/pycobertura | pycobertura/utils.py | hunkify_lines | python | def hunkify_lines(lines, context=3):
# Find contiguous line changes
ranges = []
range_start = None
for i, line in enumerate(lines):
if line.status is not None:
if range_start is None:
range_start = i
continue
elif range_start is not None:
range_stop = i
ranges.append((range_start, range_stop))
range_start = None
else:
# Append the last range
if range_start is not None:
range_stop = i
ranges.append((range_start, range_stop))
# add context
ranges_w_context = []
for range_start, range_stop in ranges:
range_start = range_start - context
range_start = range_start if range_start >= 0 else 0
range_stop = range_stop + context
ranges_w_context.append((range_start, range_stop))
# merge overlapping hunks
merged_ranges = ranges_w_context[:1]
for range_start, range_stop in ranges_w_context[1:]:
prev_start, prev_stop = merged_ranges[-1]
if range_start <= prev_stop:
range_start = prev_start
merged_ranges[-1] = (range_start, range_stop)
else:
merged_ranges.append((range_start, range_stop))
# build final hunks
hunks = []
for range_start, range_stop in merged_ranges:
hunk = lines[range_start:range_stop]
hunks.append(hunk)
return hunks | Return a list of line hunks given a list of lines `lines`. The number of
context lines can be control with `context` which will return line hunks
surrounded with `context` lines before and after the code change. | train | https://github.com/aconrad/pycobertura/blob/26e472f1424f5cd499c42232dc5ee12e4042806f/pycobertura/utils.py#L162-L210 | null | import colorama
import difflib
from functools import partial
# Recipe from https://github.com/ActiveState/
# code/recipes/Python/577452_memoize_decorator_instance/recipe-577452.py
class memoize(object):
"""cache the return value of a method
This class is meant to be used as a decorator of methods. The return value
from a given method invocation will be cached on the instance whose method
was invoked. All arguments passed to a method decorated with memoize must
be hashable.
If a memoized method is invoked directly on its class the result will not
be cached. Instead the method will be invoked like a static method:
class Obj(object):
@memoize
def add_to(self, arg):
return self + arg
Obj.add_to(1) # not enough arguments
Obj.add_to(1, 2) # returns 3, result is not cached
"""
def __init__(self, func):
self.func = func
def __get__(self, obj, objtype=None):
if obj is None:
return self.func
return partial(self, obj)
def __call__(self, *args, **kw):
obj = args[0]
try:
cache = obj.__cache
except AttributeError:
cache = obj.__cache = {}
key = (self.func, args[1:], frozenset(kw.items()))
try:
res = cache[key]
except KeyError:
res = cache[key] = self.func(*args, **kw)
return res
def colorize(text, color):
color_code = getattr(colorama.Fore, color.upper())
return '%s%s%s' % (color_code, text, colorama.Fore.RESET)
def red(text):
return colorize(text, 'red')
def green(text):
return colorize(text, 'green')
def rangify(number_list):
"""Assumes the list is sorted."""
if not number_list:
return number_list
ranges = []
range_start = prev_num = number_list[0]
for num in number_list[1:]:
if num != (prev_num + 1):
ranges.append((range_start, prev_num))
range_start = num
prev_num = num
ranges.append((range_start, prev_num))
return ranges
def extrapolate_coverage(lines_w_status):
"""
Given the following input:
>>> lines_w_status = [
(1, True),
(4, True),
(7, False),
(9, False),
]
Return expanded lines with their extrapolated line status.
>>> extrapolate_coverage(lines_w_status) == [
(1, True),
(2, True),
(3, True),
(4, True),
(5, None),
(6, None),
(7, False),
(8, False),
(9, False),
]
"""
lines = []
prev_lineno = 0
prev_status = True
for lineno, status in lines_w_status:
while (lineno - prev_lineno) > 1:
prev_lineno += 1
if prev_status is status:
lines.append((prev_lineno, status))
else:
lines.append((prev_lineno, None))
lines.append((lineno, status))
prev_lineno = lineno
prev_status = status
return lines
def reconcile_lines(lines1, lines2):
"""
Return a dict `{lineno1: lineno2}` which reconciles line numbers `lineno1`
of list `lines1` to line numbers `lineno2` of list `lines2`. Only lines
that are common in both sets are present in the dict, lines unique to one
of the sets are omitted.
"""
differ = difflib.Differ()
diff = differ.compare(lines1, lines2)
SAME = ' '
ADDED = '+ '
REMOVED = '- '
INFO = '? '
lineno_map = {} # {lineno1: lineno2, ...}
lineno1_offset = 0
lineno2 = 1
for diffline in diff:
if diffline.startswith(INFO):
continue
if diffline.startswith(SAME):
lineno1 = lineno2 + lineno1_offset
lineno_map[lineno1] = lineno2
elif diffline.startswith(ADDED):
lineno1_offset -= 1
elif diffline.startswith(REMOVED):
lineno1_offset += 1
continue
lineno2 += 1
return lineno_map
|
aconrad/pycobertura | pycobertura/cli.py | show | python | def show(cobertura_file, format, output, source, source_prefix):
cobertura = Cobertura(cobertura_file, source=source)
Reporter = reporters[format]
reporter = Reporter(cobertura)
report = reporter.generate()
if not isinstance(report, bytes):
report = report.encode('utf-8')
isatty = True if output is None else output.isatty()
click.echo(report, file=output, nl=isatty) | show coverage summary of a Cobertura report | train | https://github.com/aconrad/pycobertura/blob/26e472f1424f5cd499c42232dc5ee12e4042806f/pycobertura/cli.py#L65-L76 | null | import click
from pycobertura.cobertura import Cobertura
from pycobertura.reporters import (
HtmlReporter, TextReporter, HtmlReporterDelta, TextReporterDelta
)
pycobertura = click.Group()
reporters = {
'html': HtmlReporter,
'text': TextReporter,
}
class ExitCodes:
OK = 0
EXCEPTION = 1
COVERAGE_WORSENED = 2
NOT_ALL_CHANGES_COVERED = 3
def get_exit_code(differ, source):
# Compute the non-zero exit code. This is a 2-step process which involves
# checking whether code coverage is any better first and then check if all
# changes are covered (stricter) which can only be done if the source code
# is available (and enabled via the --source option).
if not differ.has_better_coverage():
return ExitCodes.COVERAGE_WORSENED
if source:
if differ.has_all_changes_covered():
return ExitCodes.OK
else:
return ExitCodes.NOT_ALL_CHANGES_COVERED
else:
return ExitCodes.OK
@pycobertura.command()
@click.argument('cobertura_file')
@click.option(
'-f', '--format', default='text',
type=click.Choice(list(reporters))
)
@click.option(
'-o', '--output', metavar='<file>', type=click.File('wb'),
help='Write output to <file> instead of stdout.'
)
@click.option(
'-s', '--source', metavar='<source-dir-or-zip>',
help='Provide path to source code directory for HTML output. The path can '
'also be a zip archive instead of a directory.'
)
@click.option(
'-p', '--source-prefix', metavar='<dir-prefix>',
help='For every file found in the coverage report, it will use this '
'prefix to lookup files on disk. This is especially useful when '
'the --source is a zip archive and the files were zipped under '
'a directory prefix that is not part of the source.',
)
delta_reporters = {
'text': TextReporterDelta,
'html': HtmlReporterDelta,
}
@pycobertura.command(help="""\
The diff command compares and shows the changes between two Cobertura reports.
NOTE: Reporting missing lines or showing the source code with the diff command
can only be accurately computed if the versions of the source code used to
generate each of the coverage reports is accessible. By default, the source
will read from the Cobertura report and resolved relatively from the report's
location. If the source is not accessible from the report's location, the
options `--source1` and `--source2` are necessary to point to the source code
directories (or zip archives). If the source is not available at all, pass
`--no-source` but missing lines and source code will not be reported.
""")
@click.argument('cobertura_file1')
@click.argument('cobertura_file2')
@click.option(
'--color/--no-color', default=None,
help='Colorize the output. By default, pycobertura emits color codes only '
'when standard output is connected to a terminal. This has no effect '
'with the HTML output format.')
@click.option(
'-f', '--format', default='text',
type=click.Choice(list(delta_reporters))
)
@click.option(
'-o', '--output', metavar='<file>', type=click.File('wb'),
help='Write output to <file> instead of stdout.'
)
@click.option(
'-s1', '--source1', metavar='<source-dir1-or-zip-archive>',
help='Provide path to source code directory or zip archive of first '
'Cobertura report. This is necessary if the filename path defined '
'in the report is not accessible from the location of the report.'
)
@click.option(
'-s2', '--source2', metavar='<source-dir2-or-zip-archive>',
help='Like --source1 but for the second coverage report of the diff.'
)
@click.option(
'-p1', '--source-prefix1', metavar='<dir-prefix1>',
help='For every file found in the coverage report, it will use this '
'prefix to lookup files on disk. This is especially useful when '
'the --source1 is a zip archive and the files were zipped under '
'a directory prefix that is not part of the source',
)
@click.option(
'-p2', '--source-prefix2', metavar='<dir-prefix2>',
help='Like --source-prefix1, but for applies for --source2.',
)
@click.option(
'--source/--no-source', default=True,
help='Show missing lines and source code. When enabled (default), this '
'option requires access to the source code that was used to generate '
'both Cobertura reports (see --source1 and --source2). When '
'`--no-source` is passed, missing lines and the source code will '
'not be displayed.'
)
def diff(
cobertura_file1, cobertura_file2,
color, format, output, source1, source2,
source_prefix1, source_prefix2, source):
"""compare coverage of two Cobertura reports"""
cobertura1 = Cobertura(
cobertura_file1,
source=source1,
source_prefix=source_prefix1
)
cobertura2 = Cobertura(
cobertura_file2,
source=source2,
source_prefix=source_prefix2
)
Reporter = delta_reporters[format]
reporter_args = [cobertura1, cobertura2]
reporter_kwargs = {'show_source': source}
isatty = True if output is None else output.isatty()
if format == 'text':
color = isatty if color is None else color is True
reporter_kwargs['color'] = color
reporter = Reporter(*reporter_args, **reporter_kwargs)
report = reporter.generate()
if not isinstance(report, bytes):
report = report.encode('utf-8')
click.echo(report, file=output, nl=isatty, color=color)
exit_code = get_exit_code(reporter.differ, source)
raise SystemExit(exit_code)
|
aconrad/pycobertura | pycobertura/cli.py | diff | python | def diff(
cobertura_file1, cobertura_file2,
color, format, output, source1, source2,
source_prefix1, source_prefix2, source):
cobertura1 = Cobertura(
cobertura_file1,
source=source1,
source_prefix=source_prefix1
)
cobertura2 = Cobertura(
cobertura_file2,
source=source2,
source_prefix=source_prefix2
)
Reporter = delta_reporters[format]
reporter_args = [cobertura1, cobertura2]
reporter_kwargs = {'show_source': source}
isatty = True if output is None else output.isatty()
if format == 'text':
color = isatty if color is None else color is True
reporter_kwargs['color'] = color
reporter = Reporter(*reporter_args, **reporter_kwargs)
report = reporter.generate()
if not isinstance(report, bytes):
report = report.encode('utf-8')
click.echo(report, file=output, nl=isatty, color=color)
exit_code = get_exit_code(reporter.differ, source)
raise SystemExit(exit_code) | compare coverage of two Cobertura reports | train | https://github.com/aconrad/pycobertura/blob/26e472f1424f5cd499c42232dc5ee12e4042806f/pycobertura/cli.py#L141-L176 | [
"def get_exit_code(differ, source):\n # Compute the non-zero exit code. This is a 2-step process which involves\n # checking whether code coverage is any better first and then check if all\n # changes are covered (stricter) which can only be done if the source code\n # is available (and enabled via the ... | import click
from pycobertura.cobertura import Cobertura
from pycobertura.reporters import (
HtmlReporter, TextReporter, HtmlReporterDelta, TextReporterDelta
)
pycobertura = click.Group()
reporters = {
'html': HtmlReporter,
'text': TextReporter,
}
class ExitCodes:
OK = 0
EXCEPTION = 1
COVERAGE_WORSENED = 2
NOT_ALL_CHANGES_COVERED = 3
def get_exit_code(differ, source):
# Compute the non-zero exit code. This is a 2-step process which involves
# checking whether code coverage is any better first and then check if all
# changes are covered (stricter) which can only be done if the source code
# is available (and enabled via the --source option).
if not differ.has_better_coverage():
return ExitCodes.COVERAGE_WORSENED
if source:
if differ.has_all_changes_covered():
return ExitCodes.OK
else:
return ExitCodes.NOT_ALL_CHANGES_COVERED
else:
return ExitCodes.OK
@pycobertura.command()
@click.argument('cobertura_file')
@click.option(
'-f', '--format', default='text',
type=click.Choice(list(reporters))
)
@click.option(
'-o', '--output', metavar='<file>', type=click.File('wb'),
help='Write output to <file> instead of stdout.'
)
@click.option(
'-s', '--source', metavar='<source-dir-or-zip>',
help='Provide path to source code directory for HTML output. The path can '
'also be a zip archive instead of a directory.'
)
@click.option(
'-p', '--source-prefix', metavar='<dir-prefix>',
help='For every file found in the coverage report, it will use this '
'prefix to lookup files on disk. This is especially useful when '
'the --source is a zip archive and the files were zipped under '
'a directory prefix that is not part of the source.',
)
def show(cobertura_file, format, output, source, source_prefix):
"""show coverage summary of a Cobertura report"""
cobertura = Cobertura(cobertura_file, source=source)
Reporter = reporters[format]
reporter = Reporter(cobertura)
report = reporter.generate()
if not isinstance(report, bytes):
report = report.encode('utf-8')
isatty = True if output is None else output.isatty()
click.echo(report, file=output, nl=isatty)
delta_reporters = {
'text': TextReporterDelta,
'html': HtmlReporterDelta,
}
@pycobertura.command(help="""\
The diff command compares and shows the changes between two Cobertura reports.
NOTE: Reporting missing lines or showing the source code with the diff command
can only be accurately computed if the versions of the source code used to
generate each of the coverage reports is accessible. By default, the source
will read from the Cobertura report and resolved relatively from the report's
location. If the source is not accessible from the report's location, the
options `--source1` and `--source2` are necessary to point to the source code
directories (or zip archives). If the source is not available at all, pass
`--no-source` but missing lines and source code will not be reported.
""")
@click.argument('cobertura_file1')
@click.argument('cobertura_file2')
@click.option(
'--color/--no-color', default=None,
help='Colorize the output. By default, pycobertura emits color codes only '
'when standard output is connected to a terminal. This has no effect '
'with the HTML output format.')
@click.option(
'-f', '--format', default='text',
type=click.Choice(list(delta_reporters))
)
@click.option(
'-o', '--output', metavar='<file>', type=click.File('wb'),
help='Write output to <file> instead of stdout.'
)
@click.option(
'-s1', '--source1', metavar='<source-dir1-or-zip-archive>',
help='Provide path to source code directory or zip archive of first '
'Cobertura report. This is necessary if the filename path defined '
'in the report is not accessible from the location of the report.'
)
@click.option(
'-s2', '--source2', metavar='<source-dir2-or-zip-archive>',
help='Like --source1 but for the second coverage report of the diff.'
)
@click.option(
'-p1', '--source-prefix1', metavar='<dir-prefix1>',
help='For every file found in the coverage report, it will use this '
'prefix to lookup files on disk. This is especially useful when '
'the --source1 is a zip archive and the files were zipped under '
'a directory prefix that is not part of the source',
)
@click.option(
'-p2', '--source-prefix2', metavar='<dir-prefix2>',
help='Like --source-prefix1, but for applies for --source2.',
)
@click.option(
'--source/--no-source', default=True,
help='Show missing lines and source code. When enabled (default), this '
'option requires access to the source code that was used to generate '
'both Cobertura reports (see --source1 and --source2). When '
'`--no-source` is passed, missing lines and the source code will '
'not be displayed.'
)
|
aconrad/pycobertura | pycobertura/filesystem.py | DirectoryFileSystem.open | python | def open(self, filename):
filename = self.real_filename(filename)
if not os.path.exists(filename):
raise self.FileNotFound(filename)
with codecs.open(filename, encoding='utf-8') as f:
yield f | Yield a file-like object for file `filename`.
This function is a context manager. | train | https://github.com/aconrad/pycobertura/blob/26e472f1424f5cd499c42232dc5ee12e4042806f/pycobertura/filesystem.py#L31-L43 | [
"def real_filename(self, filename):\n if self.source_prefix is not None:\n filename = os.path.join(self.source_prefix, filename)\n return os.path.join(self.source_dir, filename)\n"
] | class DirectoryFileSystem(FileSystem):
def __init__(self, source_dir, source_prefix=None):
self.source_dir = source_dir
self.source_prefix = source_prefix
def real_filename(self, filename):
if self.source_prefix is not None:
filename = os.path.join(self.source_prefix, filename)
return os.path.join(self.source_dir, filename)
def has_file(self, filename):
# FIXME: make this O(1)
filename = self.real_filename(filename)
return os.path.isfile(filename)
@contextmanager
|
rbarrois/xworkflows | src/xworkflows/base.py | _setup_states | python | def _setup_states(state_definitions, prev=()):
states = list(prev)
for state_def in state_definitions:
if len(state_def) != 2:
raise TypeError(
"The 'state' attribute of a workflow should be "
"a two-tuple of strings; got %r instead." % (state_def,)
)
name, title = state_def
state = State(name, title)
if any(st.name == name for st in states):
# Replacing an existing state
states = [state if st.name == name else st for st in states]
else:
states.append(state)
return StateList(states) | Create a StateList object from a 'states' Workflow attribute. | train | https://github.com/rbarrois/xworkflows/blob/4a94b04ba83cb43f61d4b0f7db6964a667c86b5b/src/xworkflows/base.py#L165-L181 | null | # -*- coding: utf-8 -*-
# Copyright (c) 2011-2013 Raphaël Barrois
# This code is distributed under the two-clause BSD License.
"""Base components of XWorkflows."""
import logging
import re
import warnings
from .compat import is_callable, is_python3, is_string, u
from . import utils
class WorkflowError(Exception):
"""Base class for errors from the xworkflows module."""
class AbortTransition(WorkflowError):
"""Raised to prevent a transition from proceeding."""
class InvalidTransitionError(AbortTransition):
"""Raised when trying to perform a transition not available from current state."""
class ForbiddenTransition(AbortTransition):
"""Raised when the 'check' hook of a transition was defined and returned False."""
class State(object):
"""A state within a workflow.
Attributes:
name (str): the name of the state
title (str): the human-readable title for the state
"""
STATE_NAME_RE = re.compile('\w+$')
def __init__(self, name, title):
if not self.STATE_NAME_RE.match(name):
raise ValueError('Invalid state name %s.' % name)
self.name = name
self.title = title
def __str__(self):
return self.name
def __repr__(self):
return '<%s: %r>' % (self.__class__.__name__, self.name)
class StateList(object):
"""A list of states."""
def __init__(self, states):
self._states = dict((st.name, st) for st in states)
self._order = tuple(st.name for st in states)
def __getattr__(self, name):
try:
return self._states[name]
except KeyError:
raise AttributeError('StateList %s has no state named %s' % (self, name))
def __len__(self):
return len(self._states)
def __getitem__(self, name_or_state):
if isinstance(name_or_state, State):
return self._states[name_or_state.name]
else:
return self._states[name_or_state]
def __repr__(self):
return '%s(%r)' % (self.__class__.__name__, self._states)
def __iter__(self):
for name in self._order:
yield self._states[name]
def __contains__(self, state):
if isinstance(state, State):
return state.name in self._states and self._states[state.name] == state
else: # Expect a state name
return state in self._states
class Transition(object):
"""A transition.
Attributes:
name (str): the name of the Transition
source (State list): the 'source' states of the transition
target (State): the 'target' state of the transition
"""
def __init__(self, name, source, target):
self.name = name
if isinstance(source, State):
source = [source]
self.source = source
self.target = target
def __repr__(self):
return '%s(%r, %r, %r)' % (self.__class__.__name__,
self.name, self.source, self.target)
class TransitionList(object):
"""Holder for the transitions of a given workflow."""
def __init__(self, transitions):
"""Create a TransitionList.
Args:
transitions (list of (name, source, target) tuple): the transitions
to include.
"""
self._transitions = {}
self._order = []
for trdef in transitions:
self._transitions[trdef.name] = trdef
self._order.append(trdef.name)
def __len__(self):
return len(self._transitions)
def __getattr__(self, name):
try:
return self._transitions[name]
except KeyError:
raise AttributeError(
"TransitionList %s has no transition named %s." % (self, name))
def __getitem__(self, name):
return self._transitions[name]
def __iter__(self):
for name in self._order:
yield self._transitions[name]
def __contains__(self, value):
if isinstance(value, Transition):
return value.name in self._transitions and self._transitions[value.name] == value
else:
return value in self._transitions
def available_from(self, state):
"""Retrieve all transitions available from a given state.
Args:
state (State): the initial state.
Yields:
Transition: all transitions starting from that state
"""
for transition in self:
if state in transition.source:
yield transition
def __repr__(self):
return '%s(%r)' % (self.__class__.__name__, self._transitions.values())
def _setup_transitions(tdef, states, prev=()):
"""Create a TransitionList object from a 'transitions' Workflow attribute.
Args:
tdef: list of transition definitions
states (StateList): already parsed state definitions.
prev (TransitionList): transition definitions from a parent.
Returns:
TransitionList: the list of transitions defined in the 'tdef' argument.
"""
trs = list(prev)
for transition in tdef:
if len(transition) == 3:
(name, source, target) = transition
if is_string(source) or isinstance(source, State):
source = [source]
source = [states[src] for src in source]
target = states[target]
tr = Transition(name, source, target)
else:
raise TypeError(
"Elements of the 'transition' attribute of a "
"workflow should be three-tuples; got %r instead." % (transition,)
)
if any(prev_tr.name == tr.name for prev_tr in trs):
# Replacing an existing state
trs = [tr if prev_tr.name == tr.name else prev_tr for prev_tr in trs]
else:
trs.append(tr)
return TransitionList(trs)
HOOK_BEFORE = 'before'
HOOK_AFTER = 'after'
HOOK_CHECK = 'check'
HOOK_ON_ENTER = 'on_enter'
HOOK_ON_LEAVE = 'on_leave'
class Hook(object):
"""A hook to run when a transition occurs.
Attributes:
kind (str): the kind of hook
priority (int): the priority of the hook (higher values run first)
function (callable): the actual function to call
names (str list): name of the transitions or states to which the hook
relates. The special value '*' means 'applies to all transitions/
states'.
Hooks are sortable by descending priority and ascending function name.
Hook kinds are as follow:
- HOOK_BEFORE: run before the related transitions
- HOOK_AFTER: run after the related transitions
- HOOK_CHECK: run as part of pre-transition checks (return value matters)
- HOOK_ON_ENTER: run just after a transition entering a related state
- HOOK_ON_LEAVE: run just before a transition leaving from a related state
"""
def __init__(self, kind, function, *names, **kwargs):
assert kind in (
HOOK_BEFORE, HOOK_AFTER, HOOK_CHECK,
HOOK_ON_ENTER, HOOK_ON_LEAVE)
self.kind = kind
self.priority = kwargs.get('priority', 0)
self.function = function
self.names = names or ('*',)
def _match_state(self, state):
"""Checks whether a given State matches self.names."""
return (self.names == '*'
or state in self.names
or state.name in self.names)
def _match_transition(self, transition):
"""Checks whether a given Transition matches self.names."""
return (self.names == '*'
or transition in self.names
or transition.name in self.names)
def applies_to(self, transition, from_state=None):
"""Whether this hook applies to the given transition/state.
Args:
transition (Transition): the transition to check
from_state (State or None): the state to check. If absent, the check
is 'might this hook apply to the related transition, given a
valid source state'.
"""
if '*' in self.names:
return True
elif self.kind in (HOOK_BEFORE, HOOK_AFTER, HOOK_CHECK):
return self._match_transition(transition)
elif self.kind == HOOK_ON_ENTER:
return self._match_state(transition.target)
elif from_state is None:
# Testing whether the hook may apply to at least one source of the
# transition
return any(self._match_state(src) for src in transition.source)
else:
return self._match_state(from_state)
def __call__(self, *args, **kwargs):
return self.function(*args, **kwargs)
def __eq__(self, other):
"""Equality is based on priority, function and kind."""
if not isinstance(other, Hook):
return NotImplemented
return (
self.priority == other.priority
and self.function == other.function
and self.kind == other.kind
and self.names == other.names
)
def __ne__(self, other):
if not isinstance(other, Hook):
return NotImplemented
return not (self == other)
def __lt__(self, other):
"""Compare hooks of the same kind."""
if not isinstance(other, Hook):
return NotImplemented
return (
(other.priority, self.function.__name__)
< (self.priority, other.function.__name__))
def __gt__(self, other):
"""Compare hooks of the same kind."""
if not isinstance(other, Hook):
return NotImplemented
return (
(other.priority, self.function.__name__)
> (self.priority, other.function.__name__))
def __repr__(self):
return '<%s: %s %r>' % (
self.__class__.__name__, self.kind, self.function)
class ImplementationWrapper(object):
"""Wraps a transition implementation.
Emulates a function behaviour, but provides a few extra features.
Attributes:
instance (WorkflowEnabled): the instance to update
.
field_name (str): the name of the field of the instance to update.
transition (Transition): the transition to perform
workflow (Workflow): the workflow to which this is related.
hooks (Hook list): optional hooks to call during the transition
implementation (callable): the code to invoke between 'before' and the
state update.
"""
def __init__(self, instance, field_name, transition, workflow,
implementation, hooks=None):
self.instance = instance
self.field_name = field_name
self.transition = transition
self.workflow = workflow
self.hooks = hooks or {}
self.implementation = implementation
self.__doc__ = implementation.__doc__
@property
def current_state(self):
return getattr(self.instance, self.field_name)
def _pre_transition_checks(self):
"""Run the pre-transition checks."""
current_state = getattr(self.instance, self.field_name)
if current_state not in self.transition.source:
raise InvalidTransitionError(
"Transition '%s' isn't available from state '%s'." %
(self.transition.name, current_state.name))
for check in self._filter_hooks(HOOK_CHECK):
if not check(self.instance):
raise ForbiddenTransition(
"Transition '%s' was forbidden by "
"custom pre-transition check." % self.transition.name)
def _filter_hooks(self, *hook_kinds):
"""Filter a list of hooks, keeping only applicable ones."""
hooks = sum((self.hooks.get(kind, []) for kind in hook_kinds), [])
return sorted(hook for hook in hooks
if hook.applies_to(self.transition, self.current_state))
def _pre_transition(self, *args, **kwargs):
for hook in self._filter_hooks(HOOK_BEFORE, HOOK_ON_LEAVE):
hook(self.instance, *args, **kwargs)
def _during_transition(self, *args, **kwargs):
return self.implementation(self.instance, *args, **kwargs)
def _log_transition(self, from_state, *args, **kwargs):
self.workflow.log_transition(
self.transition, from_state, self.instance,
*args, **kwargs)
def _post_transition(self, result, *args, **kwargs):
"""Performs post-transition actions."""
for hook in self._filter_hooks(HOOK_AFTER, HOOK_ON_ENTER):
hook(self.instance, result, *args, **kwargs)
def __call__(self, *args, **kwargs):
"""Run the transition, with all checks."""
self._pre_transition_checks()
# Call hooks.
self._pre_transition(*args, **kwargs)
result = self._during_transition(*args, **kwargs)
from_state = getattr(self.instance, self.field_name)
setattr(self.instance, self.field_name, self.transition.target)
# Call hooks.
self._log_transition(from_state, *args, **kwargs)
self._post_transition(result, *args, **kwargs)
return result
def is_available(self):
"""Check whether this transition is available on the current object.
Returns:
bool
"""
try:
self._pre_transition_checks()
except (InvalidTransitionError, ForbiddenTransition):
return False
return True
def __repr__(self):
return "<%s for %r on %r: %r>" % (
self.__class__.__name__,
self.transition.name, self.field_name, self.implementation)
class ImplementationProperty(object):
"""Holds an implementation of a transition.
This class is a 'non-data descriptor', somewhat similar to a property.
Attributes:
field_name (str): the name of the field of the instance to update.
transition (Transition): the transition to perform
workflow (Workflow): the workflow to which this is related.
hooks (Hook list): hooks to apply along with the transition.
implementation (callable): the code to invoke between 'before' and the
state update.
"""
def __init__(self, field_name, transition, workflow, implementation, hooks=None):
self.field_name = field_name
self.transition = transition
self.workflow = workflow
self.hooks = hooks or {}
self.implementation = implementation
self.__doc__ = implementation.__doc__
def copy(self):
return self.__class__(
field_name=self.field_name,
transition=self.transition,
workflow=self.workflow,
implementation=self.implementation,
# Don't copy hooks: they'll be re-generated during metaclass __new__
hooks={},
)
def add_hook(self, hook):
self.hooks.setdefault(hook.kind, []).append(hook)
def __get__(self, instance, owner):
if instance is None:
return self
if not isinstance(instance, BaseWorkflowEnabled):
raise TypeError(
"Unable to apply transition '%s' to object %r, which is not "
"attached to a Workflow." % (self.transition.name, instance))
return self.workflow.implementation_class(
instance,
self.field_name, self.transition, self.workflow,
self.implementation, self.hooks)
def __repr__(self):
return "<%s for '%s' on '%s': %s>" % (
self.__class__.__name__,
self.transition.name, self.field_name, self.implementation)
class TransitionWrapper(object):
"""Mark that a method should be used for a transition with a different name.
Attributes:
trname (str): the name of the transition that the method implements
func (function): the decorated method
"""
def __init__(self, trname, field='', check=None, before=None, after=None):
self.trname = trname
self.field = field
self.check = check
self.before = before
self.after = after
self.func = None
def __call__(self, func):
self.func = func
if self.trname == '':
self.trname = func.__name__
return self
def __repr__(self):
return "<%s for %r: %s>" % (self.__class__.__name__, self.trname, self.func)
def transition(trname='', field='', check=None, before=None, after=None):
"""Decorator to declare a function as a transition implementation."""
if is_callable(trname):
raise ValueError(
"The @transition decorator should be called as "
"@transition(['transition_name'], **kwargs)")
if check or before or after:
warnings.warn(
"The use of check=, before= and after= in @transition decorators is "
"deprecated in favor of @transition_check, @before_transition and "
"@after_transition decorators.",
DeprecationWarning,
stacklevel=2)
return TransitionWrapper(trname, field=field, check=check, before=before, after=after)
def _make_hook_dict(fun):
"""Ensure the given function has a xworkflows_hook attribute.
That attribute has the following structure:
>>> {
... 'before': [('state', <TransitionHook>), ...],
... }
"""
if not hasattr(fun, 'xworkflows_hook'):
fun.xworkflows_hook = {
HOOK_BEFORE: [],
HOOK_AFTER: [],
HOOK_CHECK: [],
HOOK_ON_ENTER: [],
HOOK_ON_LEAVE: [],
}
return fun.xworkflows_hook
class _HookDeclaration(object):
"""Base class for decorators declaring methods as transition hooks.
Args:
*names (str tuple): name of the states/transitions to bind to; use '*'
for 'all'
priority (int): priority of the hook, defaults to 0
field (str): name of the field to which the hooked transition relates
Usage:
>>> @_HookDeclaration('foo', 'bar', priority=4)
... def my_hook(self):
... pass
"""
def __init__(self, *names, **kwargs):
if not names:
names = ('*',)
self.names = names
self.priority = kwargs.get('priority', 0)
self.field = kwargs.get('field', '')
def _as_hook(self, func):
return Hook(self.hook_name, func, *self.names, priority=self.priority)
def __call__(self, func):
hook_dict = _make_hook_dict(func)
hooks = hook_dict[self.hook_name]
hooks.append((self.field, self._as_hook(func)))
return func
class before_transition(_HookDeclaration):
"""Decorates a method that should be called before a given transition.
Example:
>>> @before_transition('foobar')
... def blah(self):
... pass
"""
hook_name = HOOK_BEFORE
class after_transition(_HookDeclaration):
"""Decorates a method that should be called after a given transition.
Example:
>>> @after_transition('foobar')
... def blah(self):
... pass
"""
hook_name = HOOK_AFTER
class transition_check(_HookDeclaration):
"""Decorates a method that should be called after a given transition.
Example:
>>> @transition_check('foobar')
... def blah(self):
... pass
"""
hook_name = HOOK_CHECK
class on_enter_state(_HookDeclaration):
"""Decorates a method that should be used as a hook for a state.
Example:
>>> @on_enter_state('foo', 'bar')
... def blah(self):
... pass
"""
hook_name = HOOK_ON_ENTER
class on_leave_state(_HookDeclaration):
"""Decorates a method that should be used as a hook for a state.
Example:
>>> @on_leave_state('foo', 'bar')
... def blah(self):
... pass
"""
hook_name = HOOK_ON_LEAVE
def noop(instance, *args, **kwargs):
"""NoOp function, ignores all arguments."""
pass
class ImplementationList(object):
"""Stores all implementations.
Attributes:
state_field (str): the name of the field holding the state of objects.
implementations (dict(str => ImplementationProperty)): maps a transition
name to the associated implementation.
workflow (Workflow): the related workflow
transitions_at (dict(str => str)): maps a transition name to the
name of the attribute holding the related implementation.
custom_implems (str set): list of transition names for which a custom
implementation has been defined.
"""
def __init__(self, state_field, workflow):
self.state_field = state_field
self.workflow = workflow
self.implementations = {}
self.transitions_at = {}
self.custom_implems = set()
def load_parent_implems(self, parent_implems):
"""Import previously defined implementations.
Args:
parent_implems (ImplementationList): List of implementations defined
in a parent class.
"""
for trname, attr, implem in parent_implems.get_custom_implementations():
self.implementations[trname] = implem.copy()
self.transitions_at[trname] = attr
self.custom_implems.add(trname)
def add_implem(self, transition, attribute, function, **kwargs):
"""Add an implementation.
Args:
transition (Transition): the transition for which the implementation
is added
attribute (str): the name of the attribute where the implementation
will be available
function (callable): the actual implementation function
**kwargs: extra arguments for the related ImplementationProperty.
"""
implem = ImplementationProperty(
field_name=self.state_field,
transition=transition,
workflow=self.workflow,
implementation=function,
**kwargs)
self.implementations[transition.name] = implem
self.transitions_at[transition.name] = attribute
return implem
def should_collect(self, value):
"""Decide whether a given value should be collected."""
return (
# decorated with @transition
isinstance(value, TransitionWrapper)
# Relates to a compatible transition
and value.trname in self.workflow.transitions
# Either not bound to a state field or bound to the current one
and (not value.field or value.field == self.state_field))
def collect(self, attrs):
"""Collect the implementations from a given attributes dict."""
for name, value in attrs.items():
if self.should_collect(value):
transition = self.workflow.transitions[value.trname]
if (
value.trname in self.implementations
and value.trname in self.custom_implems
and name != self.transitions_at[value.trname]):
# We already have an implementation registered.
other_implem_at = self.transitions_at[value.trname]
raise ValueError(
"Error for attribute %s: it defines implementation "
"%s for transition %s, which is already implemented "
"at %s." % (name, value, transition, other_implem_at))
implem = self.add_implem(transition, name, value.func)
self.custom_implems.add(transition.name)
if value.check:
implem.add_hook(Hook(HOOK_CHECK, value.check))
if value.before:
implem.add_hook(Hook(HOOK_BEFORE, value.before))
if value.after:
implem.add_hook(Hook(HOOK_AFTER, value.after))
def get_custom_implementations(self):
"""Retrieve a list of cutom implementations.
Yields:
(str, str, ImplementationProperty) tuples: The name of the attribute
an implementation lives at, the name of the related transition,
and the related implementation.
"""
for trname in self.custom_implems:
attr = self.transitions_at[trname]
implem = self.implementations[trname]
yield (trname, attr, implem)
def add_missing_implementations(self):
for transition in self.workflow.transitions:
if transition.name not in self.implementations:
self.add_implem(transition, transition.name, noop)
def register_hooks(self, cls):
for field, value in utils.iterclass(cls):
if is_callable(value) and hasattr(value, 'xworkflows_hook'):
self.register_function_hooks(value)
def register_function_hooks(self, func):
"""Looks at an object method and registers it for relevent transitions."""
for hook_kind, hooks in func.xworkflows_hook.items():
for field_name, hook in hooks:
if field_name and field_name != self.state_field:
continue
for transition in self.workflow.transitions:
if hook.applies_to(transition):
implem = self.implementations[transition.name]
implem.add_hook(hook)
def _may_override(self, implem, other):
"""Checks whether an ImplementationProperty may override an attribute."""
if isinstance(other, ImplementationProperty):
# Overriding another custom implementation for the same transition
# and field
return (other.transition == implem.transition and other.field_name == self.state_field)
elif isinstance(other, TransitionWrapper):
# Overriding the definition that led to adding the current
# ImplementationProperty.
return (
other.trname == implem.transition.name
and (not other.field or other.field == self.state_field)
and other.func == implem.implementation)
return False
def fill_attrs(self, attrs):
"""Update the 'attrs' dict with generated ImplementationProperty."""
for trname, attrname in self.transitions_at.items():
implem = self.implementations[trname]
if attrname in attrs:
conflicting = attrs[attrname]
if not self._may_override(implem, conflicting):
raise ValueError(
"Can't override transition implementation %s=%r with %r" %
(attrname, conflicting, implem))
attrs[attrname] = implem
return attrs
def transform(self, attrs):
"""Perform all actions on a given attribute dict."""
self.collect(attrs)
self.add_missing_implementations()
self.fill_attrs(attrs)
class WorkflowMeta(type):
"""Base metaclass for all Workflows.
Sets the 'states', 'transitions', and 'initial_state' attributes.
"""
def __new__(mcs, name, bases, attrs):
state_defs = attrs.pop('states', [])
transitions_defs = attrs.pop('transitions', [])
initial_state = attrs.pop('initial_state', None)
new_class = super(WorkflowMeta, mcs).__new__(mcs, name, bases, attrs)
new_class.states = _setup_states(state_defs, getattr(new_class, 'states', []))
new_class.transitions = _setup_transitions(
transitions_defs,
new_class.states,
getattr(new_class, 'transitions', []),
)
if initial_state is not None:
new_class.initial_state = new_class.states[initial_state]
return new_class
class BaseWorkflow(object):
"""Base class for all workflows.
Attributes:
states (StateList): list of states of this Workflow
transitions (TransitionList): list of Transitions of this Workflow
initial_state (State): initial state for the Workflow
implementation_class (ImplementationWrapper subclass): class to use
for transition implementation wrapping.
For each transition, a ImplementationWrapper with the same name (unless
another name has been specified through the use of the @transition
decorator) is provided to perform the specified transition.
"""
implementation_class = ImplementationWrapper
def log_transition(self, transition, from_state, instance, *args, **kwargs):
"""Log a transition.
Args:
transition (Transition): the name of the performed transition
from_state (State): the source state
instance (object): the modified object
Kwargs:
Any passed when calling the transition
"""
logger = logging.getLogger('xworkflows.transitions')
try:
instance_repr = u(repr(instance), 'ignore')
except (UnicodeEncodeError, UnicodeDecodeError):
instance_repr = u("<bad repr>")
logger.info(
u("%s performed transition %s.%s (%s -> %s)"), instance_repr,
self.__class__.__name__, transition.name, from_state.name,
transition.target.name)
# Workaround for metaclasses on python2/3.
# Equivalent to:
# Python2
#
# class Workflow(BaseWorkflow):
# __metaclass__ = WorkflowMeta
#
# Python3
#
# class Workflow(metaclass=WorkflowMeta):
# pass
Workflow = WorkflowMeta('Workflow', (BaseWorkflow,), {})
class StateWrapper(object):
"""Slightly enhanced wrapper around a base State object.
Knows about the workflow.
"""
def __init__(self, state, workflow):
self.state = state
self.workflow = workflow
for st in workflow.states:
setattr(self, 'is_%s' % st.name, st.name == self.state.name)
def __eq__(self, other):
if isinstance(other, self.__class__):
return self.state == other.state
elif isinstance(other, State):
return self.state == other
elif is_string(other):
return self.state.name == other
else:
return NotImplemented
def __ne__(self, other):
return not (self == other)
def __str__(self):
return self.state.name
def __repr__(self):
return '<%s: %r>' % (self.__class__.__name__, self.state)
def __getattr__(self, attr):
if attr == 'state':
raise AttributeError(
'Trying to access attribute %s of a non-initialized %r object!'
% (attr, self.__class__))
else:
return getattr(self.state, attr)
if not is_python3:
def __unicode__(self):
return u(str(self))
def __hash__(self):
# A StateWrapper should compare equal to its name.
return hash(self.state.name)
def transitions(self):
"""Retrieve a list of transitions available from this state."""
return self.workflow.transitions.available_from(self.state)
class StateProperty(object):
"""Property-like attribute holding the state of a WorkflowEnabled object.
The state is stored in the internal __dict__ of the instance.
"""
def __init__(self, workflow, state_field_name):
super(StateProperty, self).__init__()
self.workflow = workflow
self.field_name = state_field_name
def __get__(self, instance, owner):
"""Retrieve the current state of the 'instance' object."""
if instance is None:
return self
state = instance.__dict__.get(self.field_name,
self.workflow.initial_state)
return StateWrapper(state, self.workflow)
def __set__(self, instance, value):
"""Set the current state of the 'instance' object."""
try:
state = self.workflow.states[value]
except KeyError:
raise ValueError("Value %s is not a valid state for workflow %s." % (value, self.workflow))
instance.__dict__[self.field_name] = state
def __str__(self):
return 'StateProperty(%s, %s)' % (self.workflow, self.field_name)
class StateField(object):
"""Indicates that a given class attribute is actually a workflow state."""
def __init__(self, workflow):
self.workflow = workflow
class WorkflowEnabledMeta(type):
"""Base metaclass for all Workflow Enabled objects.
Defines:
- one class attribute for each the attached workflows,
- a '_workflows' attribute, a dict mapping each field_name to the related
Workflow,
- a '_xworkflows_implems' attribute, a dict mapping each field_name to a
dict of related ImplementationProperty.
- one class attribute for each transition for each attached workflow
"""
@classmethod
def _add_workflow(mcs, field_name, state_field, attrs):
"""Attach a workflow to the attribute list (create a StateProperty)."""
attrs[field_name] = StateProperty(state_field.workflow, field_name)
@classmethod
def _find_workflows(mcs, attrs):
"""Finds all occurrences of a workflow in the attributes definitions.
Returns:
dict(str => StateField): maps an attribute name to a StateField
describing the related Workflow.
"""
workflows = {}
for attribute, value in attrs.items():
if isinstance(value, Workflow):
workflows[attribute] = StateField(value)
return workflows
@classmethod
def _add_transitions(mcs, field_name, workflow, attrs, implems=None):
"""Collect and enhance transition definitions to a workflow.
Modifies the 'attrs' dict in-place.
Args:
field_name (str): name of the field transitions should update
workflow (Workflow): workflow we're working on
attrs (dict): dictionary of attributes to be updated.
implems (ImplementationList): Implementation list from parent
classes (optional)
Returns:
ImplementationList: The new implementation list for this field.
"""
new_implems = ImplementationList(field_name, workflow)
if implems:
new_implems.load_parent_implems(implems)
new_implems.transform(attrs)
return new_implems
@classmethod
def _register_hooks(mcs, cls, implems):
for implem_list in implems.values():
implem_list.register_hooks(cls)
def __new__(mcs, name, bases, attrs):
# Map field_name => StateField
workflows = {}
# Map field_name => ImplementationList
implems = {}
# Collect workflows and implementations from parents
for base in reversed(bases):
if hasattr(base, '_workflows'):
workflows.update(base._workflows)
implems.update(base._xworkflows_implems)
workflows.update(mcs._find_workflows(attrs))
# Update attributes with workflow descriptions, and collect
# implementation declarations.
for field, state_field in workflows.items():
mcs._add_workflow(field, state_field, attrs)
implems[field] = mcs._add_transitions(
field, state_field.workflow, attrs, implems.get(field))
# Set specific attributes for children
attrs['_workflows'] = workflows
attrs['_xworkflows_implems'] = implems
cls = super(WorkflowEnabledMeta, mcs).__new__(mcs, name, bases, attrs)
mcs._register_hooks(cls, implems)
return cls
class BaseWorkflowEnabled(object):
"""Base class for all objects using a workflow.
Attributes:
workflows (dict(str, StateField)): Maps the name of a 'state_field' to
the related Workflow
"""
# Workaround for metaclasses on python2/3.
# Equivalent to:
# Python2
#
# class WorkflowEnabled(BaseWorkflowEnabled):
# __metaclass__ = WorkflowEnabledMeta
#
# Python3
#
# class WorkflowEnabled(metaclass=WorkflowEnabledMeta):
# pass
WorkflowEnabled = WorkflowEnabledMeta('WorkflowEnabled', (BaseWorkflowEnabled,), {})
|
rbarrois/xworkflows | src/xworkflows/base.py | _setup_transitions | python | def _setup_transitions(tdef, states, prev=()):
trs = list(prev)
for transition in tdef:
if len(transition) == 3:
(name, source, target) = transition
if is_string(source) or isinstance(source, State):
source = [source]
source = [states[src] for src in source]
target = states[target]
tr = Transition(name, source, target)
else:
raise TypeError(
"Elements of the 'transition' attribute of a "
"workflow should be three-tuples; got %r instead." % (transition,)
)
if any(prev_tr.name == tr.name for prev_tr in trs):
# Replacing an existing state
trs = [tr if prev_tr.name == tr.name else prev_tr for prev_tr in trs]
else:
trs.append(tr)
return TransitionList(trs) | Create a TransitionList object from a 'transitions' Workflow attribute.
Args:
tdef: list of transition definitions
states (StateList): already parsed state definitions.
prev (TransitionList): transition definitions from a parent.
Returns:
TransitionList: the list of transitions defined in the 'tdef' argument. | train | https://github.com/rbarrois/xworkflows/blob/4a94b04ba83cb43f61d4b0f7db6964a667c86b5b/src/xworkflows/base.py#L184-L215 | [
"def is_string(var):\n return isinstance(var, str)\n"
] | # -*- coding: utf-8 -*-
# Copyright (c) 2011-2013 Raphaël Barrois
# This code is distributed under the two-clause BSD License.
"""Base components of XWorkflows."""
import logging
import re
import warnings
from .compat import is_callable, is_python3, is_string, u
from . import utils
class WorkflowError(Exception):
"""Base class for errors from the xworkflows module."""
class AbortTransition(WorkflowError):
"""Raised to prevent a transition from proceeding."""
class InvalidTransitionError(AbortTransition):
"""Raised when trying to perform a transition not available from current state."""
class ForbiddenTransition(AbortTransition):
"""Raised when the 'check' hook of a transition was defined and returned False."""
class State(object):
"""A state within a workflow.
Attributes:
name (str): the name of the state
title (str): the human-readable title for the state
"""
STATE_NAME_RE = re.compile('\w+$')
def __init__(self, name, title):
if not self.STATE_NAME_RE.match(name):
raise ValueError('Invalid state name %s.' % name)
self.name = name
self.title = title
def __str__(self):
return self.name
def __repr__(self):
return '<%s: %r>' % (self.__class__.__name__, self.name)
class StateList(object):
"""A list of states."""
def __init__(self, states):
self._states = dict((st.name, st) for st in states)
self._order = tuple(st.name for st in states)
def __getattr__(self, name):
try:
return self._states[name]
except KeyError:
raise AttributeError('StateList %s has no state named %s' % (self, name))
def __len__(self):
return len(self._states)
def __getitem__(self, name_or_state):
if isinstance(name_or_state, State):
return self._states[name_or_state.name]
else:
return self._states[name_or_state]
def __repr__(self):
return '%s(%r)' % (self.__class__.__name__, self._states)
def __iter__(self):
for name in self._order:
yield self._states[name]
def __contains__(self, state):
if isinstance(state, State):
return state.name in self._states and self._states[state.name] == state
else: # Expect a state name
return state in self._states
class Transition(object):
"""A transition.
Attributes:
name (str): the name of the Transition
source (State list): the 'source' states of the transition
target (State): the 'target' state of the transition
"""
def __init__(self, name, source, target):
self.name = name
if isinstance(source, State):
source = [source]
self.source = source
self.target = target
def __repr__(self):
return '%s(%r, %r, %r)' % (self.__class__.__name__,
self.name, self.source, self.target)
class TransitionList(object):
"""Holder for the transitions of a given workflow."""
def __init__(self, transitions):
"""Create a TransitionList.
Args:
transitions (list of (name, source, target) tuple): the transitions
to include.
"""
self._transitions = {}
self._order = []
for trdef in transitions:
self._transitions[trdef.name] = trdef
self._order.append(trdef.name)
def __len__(self):
return len(self._transitions)
def __getattr__(self, name):
try:
return self._transitions[name]
except KeyError:
raise AttributeError(
"TransitionList %s has no transition named %s." % (self, name))
def __getitem__(self, name):
return self._transitions[name]
def __iter__(self):
for name in self._order:
yield self._transitions[name]
def __contains__(self, value):
if isinstance(value, Transition):
return value.name in self._transitions and self._transitions[value.name] == value
else:
return value in self._transitions
def available_from(self, state):
"""Retrieve all transitions available from a given state.
Args:
state (State): the initial state.
Yields:
Transition: all transitions starting from that state
"""
for transition in self:
if state in transition.source:
yield transition
def __repr__(self):
return '%s(%r)' % (self.__class__.__name__, self._transitions.values())
def _setup_states(state_definitions, prev=()):
"""Create a StateList object from a 'states' Workflow attribute."""
states = list(prev)
for state_def in state_definitions:
if len(state_def) != 2:
raise TypeError(
"The 'state' attribute of a workflow should be "
"a two-tuple of strings; got %r instead." % (state_def,)
)
name, title = state_def
state = State(name, title)
if any(st.name == name for st in states):
# Replacing an existing state
states = [state if st.name == name else st for st in states]
else:
states.append(state)
return StateList(states)
HOOK_BEFORE = 'before'
HOOK_AFTER = 'after'
HOOK_CHECK = 'check'
HOOK_ON_ENTER = 'on_enter'
HOOK_ON_LEAVE = 'on_leave'
class Hook(object):
"""A hook to run when a transition occurs.
Attributes:
kind (str): the kind of hook
priority (int): the priority of the hook (higher values run first)
function (callable): the actual function to call
names (str list): name of the transitions or states to which the hook
relates. The special value '*' means 'applies to all transitions/
states'.
Hooks are sortable by descending priority and ascending function name.
Hook kinds are as follow:
- HOOK_BEFORE: run before the related transitions
- HOOK_AFTER: run after the related transitions
- HOOK_CHECK: run as part of pre-transition checks (return value matters)
- HOOK_ON_ENTER: run just after a transition entering a related state
- HOOK_ON_LEAVE: run just before a transition leaving from a related state
"""
def __init__(self, kind, function, *names, **kwargs):
assert kind in (
HOOK_BEFORE, HOOK_AFTER, HOOK_CHECK,
HOOK_ON_ENTER, HOOK_ON_LEAVE)
self.kind = kind
self.priority = kwargs.get('priority', 0)
self.function = function
self.names = names or ('*',)
def _match_state(self, state):
"""Checks whether a given State matches self.names."""
return (self.names == '*'
or state in self.names
or state.name in self.names)
def _match_transition(self, transition):
"""Checks whether a given Transition matches self.names."""
return (self.names == '*'
or transition in self.names
or transition.name in self.names)
def applies_to(self, transition, from_state=None):
"""Whether this hook applies to the given transition/state.
Args:
transition (Transition): the transition to check
from_state (State or None): the state to check. If absent, the check
is 'might this hook apply to the related transition, given a
valid source state'.
"""
if '*' in self.names:
return True
elif self.kind in (HOOK_BEFORE, HOOK_AFTER, HOOK_CHECK):
return self._match_transition(transition)
elif self.kind == HOOK_ON_ENTER:
return self._match_state(transition.target)
elif from_state is None:
# Testing whether the hook may apply to at least one source of the
# transition
return any(self._match_state(src) for src in transition.source)
else:
return self._match_state(from_state)
def __call__(self, *args, **kwargs):
return self.function(*args, **kwargs)
def __eq__(self, other):
"""Equality is based on priority, function and kind."""
if not isinstance(other, Hook):
return NotImplemented
return (
self.priority == other.priority
and self.function == other.function
and self.kind == other.kind
and self.names == other.names
)
def __ne__(self, other):
if not isinstance(other, Hook):
return NotImplemented
return not (self == other)
def __lt__(self, other):
"""Compare hooks of the same kind."""
if not isinstance(other, Hook):
return NotImplemented
return (
(other.priority, self.function.__name__)
< (self.priority, other.function.__name__))
def __gt__(self, other):
"""Compare hooks of the same kind."""
if not isinstance(other, Hook):
return NotImplemented
return (
(other.priority, self.function.__name__)
> (self.priority, other.function.__name__))
def __repr__(self):
return '<%s: %s %r>' % (
self.__class__.__name__, self.kind, self.function)
class ImplementationWrapper(object):
"""Wraps a transition implementation.
Emulates a function behaviour, but provides a few extra features.
Attributes:
instance (WorkflowEnabled): the instance to update
.
field_name (str): the name of the field of the instance to update.
transition (Transition): the transition to perform
workflow (Workflow): the workflow to which this is related.
hooks (Hook list): optional hooks to call during the transition
implementation (callable): the code to invoke between 'before' and the
state update.
"""
def __init__(self, instance, field_name, transition, workflow,
implementation, hooks=None):
self.instance = instance
self.field_name = field_name
self.transition = transition
self.workflow = workflow
self.hooks = hooks or {}
self.implementation = implementation
self.__doc__ = implementation.__doc__
@property
def current_state(self):
return getattr(self.instance, self.field_name)
def _pre_transition_checks(self):
"""Run the pre-transition checks."""
current_state = getattr(self.instance, self.field_name)
if current_state not in self.transition.source:
raise InvalidTransitionError(
"Transition '%s' isn't available from state '%s'." %
(self.transition.name, current_state.name))
for check in self._filter_hooks(HOOK_CHECK):
if not check(self.instance):
raise ForbiddenTransition(
"Transition '%s' was forbidden by "
"custom pre-transition check." % self.transition.name)
def _filter_hooks(self, *hook_kinds):
"""Filter a list of hooks, keeping only applicable ones."""
hooks = sum((self.hooks.get(kind, []) for kind in hook_kinds), [])
return sorted(hook for hook in hooks
if hook.applies_to(self.transition, self.current_state))
def _pre_transition(self, *args, **kwargs):
for hook in self._filter_hooks(HOOK_BEFORE, HOOK_ON_LEAVE):
hook(self.instance, *args, **kwargs)
def _during_transition(self, *args, **kwargs):
return self.implementation(self.instance, *args, **kwargs)
def _log_transition(self, from_state, *args, **kwargs):
self.workflow.log_transition(
self.transition, from_state, self.instance,
*args, **kwargs)
def _post_transition(self, result, *args, **kwargs):
"""Performs post-transition actions."""
for hook in self._filter_hooks(HOOK_AFTER, HOOK_ON_ENTER):
hook(self.instance, result, *args, **kwargs)
def __call__(self, *args, **kwargs):
"""Run the transition, with all checks."""
self._pre_transition_checks()
# Call hooks.
self._pre_transition(*args, **kwargs)
result = self._during_transition(*args, **kwargs)
from_state = getattr(self.instance, self.field_name)
setattr(self.instance, self.field_name, self.transition.target)
# Call hooks.
self._log_transition(from_state, *args, **kwargs)
self._post_transition(result, *args, **kwargs)
return result
def is_available(self):
"""Check whether this transition is available on the current object.
Returns:
bool
"""
try:
self._pre_transition_checks()
except (InvalidTransitionError, ForbiddenTransition):
return False
return True
def __repr__(self):
return "<%s for %r on %r: %r>" % (
self.__class__.__name__,
self.transition.name, self.field_name, self.implementation)
class ImplementationProperty(object):
"""Holds an implementation of a transition.
This class is a 'non-data descriptor', somewhat similar to a property.
Attributes:
field_name (str): the name of the field of the instance to update.
transition (Transition): the transition to perform
workflow (Workflow): the workflow to which this is related.
hooks (Hook list): hooks to apply along with the transition.
implementation (callable): the code to invoke between 'before' and the
state update.
"""
def __init__(self, field_name, transition, workflow, implementation, hooks=None):
self.field_name = field_name
self.transition = transition
self.workflow = workflow
self.hooks = hooks or {}
self.implementation = implementation
self.__doc__ = implementation.__doc__
def copy(self):
return self.__class__(
field_name=self.field_name,
transition=self.transition,
workflow=self.workflow,
implementation=self.implementation,
# Don't copy hooks: they'll be re-generated during metaclass __new__
hooks={},
)
def add_hook(self, hook):
self.hooks.setdefault(hook.kind, []).append(hook)
def __get__(self, instance, owner):
if instance is None:
return self
if not isinstance(instance, BaseWorkflowEnabled):
raise TypeError(
"Unable to apply transition '%s' to object %r, which is not "
"attached to a Workflow." % (self.transition.name, instance))
return self.workflow.implementation_class(
instance,
self.field_name, self.transition, self.workflow,
self.implementation, self.hooks)
def __repr__(self):
return "<%s for '%s' on '%s': %s>" % (
self.__class__.__name__,
self.transition.name, self.field_name, self.implementation)
class TransitionWrapper(object):
"""Mark that a method should be used for a transition with a different name.
Attributes:
trname (str): the name of the transition that the method implements
func (function): the decorated method
"""
def __init__(self, trname, field='', check=None, before=None, after=None):
self.trname = trname
self.field = field
self.check = check
self.before = before
self.after = after
self.func = None
def __call__(self, func):
self.func = func
if self.trname == '':
self.trname = func.__name__
return self
def __repr__(self):
return "<%s for %r: %s>" % (self.__class__.__name__, self.trname, self.func)
def transition(trname='', field='', check=None, before=None, after=None):
"""Decorator to declare a function as a transition implementation."""
if is_callable(trname):
raise ValueError(
"The @transition decorator should be called as "
"@transition(['transition_name'], **kwargs)")
if check or before or after:
warnings.warn(
"The use of check=, before= and after= in @transition decorators is "
"deprecated in favor of @transition_check, @before_transition and "
"@after_transition decorators.",
DeprecationWarning,
stacklevel=2)
return TransitionWrapper(trname, field=field, check=check, before=before, after=after)
def _make_hook_dict(fun):
"""Ensure the given function has a xworkflows_hook attribute.
That attribute has the following structure:
>>> {
... 'before': [('state', <TransitionHook>), ...],
... }
"""
if not hasattr(fun, 'xworkflows_hook'):
fun.xworkflows_hook = {
HOOK_BEFORE: [],
HOOK_AFTER: [],
HOOK_CHECK: [],
HOOK_ON_ENTER: [],
HOOK_ON_LEAVE: [],
}
return fun.xworkflows_hook
class _HookDeclaration(object):
"""Base class for decorators declaring methods as transition hooks.
Args:
*names (str tuple): name of the states/transitions to bind to; use '*'
for 'all'
priority (int): priority of the hook, defaults to 0
field (str): name of the field to which the hooked transition relates
Usage:
>>> @_HookDeclaration('foo', 'bar', priority=4)
... def my_hook(self):
... pass
"""
def __init__(self, *names, **kwargs):
if not names:
names = ('*',)
self.names = names
self.priority = kwargs.get('priority', 0)
self.field = kwargs.get('field', '')
def _as_hook(self, func):
return Hook(self.hook_name, func, *self.names, priority=self.priority)
def __call__(self, func):
hook_dict = _make_hook_dict(func)
hooks = hook_dict[self.hook_name]
hooks.append((self.field, self._as_hook(func)))
return func
class before_transition(_HookDeclaration):
"""Decorates a method that should be called before a given transition.
Example:
>>> @before_transition('foobar')
... def blah(self):
... pass
"""
hook_name = HOOK_BEFORE
class after_transition(_HookDeclaration):
"""Decorates a method that should be called after a given transition.
Example:
>>> @after_transition('foobar')
... def blah(self):
... pass
"""
hook_name = HOOK_AFTER
class transition_check(_HookDeclaration):
"""Decorates a method that should be called after a given transition.
Example:
>>> @transition_check('foobar')
... def blah(self):
... pass
"""
hook_name = HOOK_CHECK
class on_enter_state(_HookDeclaration):
"""Decorates a method that should be used as a hook for a state.
Example:
>>> @on_enter_state('foo', 'bar')
... def blah(self):
... pass
"""
hook_name = HOOK_ON_ENTER
class on_leave_state(_HookDeclaration):
"""Decorates a method that should be used as a hook for a state.
Example:
>>> @on_leave_state('foo', 'bar')
... def blah(self):
... pass
"""
hook_name = HOOK_ON_LEAVE
def noop(instance, *args, **kwargs):
"""NoOp function, ignores all arguments."""
pass
class ImplementationList(object):
"""Stores all implementations.
Attributes:
state_field (str): the name of the field holding the state of objects.
implementations (dict(str => ImplementationProperty)): maps a transition
name to the associated implementation.
workflow (Workflow): the related workflow
transitions_at (dict(str => str)): maps a transition name to the
name of the attribute holding the related implementation.
custom_implems (str set): list of transition names for which a custom
implementation has been defined.
"""
def __init__(self, state_field, workflow):
self.state_field = state_field
self.workflow = workflow
self.implementations = {}
self.transitions_at = {}
self.custom_implems = set()
def load_parent_implems(self, parent_implems):
"""Import previously defined implementations.
Args:
parent_implems (ImplementationList): List of implementations defined
in a parent class.
"""
for trname, attr, implem in parent_implems.get_custom_implementations():
self.implementations[trname] = implem.copy()
self.transitions_at[trname] = attr
self.custom_implems.add(trname)
def add_implem(self, transition, attribute, function, **kwargs):
"""Add an implementation.
Args:
transition (Transition): the transition for which the implementation
is added
attribute (str): the name of the attribute where the implementation
will be available
function (callable): the actual implementation function
**kwargs: extra arguments for the related ImplementationProperty.
"""
implem = ImplementationProperty(
field_name=self.state_field,
transition=transition,
workflow=self.workflow,
implementation=function,
**kwargs)
self.implementations[transition.name] = implem
self.transitions_at[transition.name] = attribute
return implem
def should_collect(self, value):
"""Decide whether a given value should be collected."""
return (
# decorated with @transition
isinstance(value, TransitionWrapper)
# Relates to a compatible transition
and value.trname in self.workflow.transitions
# Either not bound to a state field or bound to the current one
and (not value.field or value.field == self.state_field))
def collect(self, attrs):
"""Collect the implementations from a given attributes dict."""
for name, value in attrs.items():
if self.should_collect(value):
transition = self.workflow.transitions[value.trname]
if (
value.trname in self.implementations
and value.trname in self.custom_implems
and name != self.transitions_at[value.trname]):
# We already have an implementation registered.
other_implem_at = self.transitions_at[value.trname]
raise ValueError(
"Error for attribute %s: it defines implementation "
"%s for transition %s, which is already implemented "
"at %s." % (name, value, transition, other_implem_at))
implem = self.add_implem(transition, name, value.func)
self.custom_implems.add(transition.name)
if value.check:
implem.add_hook(Hook(HOOK_CHECK, value.check))
if value.before:
implem.add_hook(Hook(HOOK_BEFORE, value.before))
if value.after:
implem.add_hook(Hook(HOOK_AFTER, value.after))
def get_custom_implementations(self):
"""Retrieve a list of cutom implementations.
Yields:
(str, str, ImplementationProperty) tuples: The name of the attribute
an implementation lives at, the name of the related transition,
and the related implementation.
"""
for trname in self.custom_implems:
attr = self.transitions_at[trname]
implem = self.implementations[trname]
yield (trname, attr, implem)
def add_missing_implementations(self):
for transition in self.workflow.transitions:
if transition.name not in self.implementations:
self.add_implem(transition, transition.name, noop)
def register_hooks(self, cls):
for field, value in utils.iterclass(cls):
if is_callable(value) and hasattr(value, 'xworkflows_hook'):
self.register_function_hooks(value)
def register_function_hooks(self, func):
"""Looks at an object method and registers it for relevent transitions."""
for hook_kind, hooks in func.xworkflows_hook.items():
for field_name, hook in hooks:
if field_name and field_name != self.state_field:
continue
for transition in self.workflow.transitions:
if hook.applies_to(transition):
implem = self.implementations[transition.name]
implem.add_hook(hook)
def _may_override(self, implem, other):
"""Checks whether an ImplementationProperty may override an attribute."""
if isinstance(other, ImplementationProperty):
# Overriding another custom implementation for the same transition
# and field
return (other.transition == implem.transition and other.field_name == self.state_field)
elif isinstance(other, TransitionWrapper):
# Overriding the definition that led to adding the current
# ImplementationProperty.
return (
other.trname == implem.transition.name
and (not other.field or other.field == self.state_field)
and other.func == implem.implementation)
return False
def fill_attrs(self, attrs):
"""Update the 'attrs' dict with generated ImplementationProperty."""
for trname, attrname in self.transitions_at.items():
implem = self.implementations[trname]
if attrname in attrs:
conflicting = attrs[attrname]
if not self._may_override(implem, conflicting):
raise ValueError(
"Can't override transition implementation %s=%r with %r" %
(attrname, conflicting, implem))
attrs[attrname] = implem
return attrs
def transform(self, attrs):
"""Perform all actions on a given attribute dict."""
self.collect(attrs)
self.add_missing_implementations()
self.fill_attrs(attrs)
class WorkflowMeta(type):
"""Base metaclass for all Workflows.
Sets the 'states', 'transitions', and 'initial_state' attributes.
"""
def __new__(mcs, name, bases, attrs):
state_defs = attrs.pop('states', [])
transitions_defs = attrs.pop('transitions', [])
initial_state = attrs.pop('initial_state', None)
new_class = super(WorkflowMeta, mcs).__new__(mcs, name, bases, attrs)
new_class.states = _setup_states(state_defs, getattr(new_class, 'states', []))
new_class.transitions = _setup_transitions(
transitions_defs,
new_class.states,
getattr(new_class, 'transitions', []),
)
if initial_state is not None:
new_class.initial_state = new_class.states[initial_state]
return new_class
class BaseWorkflow(object):
"""Base class for all workflows.
Attributes:
states (StateList): list of states of this Workflow
transitions (TransitionList): list of Transitions of this Workflow
initial_state (State): initial state for the Workflow
implementation_class (ImplementationWrapper subclass): class to use
for transition implementation wrapping.
For each transition, a ImplementationWrapper with the same name (unless
another name has been specified through the use of the @transition
decorator) is provided to perform the specified transition.
"""
implementation_class = ImplementationWrapper
def log_transition(self, transition, from_state, instance, *args, **kwargs):
"""Log a transition.
Args:
transition (Transition): the name of the performed transition
from_state (State): the source state
instance (object): the modified object
Kwargs:
Any passed when calling the transition
"""
logger = logging.getLogger('xworkflows.transitions')
try:
instance_repr = u(repr(instance), 'ignore')
except (UnicodeEncodeError, UnicodeDecodeError):
instance_repr = u("<bad repr>")
logger.info(
u("%s performed transition %s.%s (%s -> %s)"), instance_repr,
self.__class__.__name__, transition.name, from_state.name,
transition.target.name)
# Workaround for metaclasses on python2/3.
# Equivalent to:
# Python2
#
# class Workflow(BaseWorkflow):
# __metaclass__ = WorkflowMeta
#
# Python3
#
# class Workflow(metaclass=WorkflowMeta):
# pass
Workflow = WorkflowMeta('Workflow', (BaseWorkflow,), {})
class StateWrapper(object):
"""Slightly enhanced wrapper around a base State object.
Knows about the workflow.
"""
def __init__(self, state, workflow):
self.state = state
self.workflow = workflow
for st in workflow.states:
setattr(self, 'is_%s' % st.name, st.name == self.state.name)
def __eq__(self, other):
if isinstance(other, self.__class__):
return self.state == other.state
elif isinstance(other, State):
return self.state == other
elif is_string(other):
return self.state.name == other
else:
return NotImplemented
def __ne__(self, other):
return not (self == other)
def __str__(self):
return self.state.name
def __repr__(self):
return '<%s: %r>' % (self.__class__.__name__, self.state)
def __getattr__(self, attr):
if attr == 'state':
raise AttributeError(
'Trying to access attribute %s of a non-initialized %r object!'
% (attr, self.__class__))
else:
return getattr(self.state, attr)
if not is_python3:
def __unicode__(self):
return u(str(self))
def __hash__(self):
# A StateWrapper should compare equal to its name.
return hash(self.state.name)
def transitions(self):
"""Retrieve a list of transitions available from this state."""
return self.workflow.transitions.available_from(self.state)
class StateProperty(object):
"""Property-like attribute holding the state of a WorkflowEnabled object.
The state is stored in the internal __dict__ of the instance.
"""
def __init__(self, workflow, state_field_name):
super(StateProperty, self).__init__()
self.workflow = workflow
self.field_name = state_field_name
def __get__(self, instance, owner):
"""Retrieve the current state of the 'instance' object."""
if instance is None:
return self
state = instance.__dict__.get(self.field_name,
self.workflow.initial_state)
return StateWrapper(state, self.workflow)
def __set__(self, instance, value):
"""Set the current state of the 'instance' object."""
try:
state = self.workflow.states[value]
except KeyError:
raise ValueError("Value %s is not a valid state for workflow %s." % (value, self.workflow))
instance.__dict__[self.field_name] = state
def __str__(self):
return 'StateProperty(%s, %s)' % (self.workflow, self.field_name)
class StateField(object):
"""Indicates that a given class attribute is actually a workflow state."""
def __init__(self, workflow):
self.workflow = workflow
class WorkflowEnabledMeta(type):
"""Base metaclass for all Workflow Enabled objects.
Defines:
- one class attribute for each the attached workflows,
- a '_workflows' attribute, a dict mapping each field_name to the related
Workflow,
- a '_xworkflows_implems' attribute, a dict mapping each field_name to a
dict of related ImplementationProperty.
- one class attribute for each transition for each attached workflow
"""
@classmethod
def _add_workflow(mcs, field_name, state_field, attrs):
"""Attach a workflow to the attribute list (create a StateProperty)."""
attrs[field_name] = StateProperty(state_field.workflow, field_name)
@classmethod
def _find_workflows(mcs, attrs):
"""Finds all occurrences of a workflow in the attributes definitions.
Returns:
dict(str => StateField): maps an attribute name to a StateField
describing the related Workflow.
"""
workflows = {}
for attribute, value in attrs.items():
if isinstance(value, Workflow):
workflows[attribute] = StateField(value)
return workflows
@classmethod
def _add_transitions(mcs, field_name, workflow, attrs, implems=None):
"""Collect and enhance transition definitions to a workflow.
Modifies the 'attrs' dict in-place.
Args:
field_name (str): name of the field transitions should update
workflow (Workflow): workflow we're working on
attrs (dict): dictionary of attributes to be updated.
implems (ImplementationList): Implementation list from parent
classes (optional)
Returns:
ImplementationList: The new implementation list for this field.
"""
new_implems = ImplementationList(field_name, workflow)
if implems:
new_implems.load_parent_implems(implems)
new_implems.transform(attrs)
return new_implems
@classmethod
def _register_hooks(mcs, cls, implems):
for implem_list in implems.values():
implem_list.register_hooks(cls)
def __new__(mcs, name, bases, attrs):
# Map field_name => StateField
workflows = {}
# Map field_name => ImplementationList
implems = {}
# Collect workflows and implementations from parents
for base in reversed(bases):
if hasattr(base, '_workflows'):
workflows.update(base._workflows)
implems.update(base._xworkflows_implems)
workflows.update(mcs._find_workflows(attrs))
# Update attributes with workflow descriptions, and collect
# implementation declarations.
for field, state_field in workflows.items():
mcs._add_workflow(field, state_field, attrs)
implems[field] = mcs._add_transitions(
field, state_field.workflow, attrs, implems.get(field))
# Set specific attributes for children
attrs['_workflows'] = workflows
attrs['_xworkflows_implems'] = implems
cls = super(WorkflowEnabledMeta, mcs).__new__(mcs, name, bases, attrs)
mcs._register_hooks(cls, implems)
return cls
class BaseWorkflowEnabled(object):
"""Base class for all objects using a workflow.
Attributes:
workflows (dict(str, StateField)): Maps the name of a 'state_field' to
the related Workflow
"""
# Workaround for metaclasses on python2/3.
# Equivalent to:
# Python2
#
# class WorkflowEnabled(BaseWorkflowEnabled):
# __metaclass__ = WorkflowEnabledMeta
#
# Python3
#
# class WorkflowEnabled(metaclass=WorkflowEnabledMeta):
# pass
WorkflowEnabled = WorkflowEnabledMeta('WorkflowEnabled', (BaseWorkflowEnabled,), {})
|
rbarrois/xworkflows | src/xworkflows/base.py | transition | python | def transition(trname='', field='', check=None, before=None, after=None):
if is_callable(trname):
raise ValueError(
"The @transition decorator should be called as "
"@transition(['transition_name'], **kwargs)")
if check or before or after:
warnings.warn(
"The use of check=, before= and after= in @transition decorators is "
"deprecated in favor of @transition_check, @before_transition and "
"@after_transition decorators.",
DeprecationWarning,
stacklevel=2)
return TransitionWrapper(trname, field=field, check=check, before=before, after=after) | Decorator to declare a function as a transition implementation. | train | https://github.com/rbarrois/xworkflows/blob/4a94b04ba83cb43f61d4b0f7db6964a667c86b5b/src/xworkflows/base.py#L516-L529 | [
"def is_callable(var):\n return isinstance(var, collections.Callable)\n"
] | # -*- coding: utf-8 -*-
# Copyright (c) 2011-2013 Raphaël Barrois
# This code is distributed under the two-clause BSD License.
"""Base components of XWorkflows."""
import logging
import re
import warnings
from .compat import is_callable, is_python3, is_string, u
from . import utils
class WorkflowError(Exception):
"""Base class for errors from the xworkflows module."""
class AbortTransition(WorkflowError):
"""Raised to prevent a transition from proceeding."""
class InvalidTransitionError(AbortTransition):
"""Raised when trying to perform a transition not available from current state."""
class ForbiddenTransition(AbortTransition):
"""Raised when the 'check' hook of a transition was defined and returned False."""
class State(object):
"""A state within a workflow.
Attributes:
name (str): the name of the state
title (str): the human-readable title for the state
"""
STATE_NAME_RE = re.compile('\w+$')
def __init__(self, name, title):
if not self.STATE_NAME_RE.match(name):
raise ValueError('Invalid state name %s.' % name)
self.name = name
self.title = title
def __str__(self):
return self.name
def __repr__(self):
return '<%s: %r>' % (self.__class__.__name__, self.name)
class StateList(object):
"""A list of states."""
def __init__(self, states):
self._states = dict((st.name, st) for st in states)
self._order = tuple(st.name for st in states)
def __getattr__(self, name):
try:
return self._states[name]
except KeyError:
raise AttributeError('StateList %s has no state named %s' % (self, name))
def __len__(self):
return len(self._states)
def __getitem__(self, name_or_state):
if isinstance(name_or_state, State):
return self._states[name_or_state.name]
else:
return self._states[name_or_state]
def __repr__(self):
return '%s(%r)' % (self.__class__.__name__, self._states)
def __iter__(self):
for name in self._order:
yield self._states[name]
def __contains__(self, state):
if isinstance(state, State):
return state.name in self._states and self._states[state.name] == state
else: # Expect a state name
return state in self._states
class Transition(object):
"""A transition.
Attributes:
name (str): the name of the Transition
source (State list): the 'source' states of the transition
target (State): the 'target' state of the transition
"""
def __init__(self, name, source, target):
self.name = name
if isinstance(source, State):
source = [source]
self.source = source
self.target = target
def __repr__(self):
return '%s(%r, %r, %r)' % (self.__class__.__name__,
self.name, self.source, self.target)
class TransitionList(object):
"""Holder for the transitions of a given workflow."""
def __init__(self, transitions):
"""Create a TransitionList.
Args:
transitions (list of (name, source, target) tuple): the transitions
to include.
"""
self._transitions = {}
self._order = []
for trdef in transitions:
self._transitions[trdef.name] = trdef
self._order.append(trdef.name)
def __len__(self):
return len(self._transitions)
def __getattr__(self, name):
try:
return self._transitions[name]
except KeyError:
raise AttributeError(
"TransitionList %s has no transition named %s." % (self, name))
def __getitem__(self, name):
return self._transitions[name]
def __iter__(self):
for name in self._order:
yield self._transitions[name]
def __contains__(self, value):
if isinstance(value, Transition):
return value.name in self._transitions and self._transitions[value.name] == value
else:
return value in self._transitions
def available_from(self, state):
"""Retrieve all transitions available from a given state.
Args:
state (State): the initial state.
Yields:
Transition: all transitions starting from that state
"""
for transition in self:
if state in transition.source:
yield transition
def __repr__(self):
return '%s(%r)' % (self.__class__.__name__, self._transitions.values())
def _setup_states(state_definitions, prev=()):
"""Create a StateList object from a 'states' Workflow attribute."""
states = list(prev)
for state_def in state_definitions:
if len(state_def) != 2:
raise TypeError(
"The 'state' attribute of a workflow should be "
"a two-tuple of strings; got %r instead." % (state_def,)
)
name, title = state_def
state = State(name, title)
if any(st.name == name for st in states):
# Replacing an existing state
states = [state if st.name == name else st for st in states]
else:
states.append(state)
return StateList(states)
def _setup_transitions(tdef, states, prev=()):
"""Create a TransitionList object from a 'transitions' Workflow attribute.
Args:
tdef: list of transition definitions
states (StateList): already parsed state definitions.
prev (TransitionList): transition definitions from a parent.
Returns:
TransitionList: the list of transitions defined in the 'tdef' argument.
"""
trs = list(prev)
for transition in tdef:
if len(transition) == 3:
(name, source, target) = transition
if is_string(source) or isinstance(source, State):
source = [source]
source = [states[src] for src in source]
target = states[target]
tr = Transition(name, source, target)
else:
raise TypeError(
"Elements of the 'transition' attribute of a "
"workflow should be three-tuples; got %r instead." % (transition,)
)
if any(prev_tr.name == tr.name for prev_tr in trs):
# Replacing an existing state
trs = [tr if prev_tr.name == tr.name else prev_tr for prev_tr in trs]
else:
trs.append(tr)
return TransitionList(trs)
HOOK_BEFORE = 'before'
HOOK_AFTER = 'after'
HOOK_CHECK = 'check'
HOOK_ON_ENTER = 'on_enter'
HOOK_ON_LEAVE = 'on_leave'
class Hook(object):
"""A hook to run when a transition occurs.
Attributes:
kind (str): the kind of hook
priority (int): the priority of the hook (higher values run first)
function (callable): the actual function to call
names (str list): name of the transitions or states to which the hook
relates. The special value '*' means 'applies to all transitions/
states'.
Hooks are sortable by descending priority and ascending function name.
Hook kinds are as follow:
- HOOK_BEFORE: run before the related transitions
- HOOK_AFTER: run after the related transitions
- HOOK_CHECK: run as part of pre-transition checks (return value matters)
- HOOK_ON_ENTER: run just after a transition entering a related state
- HOOK_ON_LEAVE: run just before a transition leaving from a related state
"""
def __init__(self, kind, function, *names, **kwargs):
assert kind in (
HOOK_BEFORE, HOOK_AFTER, HOOK_CHECK,
HOOK_ON_ENTER, HOOK_ON_LEAVE)
self.kind = kind
self.priority = kwargs.get('priority', 0)
self.function = function
self.names = names or ('*',)
def _match_state(self, state):
"""Checks whether a given State matches self.names."""
return (self.names == '*'
or state in self.names
or state.name in self.names)
def _match_transition(self, transition):
"""Checks whether a given Transition matches self.names."""
return (self.names == '*'
or transition in self.names
or transition.name in self.names)
def applies_to(self, transition, from_state=None):
"""Whether this hook applies to the given transition/state.
Args:
transition (Transition): the transition to check
from_state (State or None): the state to check. If absent, the check
is 'might this hook apply to the related transition, given a
valid source state'.
"""
if '*' in self.names:
return True
elif self.kind in (HOOK_BEFORE, HOOK_AFTER, HOOK_CHECK):
return self._match_transition(transition)
elif self.kind == HOOK_ON_ENTER:
return self._match_state(transition.target)
elif from_state is None:
# Testing whether the hook may apply to at least one source of the
# transition
return any(self._match_state(src) for src in transition.source)
else:
return self._match_state(from_state)
def __call__(self, *args, **kwargs):
return self.function(*args, **kwargs)
def __eq__(self, other):
"""Equality is based on priority, function and kind."""
if not isinstance(other, Hook):
return NotImplemented
return (
self.priority == other.priority
and self.function == other.function
and self.kind == other.kind
and self.names == other.names
)
def __ne__(self, other):
if not isinstance(other, Hook):
return NotImplemented
return not (self == other)
def __lt__(self, other):
"""Compare hooks of the same kind."""
if not isinstance(other, Hook):
return NotImplemented
return (
(other.priority, self.function.__name__)
< (self.priority, other.function.__name__))
def __gt__(self, other):
"""Compare hooks of the same kind."""
if not isinstance(other, Hook):
return NotImplemented
return (
(other.priority, self.function.__name__)
> (self.priority, other.function.__name__))
def __repr__(self):
return '<%s: %s %r>' % (
self.__class__.__name__, self.kind, self.function)
class ImplementationWrapper(object):
"""Wraps a transition implementation.
Emulates a function behaviour, but provides a few extra features.
Attributes:
instance (WorkflowEnabled): the instance to update
.
field_name (str): the name of the field of the instance to update.
transition (Transition): the transition to perform
workflow (Workflow): the workflow to which this is related.
hooks (Hook list): optional hooks to call during the transition
implementation (callable): the code to invoke between 'before' and the
state update.
"""
def __init__(self, instance, field_name, transition, workflow,
implementation, hooks=None):
self.instance = instance
self.field_name = field_name
self.transition = transition
self.workflow = workflow
self.hooks = hooks or {}
self.implementation = implementation
self.__doc__ = implementation.__doc__
@property
def current_state(self):
return getattr(self.instance, self.field_name)
def _pre_transition_checks(self):
"""Run the pre-transition checks."""
current_state = getattr(self.instance, self.field_name)
if current_state not in self.transition.source:
raise InvalidTransitionError(
"Transition '%s' isn't available from state '%s'." %
(self.transition.name, current_state.name))
for check in self._filter_hooks(HOOK_CHECK):
if not check(self.instance):
raise ForbiddenTransition(
"Transition '%s' was forbidden by "
"custom pre-transition check." % self.transition.name)
def _filter_hooks(self, *hook_kinds):
"""Filter a list of hooks, keeping only applicable ones."""
hooks = sum((self.hooks.get(kind, []) for kind in hook_kinds), [])
return sorted(hook for hook in hooks
if hook.applies_to(self.transition, self.current_state))
def _pre_transition(self, *args, **kwargs):
for hook in self._filter_hooks(HOOK_BEFORE, HOOK_ON_LEAVE):
hook(self.instance, *args, **kwargs)
def _during_transition(self, *args, **kwargs):
return self.implementation(self.instance, *args, **kwargs)
def _log_transition(self, from_state, *args, **kwargs):
self.workflow.log_transition(
self.transition, from_state, self.instance,
*args, **kwargs)
def _post_transition(self, result, *args, **kwargs):
"""Performs post-transition actions."""
for hook in self._filter_hooks(HOOK_AFTER, HOOK_ON_ENTER):
hook(self.instance, result, *args, **kwargs)
def __call__(self, *args, **kwargs):
"""Run the transition, with all checks."""
self._pre_transition_checks()
# Call hooks.
self._pre_transition(*args, **kwargs)
result = self._during_transition(*args, **kwargs)
from_state = getattr(self.instance, self.field_name)
setattr(self.instance, self.field_name, self.transition.target)
# Call hooks.
self._log_transition(from_state, *args, **kwargs)
self._post_transition(result, *args, **kwargs)
return result
def is_available(self):
"""Check whether this transition is available on the current object.
Returns:
bool
"""
try:
self._pre_transition_checks()
except (InvalidTransitionError, ForbiddenTransition):
return False
return True
def __repr__(self):
return "<%s for %r on %r: %r>" % (
self.__class__.__name__,
self.transition.name, self.field_name, self.implementation)
class ImplementationProperty(object):
"""Holds an implementation of a transition.
This class is a 'non-data descriptor', somewhat similar to a property.
Attributes:
field_name (str): the name of the field of the instance to update.
transition (Transition): the transition to perform
workflow (Workflow): the workflow to which this is related.
hooks (Hook list): hooks to apply along with the transition.
implementation (callable): the code to invoke between 'before' and the
state update.
"""
def __init__(self, field_name, transition, workflow, implementation, hooks=None):
self.field_name = field_name
self.transition = transition
self.workflow = workflow
self.hooks = hooks or {}
self.implementation = implementation
self.__doc__ = implementation.__doc__
def copy(self):
return self.__class__(
field_name=self.field_name,
transition=self.transition,
workflow=self.workflow,
implementation=self.implementation,
# Don't copy hooks: they'll be re-generated during metaclass __new__
hooks={},
)
def add_hook(self, hook):
self.hooks.setdefault(hook.kind, []).append(hook)
def __get__(self, instance, owner):
if instance is None:
return self
if not isinstance(instance, BaseWorkflowEnabled):
raise TypeError(
"Unable to apply transition '%s' to object %r, which is not "
"attached to a Workflow." % (self.transition.name, instance))
return self.workflow.implementation_class(
instance,
self.field_name, self.transition, self.workflow,
self.implementation, self.hooks)
def __repr__(self):
return "<%s for '%s' on '%s': %s>" % (
self.__class__.__name__,
self.transition.name, self.field_name, self.implementation)
class TransitionWrapper(object):
"""Mark that a method should be used for a transition with a different name.
Attributes:
trname (str): the name of the transition that the method implements
func (function): the decorated method
"""
def __init__(self, trname, field='', check=None, before=None, after=None):
self.trname = trname
self.field = field
self.check = check
self.before = before
self.after = after
self.func = None
def __call__(self, func):
self.func = func
if self.trname == '':
self.trname = func.__name__
return self
def __repr__(self):
return "<%s for %r: %s>" % (self.__class__.__name__, self.trname, self.func)
def _make_hook_dict(fun):
"""Ensure the given function has a xworkflows_hook attribute.
That attribute has the following structure:
>>> {
... 'before': [('state', <TransitionHook>), ...],
... }
"""
if not hasattr(fun, 'xworkflows_hook'):
fun.xworkflows_hook = {
HOOK_BEFORE: [],
HOOK_AFTER: [],
HOOK_CHECK: [],
HOOK_ON_ENTER: [],
HOOK_ON_LEAVE: [],
}
return fun.xworkflows_hook
class _HookDeclaration(object):
"""Base class for decorators declaring methods as transition hooks.
Args:
*names (str tuple): name of the states/transitions to bind to; use '*'
for 'all'
priority (int): priority of the hook, defaults to 0
field (str): name of the field to which the hooked transition relates
Usage:
>>> @_HookDeclaration('foo', 'bar', priority=4)
... def my_hook(self):
... pass
"""
def __init__(self, *names, **kwargs):
if not names:
names = ('*',)
self.names = names
self.priority = kwargs.get('priority', 0)
self.field = kwargs.get('field', '')
def _as_hook(self, func):
return Hook(self.hook_name, func, *self.names, priority=self.priority)
def __call__(self, func):
hook_dict = _make_hook_dict(func)
hooks = hook_dict[self.hook_name]
hooks.append((self.field, self._as_hook(func)))
return func
class before_transition(_HookDeclaration):
"""Decorates a method that should be called before a given transition.
Example:
>>> @before_transition('foobar')
... def blah(self):
... pass
"""
hook_name = HOOK_BEFORE
class after_transition(_HookDeclaration):
"""Decorates a method that should be called after a given transition.
Example:
>>> @after_transition('foobar')
... def blah(self):
... pass
"""
hook_name = HOOK_AFTER
class transition_check(_HookDeclaration):
"""Decorates a method that should be called after a given transition.
Example:
>>> @transition_check('foobar')
... def blah(self):
... pass
"""
hook_name = HOOK_CHECK
class on_enter_state(_HookDeclaration):
"""Decorates a method that should be used as a hook for a state.
Example:
>>> @on_enter_state('foo', 'bar')
... def blah(self):
... pass
"""
hook_name = HOOK_ON_ENTER
class on_leave_state(_HookDeclaration):
"""Decorates a method that should be used as a hook for a state.
Example:
>>> @on_leave_state('foo', 'bar')
... def blah(self):
... pass
"""
hook_name = HOOK_ON_LEAVE
def noop(instance, *args, **kwargs):
"""NoOp function, ignores all arguments."""
pass
class ImplementationList(object):
"""Stores all implementations.
Attributes:
state_field (str): the name of the field holding the state of objects.
implementations (dict(str => ImplementationProperty)): maps a transition
name to the associated implementation.
workflow (Workflow): the related workflow
transitions_at (dict(str => str)): maps a transition name to the
name of the attribute holding the related implementation.
custom_implems (str set): list of transition names for which a custom
implementation has been defined.
"""
def __init__(self, state_field, workflow):
self.state_field = state_field
self.workflow = workflow
self.implementations = {}
self.transitions_at = {}
self.custom_implems = set()
def load_parent_implems(self, parent_implems):
"""Import previously defined implementations.
Args:
parent_implems (ImplementationList): List of implementations defined
in a parent class.
"""
for trname, attr, implem in parent_implems.get_custom_implementations():
self.implementations[trname] = implem.copy()
self.transitions_at[trname] = attr
self.custom_implems.add(trname)
def add_implem(self, transition, attribute, function, **kwargs):
"""Add an implementation.
Args:
transition (Transition): the transition for which the implementation
is added
attribute (str): the name of the attribute where the implementation
will be available
function (callable): the actual implementation function
**kwargs: extra arguments for the related ImplementationProperty.
"""
implem = ImplementationProperty(
field_name=self.state_field,
transition=transition,
workflow=self.workflow,
implementation=function,
**kwargs)
self.implementations[transition.name] = implem
self.transitions_at[transition.name] = attribute
return implem
def should_collect(self, value):
"""Decide whether a given value should be collected."""
return (
# decorated with @transition
isinstance(value, TransitionWrapper)
# Relates to a compatible transition
and value.trname in self.workflow.transitions
# Either not bound to a state field or bound to the current one
and (not value.field or value.field == self.state_field))
def collect(self, attrs):
"""Collect the implementations from a given attributes dict."""
for name, value in attrs.items():
if self.should_collect(value):
transition = self.workflow.transitions[value.trname]
if (
value.trname in self.implementations
and value.trname in self.custom_implems
and name != self.transitions_at[value.trname]):
# We already have an implementation registered.
other_implem_at = self.transitions_at[value.trname]
raise ValueError(
"Error for attribute %s: it defines implementation "
"%s for transition %s, which is already implemented "
"at %s." % (name, value, transition, other_implem_at))
implem = self.add_implem(transition, name, value.func)
self.custom_implems.add(transition.name)
if value.check:
implem.add_hook(Hook(HOOK_CHECK, value.check))
if value.before:
implem.add_hook(Hook(HOOK_BEFORE, value.before))
if value.after:
implem.add_hook(Hook(HOOK_AFTER, value.after))
def get_custom_implementations(self):
"""Retrieve a list of cutom implementations.
Yields:
(str, str, ImplementationProperty) tuples: The name of the attribute
an implementation lives at, the name of the related transition,
and the related implementation.
"""
for trname in self.custom_implems:
attr = self.transitions_at[trname]
implem = self.implementations[trname]
yield (trname, attr, implem)
def add_missing_implementations(self):
for transition in self.workflow.transitions:
if transition.name not in self.implementations:
self.add_implem(transition, transition.name, noop)
def register_hooks(self, cls):
for field, value in utils.iterclass(cls):
if is_callable(value) and hasattr(value, 'xworkflows_hook'):
self.register_function_hooks(value)
def register_function_hooks(self, func):
"""Looks at an object method and registers it for relevent transitions."""
for hook_kind, hooks in func.xworkflows_hook.items():
for field_name, hook in hooks:
if field_name and field_name != self.state_field:
continue
for transition in self.workflow.transitions:
if hook.applies_to(transition):
implem = self.implementations[transition.name]
implem.add_hook(hook)
def _may_override(self, implem, other):
"""Checks whether an ImplementationProperty may override an attribute."""
if isinstance(other, ImplementationProperty):
# Overriding another custom implementation for the same transition
# and field
return (other.transition == implem.transition and other.field_name == self.state_field)
elif isinstance(other, TransitionWrapper):
# Overriding the definition that led to adding the current
# ImplementationProperty.
return (
other.trname == implem.transition.name
and (not other.field or other.field == self.state_field)
and other.func == implem.implementation)
return False
def fill_attrs(self, attrs):
"""Update the 'attrs' dict with generated ImplementationProperty."""
for trname, attrname in self.transitions_at.items():
implem = self.implementations[trname]
if attrname in attrs:
conflicting = attrs[attrname]
if not self._may_override(implem, conflicting):
raise ValueError(
"Can't override transition implementation %s=%r with %r" %
(attrname, conflicting, implem))
attrs[attrname] = implem
return attrs
def transform(self, attrs):
"""Perform all actions on a given attribute dict."""
self.collect(attrs)
self.add_missing_implementations()
self.fill_attrs(attrs)
class WorkflowMeta(type):
"""Base metaclass for all Workflows.
Sets the 'states', 'transitions', and 'initial_state' attributes.
"""
def __new__(mcs, name, bases, attrs):
state_defs = attrs.pop('states', [])
transitions_defs = attrs.pop('transitions', [])
initial_state = attrs.pop('initial_state', None)
new_class = super(WorkflowMeta, mcs).__new__(mcs, name, bases, attrs)
new_class.states = _setup_states(state_defs, getattr(new_class, 'states', []))
new_class.transitions = _setup_transitions(
transitions_defs,
new_class.states,
getattr(new_class, 'transitions', []),
)
if initial_state is not None:
new_class.initial_state = new_class.states[initial_state]
return new_class
class BaseWorkflow(object):
"""Base class for all workflows.
Attributes:
states (StateList): list of states of this Workflow
transitions (TransitionList): list of Transitions of this Workflow
initial_state (State): initial state for the Workflow
implementation_class (ImplementationWrapper subclass): class to use
for transition implementation wrapping.
For each transition, a ImplementationWrapper with the same name (unless
another name has been specified through the use of the @transition
decorator) is provided to perform the specified transition.
"""
implementation_class = ImplementationWrapper
def log_transition(self, transition, from_state, instance, *args, **kwargs):
"""Log a transition.
Args:
transition (Transition): the name of the performed transition
from_state (State): the source state
instance (object): the modified object
Kwargs:
Any passed when calling the transition
"""
logger = logging.getLogger('xworkflows.transitions')
try:
instance_repr = u(repr(instance), 'ignore')
except (UnicodeEncodeError, UnicodeDecodeError):
instance_repr = u("<bad repr>")
logger.info(
u("%s performed transition %s.%s (%s -> %s)"), instance_repr,
self.__class__.__name__, transition.name, from_state.name,
transition.target.name)
# Workaround for metaclasses on python2/3.
# Equivalent to:
# Python2
#
# class Workflow(BaseWorkflow):
# __metaclass__ = WorkflowMeta
#
# Python3
#
# class Workflow(metaclass=WorkflowMeta):
# pass
Workflow = WorkflowMeta('Workflow', (BaseWorkflow,), {})
class StateWrapper(object):
"""Slightly enhanced wrapper around a base State object.
Knows about the workflow.
"""
def __init__(self, state, workflow):
self.state = state
self.workflow = workflow
for st in workflow.states:
setattr(self, 'is_%s' % st.name, st.name == self.state.name)
def __eq__(self, other):
if isinstance(other, self.__class__):
return self.state == other.state
elif isinstance(other, State):
return self.state == other
elif is_string(other):
return self.state.name == other
else:
return NotImplemented
def __ne__(self, other):
return not (self == other)
def __str__(self):
return self.state.name
def __repr__(self):
return '<%s: %r>' % (self.__class__.__name__, self.state)
def __getattr__(self, attr):
if attr == 'state':
raise AttributeError(
'Trying to access attribute %s of a non-initialized %r object!'
% (attr, self.__class__))
else:
return getattr(self.state, attr)
if not is_python3:
def __unicode__(self):
return u(str(self))
def __hash__(self):
# A StateWrapper should compare equal to its name.
return hash(self.state.name)
def transitions(self):
"""Retrieve a list of transitions available from this state."""
return self.workflow.transitions.available_from(self.state)
class StateProperty(object):
"""Property-like attribute holding the state of a WorkflowEnabled object.
The state is stored in the internal __dict__ of the instance.
"""
def __init__(self, workflow, state_field_name):
super(StateProperty, self).__init__()
self.workflow = workflow
self.field_name = state_field_name
def __get__(self, instance, owner):
"""Retrieve the current state of the 'instance' object."""
if instance is None:
return self
state = instance.__dict__.get(self.field_name,
self.workflow.initial_state)
return StateWrapper(state, self.workflow)
def __set__(self, instance, value):
"""Set the current state of the 'instance' object."""
try:
state = self.workflow.states[value]
except KeyError:
raise ValueError("Value %s is not a valid state for workflow %s." % (value, self.workflow))
instance.__dict__[self.field_name] = state
def __str__(self):
return 'StateProperty(%s, %s)' % (self.workflow, self.field_name)
class StateField(object):
"""Indicates that a given class attribute is actually a workflow state."""
def __init__(self, workflow):
self.workflow = workflow
class WorkflowEnabledMeta(type):
"""Base metaclass for all Workflow Enabled objects.
Defines:
- one class attribute for each the attached workflows,
- a '_workflows' attribute, a dict mapping each field_name to the related
Workflow,
- a '_xworkflows_implems' attribute, a dict mapping each field_name to a
dict of related ImplementationProperty.
- one class attribute for each transition for each attached workflow
"""
@classmethod
def _add_workflow(mcs, field_name, state_field, attrs):
"""Attach a workflow to the attribute list (create a StateProperty)."""
attrs[field_name] = StateProperty(state_field.workflow, field_name)
@classmethod
def _find_workflows(mcs, attrs):
"""Finds all occurrences of a workflow in the attributes definitions.
Returns:
dict(str => StateField): maps an attribute name to a StateField
describing the related Workflow.
"""
workflows = {}
for attribute, value in attrs.items():
if isinstance(value, Workflow):
workflows[attribute] = StateField(value)
return workflows
@classmethod
def _add_transitions(mcs, field_name, workflow, attrs, implems=None):
"""Collect and enhance transition definitions to a workflow.
Modifies the 'attrs' dict in-place.
Args:
field_name (str): name of the field transitions should update
workflow (Workflow): workflow we're working on
attrs (dict): dictionary of attributes to be updated.
implems (ImplementationList): Implementation list from parent
classes (optional)
Returns:
ImplementationList: The new implementation list for this field.
"""
new_implems = ImplementationList(field_name, workflow)
if implems:
new_implems.load_parent_implems(implems)
new_implems.transform(attrs)
return new_implems
@classmethod
def _register_hooks(mcs, cls, implems):
for implem_list in implems.values():
implem_list.register_hooks(cls)
def __new__(mcs, name, bases, attrs):
# Map field_name => StateField
workflows = {}
# Map field_name => ImplementationList
implems = {}
# Collect workflows and implementations from parents
for base in reversed(bases):
if hasattr(base, '_workflows'):
workflows.update(base._workflows)
implems.update(base._xworkflows_implems)
workflows.update(mcs._find_workflows(attrs))
# Update attributes with workflow descriptions, and collect
# implementation declarations.
for field, state_field in workflows.items():
mcs._add_workflow(field, state_field, attrs)
implems[field] = mcs._add_transitions(
field, state_field.workflow, attrs, implems.get(field))
# Set specific attributes for children
attrs['_workflows'] = workflows
attrs['_xworkflows_implems'] = implems
cls = super(WorkflowEnabledMeta, mcs).__new__(mcs, name, bases, attrs)
mcs._register_hooks(cls, implems)
return cls
class BaseWorkflowEnabled(object):
"""Base class for all objects using a workflow.
Attributes:
workflows (dict(str, StateField)): Maps the name of a 'state_field' to
the related Workflow
"""
# Workaround for metaclasses on python2/3.
# Equivalent to:
# Python2
#
# class WorkflowEnabled(BaseWorkflowEnabled):
# __metaclass__ = WorkflowEnabledMeta
#
# Python3
#
# class WorkflowEnabled(metaclass=WorkflowEnabledMeta):
# pass
WorkflowEnabled = WorkflowEnabledMeta('WorkflowEnabled', (BaseWorkflowEnabled,), {})
|
rbarrois/xworkflows | src/xworkflows/base.py | _make_hook_dict | python | def _make_hook_dict(fun):
if not hasattr(fun, 'xworkflows_hook'):
fun.xworkflows_hook = {
HOOK_BEFORE: [],
HOOK_AFTER: [],
HOOK_CHECK: [],
HOOK_ON_ENTER: [],
HOOK_ON_LEAVE: [],
}
return fun.xworkflows_hook | Ensure the given function has a xworkflows_hook attribute.
That attribute has the following structure:
>>> {
... 'before': [('state', <TransitionHook>), ...],
... } | train | https://github.com/rbarrois/xworkflows/blob/4a94b04ba83cb43f61d4b0f7db6964a667c86b5b/src/xworkflows/base.py#L532-L548 | null | # -*- coding: utf-8 -*-
# Copyright (c) 2011-2013 Raphaël Barrois
# This code is distributed under the two-clause BSD License.
"""Base components of XWorkflows."""
import logging
import re
import warnings
from .compat import is_callable, is_python3, is_string, u
from . import utils
class WorkflowError(Exception):
"""Base class for errors from the xworkflows module."""
class AbortTransition(WorkflowError):
"""Raised to prevent a transition from proceeding."""
class InvalidTransitionError(AbortTransition):
"""Raised when trying to perform a transition not available from current state."""
class ForbiddenTransition(AbortTransition):
"""Raised when the 'check' hook of a transition was defined and returned False."""
class State(object):
"""A state within a workflow.
Attributes:
name (str): the name of the state
title (str): the human-readable title for the state
"""
STATE_NAME_RE = re.compile('\w+$')
def __init__(self, name, title):
if not self.STATE_NAME_RE.match(name):
raise ValueError('Invalid state name %s.' % name)
self.name = name
self.title = title
def __str__(self):
return self.name
def __repr__(self):
return '<%s: %r>' % (self.__class__.__name__, self.name)
class StateList(object):
"""A list of states."""
def __init__(self, states):
self._states = dict((st.name, st) for st in states)
self._order = tuple(st.name for st in states)
def __getattr__(self, name):
try:
return self._states[name]
except KeyError:
raise AttributeError('StateList %s has no state named %s' % (self, name))
def __len__(self):
return len(self._states)
def __getitem__(self, name_or_state):
if isinstance(name_or_state, State):
return self._states[name_or_state.name]
else:
return self._states[name_or_state]
def __repr__(self):
return '%s(%r)' % (self.__class__.__name__, self._states)
def __iter__(self):
for name in self._order:
yield self._states[name]
def __contains__(self, state):
if isinstance(state, State):
return state.name in self._states and self._states[state.name] == state
else: # Expect a state name
return state in self._states
class Transition(object):
"""A transition.
Attributes:
name (str): the name of the Transition
source (State list): the 'source' states of the transition
target (State): the 'target' state of the transition
"""
def __init__(self, name, source, target):
self.name = name
if isinstance(source, State):
source = [source]
self.source = source
self.target = target
def __repr__(self):
return '%s(%r, %r, %r)' % (self.__class__.__name__,
self.name, self.source, self.target)
class TransitionList(object):
"""Holder for the transitions of a given workflow."""
def __init__(self, transitions):
"""Create a TransitionList.
Args:
transitions (list of (name, source, target) tuple): the transitions
to include.
"""
self._transitions = {}
self._order = []
for trdef in transitions:
self._transitions[trdef.name] = trdef
self._order.append(trdef.name)
def __len__(self):
return len(self._transitions)
def __getattr__(self, name):
try:
return self._transitions[name]
except KeyError:
raise AttributeError(
"TransitionList %s has no transition named %s." % (self, name))
def __getitem__(self, name):
return self._transitions[name]
def __iter__(self):
for name in self._order:
yield self._transitions[name]
def __contains__(self, value):
if isinstance(value, Transition):
return value.name in self._transitions and self._transitions[value.name] == value
else:
return value in self._transitions
def available_from(self, state):
"""Retrieve all transitions available from a given state.
Args:
state (State): the initial state.
Yields:
Transition: all transitions starting from that state
"""
for transition in self:
if state in transition.source:
yield transition
def __repr__(self):
return '%s(%r)' % (self.__class__.__name__, self._transitions.values())
def _setup_states(state_definitions, prev=()):
"""Create a StateList object from a 'states' Workflow attribute."""
states = list(prev)
for state_def in state_definitions:
if len(state_def) != 2:
raise TypeError(
"The 'state' attribute of a workflow should be "
"a two-tuple of strings; got %r instead." % (state_def,)
)
name, title = state_def
state = State(name, title)
if any(st.name == name for st in states):
# Replacing an existing state
states = [state if st.name == name else st for st in states]
else:
states.append(state)
return StateList(states)
def _setup_transitions(tdef, states, prev=()):
"""Create a TransitionList object from a 'transitions' Workflow attribute.
Args:
tdef: list of transition definitions
states (StateList): already parsed state definitions.
prev (TransitionList): transition definitions from a parent.
Returns:
TransitionList: the list of transitions defined in the 'tdef' argument.
"""
trs = list(prev)
for transition in tdef:
if len(transition) == 3:
(name, source, target) = transition
if is_string(source) or isinstance(source, State):
source = [source]
source = [states[src] for src in source]
target = states[target]
tr = Transition(name, source, target)
else:
raise TypeError(
"Elements of the 'transition' attribute of a "
"workflow should be three-tuples; got %r instead." % (transition,)
)
if any(prev_tr.name == tr.name for prev_tr in trs):
# Replacing an existing state
trs = [tr if prev_tr.name == tr.name else prev_tr for prev_tr in trs]
else:
trs.append(tr)
return TransitionList(trs)
HOOK_BEFORE = 'before'
HOOK_AFTER = 'after'
HOOK_CHECK = 'check'
HOOK_ON_ENTER = 'on_enter'
HOOK_ON_LEAVE = 'on_leave'
class Hook(object):
"""A hook to run when a transition occurs.
Attributes:
kind (str): the kind of hook
priority (int): the priority of the hook (higher values run first)
function (callable): the actual function to call
names (str list): name of the transitions or states to which the hook
relates. The special value '*' means 'applies to all transitions/
states'.
Hooks are sortable by descending priority and ascending function name.
Hook kinds are as follow:
- HOOK_BEFORE: run before the related transitions
- HOOK_AFTER: run after the related transitions
- HOOK_CHECK: run as part of pre-transition checks (return value matters)
- HOOK_ON_ENTER: run just after a transition entering a related state
- HOOK_ON_LEAVE: run just before a transition leaving from a related state
"""
def __init__(self, kind, function, *names, **kwargs):
assert kind in (
HOOK_BEFORE, HOOK_AFTER, HOOK_CHECK,
HOOK_ON_ENTER, HOOK_ON_LEAVE)
self.kind = kind
self.priority = kwargs.get('priority', 0)
self.function = function
self.names = names or ('*',)
def _match_state(self, state):
"""Checks whether a given State matches self.names."""
return (self.names == '*'
or state in self.names
or state.name in self.names)
def _match_transition(self, transition):
"""Checks whether a given Transition matches self.names."""
return (self.names == '*'
or transition in self.names
or transition.name in self.names)
def applies_to(self, transition, from_state=None):
"""Whether this hook applies to the given transition/state.
Args:
transition (Transition): the transition to check
from_state (State or None): the state to check. If absent, the check
is 'might this hook apply to the related transition, given a
valid source state'.
"""
if '*' in self.names:
return True
elif self.kind in (HOOK_BEFORE, HOOK_AFTER, HOOK_CHECK):
return self._match_transition(transition)
elif self.kind == HOOK_ON_ENTER:
return self._match_state(transition.target)
elif from_state is None:
# Testing whether the hook may apply to at least one source of the
# transition
return any(self._match_state(src) for src in transition.source)
else:
return self._match_state(from_state)
def __call__(self, *args, **kwargs):
return self.function(*args, **kwargs)
def __eq__(self, other):
"""Equality is based on priority, function and kind."""
if not isinstance(other, Hook):
return NotImplemented
return (
self.priority == other.priority
and self.function == other.function
and self.kind == other.kind
and self.names == other.names
)
def __ne__(self, other):
if not isinstance(other, Hook):
return NotImplemented
return not (self == other)
def __lt__(self, other):
"""Compare hooks of the same kind."""
if not isinstance(other, Hook):
return NotImplemented
return (
(other.priority, self.function.__name__)
< (self.priority, other.function.__name__))
def __gt__(self, other):
"""Compare hooks of the same kind."""
if not isinstance(other, Hook):
return NotImplemented
return (
(other.priority, self.function.__name__)
> (self.priority, other.function.__name__))
def __repr__(self):
return '<%s: %s %r>' % (
self.__class__.__name__, self.kind, self.function)
class ImplementationWrapper(object):
"""Wraps a transition implementation.
Emulates a function behaviour, but provides a few extra features.
Attributes:
instance (WorkflowEnabled): the instance to update
.
field_name (str): the name of the field of the instance to update.
transition (Transition): the transition to perform
workflow (Workflow): the workflow to which this is related.
hooks (Hook list): optional hooks to call during the transition
implementation (callable): the code to invoke between 'before' and the
state update.
"""
def __init__(self, instance, field_name, transition, workflow,
implementation, hooks=None):
self.instance = instance
self.field_name = field_name
self.transition = transition
self.workflow = workflow
self.hooks = hooks or {}
self.implementation = implementation
self.__doc__ = implementation.__doc__
@property
def current_state(self):
return getattr(self.instance, self.field_name)
def _pre_transition_checks(self):
"""Run the pre-transition checks."""
current_state = getattr(self.instance, self.field_name)
if current_state not in self.transition.source:
raise InvalidTransitionError(
"Transition '%s' isn't available from state '%s'." %
(self.transition.name, current_state.name))
for check in self._filter_hooks(HOOK_CHECK):
if not check(self.instance):
raise ForbiddenTransition(
"Transition '%s' was forbidden by "
"custom pre-transition check." % self.transition.name)
def _filter_hooks(self, *hook_kinds):
"""Filter a list of hooks, keeping only applicable ones."""
hooks = sum((self.hooks.get(kind, []) for kind in hook_kinds), [])
return sorted(hook for hook in hooks
if hook.applies_to(self.transition, self.current_state))
def _pre_transition(self, *args, **kwargs):
for hook in self._filter_hooks(HOOK_BEFORE, HOOK_ON_LEAVE):
hook(self.instance, *args, **kwargs)
def _during_transition(self, *args, **kwargs):
return self.implementation(self.instance, *args, **kwargs)
def _log_transition(self, from_state, *args, **kwargs):
self.workflow.log_transition(
self.transition, from_state, self.instance,
*args, **kwargs)
def _post_transition(self, result, *args, **kwargs):
"""Performs post-transition actions."""
for hook in self._filter_hooks(HOOK_AFTER, HOOK_ON_ENTER):
hook(self.instance, result, *args, **kwargs)
def __call__(self, *args, **kwargs):
"""Run the transition, with all checks."""
self._pre_transition_checks()
# Call hooks.
self._pre_transition(*args, **kwargs)
result = self._during_transition(*args, **kwargs)
from_state = getattr(self.instance, self.field_name)
setattr(self.instance, self.field_name, self.transition.target)
# Call hooks.
self._log_transition(from_state, *args, **kwargs)
self._post_transition(result, *args, **kwargs)
return result
def is_available(self):
"""Check whether this transition is available on the current object.
Returns:
bool
"""
try:
self._pre_transition_checks()
except (InvalidTransitionError, ForbiddenTransition):
return False
return True
def __repr__(self):
return "<%s for %r on %r: %r>" % (
self.__class__.__name__,
self.transition.name, self.field_name, self.implementation)
class ImplementationProperty(object):
"""Holds an implementation of a transition.
This class is a 'non-data descriptor', somewhat similar to a property.
Attributes:
field_name (str): the name of the field of the instance to update.
transition (Transition): the transition to perform
workflow (Workflow): the workflow to which this is related.
hooks (Hook list): hooks to apply along with the transition.
implementation (callable): the code to invoke between 'before' and the
state update.
"""
def __init__(self, field_name, transition, workflow, implementation, hooks=None):
self.field_name = field_name
self.transition = transition
self.workflow = workflow
self.hooks = hooks or {}
self.implementation = implementation
self.__doc__ = implementation.__doc__
def copy(self):
return self.__class__(
field_name=self.field_name,
transition=self.transition,
workflow=self.workflow,
implementation=self.implementation,
# Don't copy hooks: they'll be re-generated during metaclass __new__
hooks={},
)
def add_hook(self, hook):
self.hooks.setdefault(hook.kind, []).append(hook)
def __get__(self, instance, owner):
if instance is None:
return self
if not isinstance(instance, BaseWorkflowEnabled):
raise TypeError(
"Unable to apply transition '%s' to object %r, which is not "
"attached to a Workflow." % (self.transition.name, instance))
return self.workflow.implementation_class(
instance,
self.field_name, self.transition, self.workflow,
self.implementation, self.hooks)
def __repr__(self):
return "<%s for '%s' on '%s': %s>" % (
self.__class__.__name__,
self.transition.name, self.field_name, self.implementation)
class TransitionWrapper(object):
"""Mark that a method should be used for a transition with a different name.
Attributes:
trname (str): the name of the transition that the method implements
func (function): the decorated method
"""
def __init__(self, trname, field='', check=None, before=None, after=None):
self.trname = trname
self.field = field
self.check = check
self.before = before
self.after = after
self.func = None
def __call__(self, func):
self.func = func
if self.trname == '':
self.trname = func.__name__
return self
def __repr__(self):
return "<%s for %r: %s>" % (self.__class__.__name__, self.trname, self.func)
def transition(trname='', field='', check=None, before=None, after=None):
"""Decorator to declare a function as a transition implementation."""
if is_callable(trname):
raise ValueError(
"The @transition decorator should be called as "
"@transition(['transition_name'], **kwargs)")
if check or before or after:
warnings.warn(
"The use of check=, before= and after= in @transition decorators is "
"deprecated in favor of @transition_check, @before_transition and "
"@after_transition decorators.",
DeprecationWarning,
stacklevel=2)
return TransitionWrapper(trname, field=field, check=check, before=before, after=after)
class _HookDeclaration(object):
"""Base class for decorators declaring methods as transition hooks.
Args:
*names (str tuple): name of the states/transitions to bind to; use '*'
for 'all'
priority (int): priority of the hook, defaults to 0
field (str): name of the field to which the hooked transition relates
Usage:
>>> @_HookDeclaration('foo', 'bar', priority=4)
... def my_hook(self):
... pass
"""
def __init__(self, *names, **kwargs):
if not names:
names = ('*',)
self.names = names
self.priority = kwargs.get('priority', 0)
self.field = kwargs.get('field', '')
def _as_hook(self, func):
return Hook(self.hook_name, func, *self.names, priority=self.priority)
def __call__(self, func):
hook_dict = _make_hook_dict(func)
hooks = hook_dict[self.hook_name]
hooks.append((self.field, self._as_hook(func)))
return func
class before_transition(_HookDeclaration):
"""Decorates a method that should be called before a given transition.
Example:
>>> @before_transition('foobar')
... def blah(self):
... pass
"""
hook_name = HOOK_BEFORE
class after_transition(_HookDeclaration):
"""Decorates a method that should be called after a given transition.
Example:
>>> @after_transition('foobar')
... def blah(self):
... pass
"""
hook_name = HOOK_AFTER
class transition_check(_HookDeclaration):
"""Decorates a method that should be called after a given transition.
Example:
>>> @transition_check('foobar')
... def blah(self):
... pass
"""
hook_name = HOOK_CHECK
class on_enter_state(_HookDeclaration):
"""Decorates a method that should be used as a hook for a state.
Example:
>>> @on_enter_state('foo', 'bar')
... def blah(self):
... pass
"""
hook_name = HOOK_ON_ENTER
class on_leave_state(_HookDeclaration):
"""Decorates a method that should be used as a hook for a state.
Example:
>>> @on_leave_state('foo', 'bar')
... def blah(self):
... pass
"""
hook_name = HOOK_ON_LEAVE
def noop(instance, *args, **kwargs):
"""NoOp function, ignores all arguments."""
pass
class ImplementationList(object):
"""Stores all implementations.
Attributes:
state_field (str): the name of the field holding the state of objects.
implementations (dict(str => ImplementationProperty)): maps a transition
name to the associated implementation.
workflow (Workflow): the related workflow
transitions_at (dict(str => str)): maps a transition name to the
name of the attribute holding the related implementation.
custom_implems (str set): list of transition names for which a custom
implementation has been defined.
"""
def __init__(self, state_field, workflow):
self.state_field = state_field
self.workflow = workflow
self.implementations = {}
self.transitions_at = {}
self.custom_implems = set()
def load_parent_implems(self, parent_implems):
"""Import previously defined implementations.
Args:
parent_implems (ImplementationList): List of implementations defined
in a parent class.
"""
for trname, attr, implem in parent_implems.get_custom_implementations():
self.implementations[trname] = implem.copy()
self.transitions_at[trname] = attr
self.custom_implems.add(trname)
def add_implem(self, transition, attribute, function, **kwargs):
"""Add an implementation.
Args:
transition (Transition): the transition for which the implementation
is added
attribute (str): the name of the attribute where the implementation
will be available
function (callable): the actual implementation function
**kwargs: extra arguments for the related ImplementationProperty.
"""
implem = ImplementationProperty(
field_name=self.state_field,
transition=transition,
workflow=self.workflow,
implementation=function,
**kwargs)
self.implementations[transition.name] = implem
self.transitions_at[transition.name] = attribute
return implem
def should_collect(self, value):
"""Decide whether a given value should be collected."""
return (
# decorated with @transition
isinstance(value, TransitionWrapper)
# Relates to a compatible transition
and value.trname in self.workflow.transitions
# Either not bound to a state field or bound to the current one
and (not value.field or value.field == self.state_field))
def collect(self, attrs):
"""Collect the implementations from a given attributes dict."""
for name, value in attrs.items():
if self.should_collect(value):
transition = self.workflow.transitions[value.trname]
if (
value.trname in self.implementations
and value.trname in self.custom_implems
and name != self.transitions_at[value.trname]):
# We already have an implementation registered.
other_implem_at = self.transitions_at[value.trname]
raise ValueError(
"Error for attribute %s: it defines implementation "
"%s for transition %s, which is already implemented "
"at %s." % (name, value, transition, other_implem_at))
implem = self.add_implem(transition, name, value.func)
self.custom_implems.add(transition.name)
if value.check:
implem.add_hook(Hook(HOOK_CHECK, value.check))
if value.before:
implem.add_hook(Hook(HOOK_BEFORE, value.before))
if value.after:
implem.add_hook(Hook(HOOK_AFTER, value.after))
def get_custom_implementations(self):
"""Retrieve a list of cutom implementations.
Yields:
(str, str, ImplementationProperty) tuples: The name of the attribute
an implementation lives at, the name of the related transition,
and the related implementation.
"""
for trname in self.custom_implems:
attr = self.transitions_at[trname]
implem = self.implementations[trname]
yield (trname, attr, implem)
def add_missing_implementations(self):
for transition in self.workflow.transitions:
if transition.name not in self.implementations:
self.add_implem(transition, transition.name, noop)
def register_hooks(self, cls):
for field, value in utils.iterclass(cls):
if is_callable(value) and hasattr(value, 'xworkflows_hook'):
self.register_function_hooks(value)
def register_function_hooks(self, func):
"""Looks at an object method and registers it for relevent transitions."""
for hook_kind, hooks in func.xworkflows_hook.items():
for field_name, hook in hooks:
if field_name and field_name != self.state_field:
continue
for transition in self.workflow.transitions:
if hook.applies_to(transition):
implem = self.implementations[transition.name]
implem.add_hook(hook)
def _may_override(self, implem, other):
"""Checks whether an ImplementationProperty may override an attribute."""
if isinstance(other, ImplementationProperty):
# Overriding another custom implementation for the same transition
# and field
return (other.transition == implem.transition and other.field_name == self.state_field)
elif isinstance(other, TransitionWrapper):
# Overriding the definition that led to adding the current
# ImplementationProperty.
return (
other.trname == implem.transition.name
and (not other.field or other.field == self.state_field)
and other.func == implem.implementation)
return False
def fill_attrs(self, attrs):
"""Update the 'attrs' dict with generated ImplementationProperty."""
for trname, attrname in self.transitions_at.items():
implem = self.implementations[trname]
if attrname in attrs:
conflicting = attrs[attrname]
if not self._may_override(implem, conflicting):
raise ValueError(
"Can't override transition implementation %s=%r with %r" %
(attrname, conflicting, implem))
attrs[attrname] = implem
return attrs
def transform(self, attrs):
"""Perform all actions on a given attribute dict."""
self.collect(attrs)
self.add_missing_implementations()
self.fill_attrs(attrs)
class WorkflowMeta(type):
"""Base metaclass for all Workflows.
Sets the 'states', 'transitions', and 'initial_state' attributes.
"""
def __new__(mcs, name, bases, attrs):
state_defs = attrs.pop('states', [])
transitions_defs = attrs.pop('transitions', [])
initial_state = attrs.pop('initial_state', None)
new_class = super(WorkflowMeta, mcs).__new__(mcs, name, bases, attrs)
new_class.states = _setup_states(state_defs, getattr(new_class, 'states', []))
new_class.transitions = _setup_transitions(
transitions_defs,
new_class.states,
getattr(new_class, 'transitions', []),
)
if initial_state is not None:
new_class.initial_state = new_class.states[initial_state]
return new_class
class BaseWorkflow(object):
"""Base class for all workflows.
Attributes:
states (StateList): list of states of this Workflow
transitions (TransitionList): list of Transitions of this Workflow
initial_state (State): initial state for the Workflow
implementation_class (ImplementationWrapper subclass): class to use
for transition implementation wrapping.
For each transition, a ImplementationWrapper with the same name (unless
another name has been specified through the use of the @transition
decorator) is provided to perform the specified transition.
"""
implementation_class = ImplementationWrapper
def log_transition(self, transition, from_state, instance, *args, **kwargs):
"""Log a transition.
Args:
transition (Transition): the name of the performed transition
from_state (State): the source state
instance (object): the modified object
Kwargs:
Any passed when calling the transition
"""
logger = logging.getLogger('xworkflows.transitions')
try:
instance_repr = u(repr(instance), 'ignore')
except (UnicodeEncodeError, UnicodeDecodeError):
instance_repr = u("<bad repr>")
logger.info(
u("%s performed transition %s.%s (%s -> %s)"), instance_repr,
self.__class__.__name__, transition.name, from_state.name,
transition.target.name)
# Workaround for metaclasses on python2/3.
# Equivalent to:
# Python2
#
# class Workflow(BaseWorkflow):
# __metaclass__ = WorkflowMeta
#
# Python3
#
# class Workflow(metaclass=WorkflowMeta):
# pass
Workflow = WorkflowMeta('Workflow', (BaseWorkflow,), {})
class StateWrapper(object):
"""Slightly enhanced wrapper around a base State object.
Knows about the workflow.
"""
def __init__(self, state, workflow):
self.state = state
self.workflow = workflow
for st in workflow.states:
setattr(self, 'is_%s' % st.name, st.name == self.state.name)
def __eq__(self, other):
if isinstance(other, self.__class__):
return self.state == other.state
elif isinstance(other, State):
return self.state == other
elif is_string(other):
return self.state.name == other
else:
return NotImplemented
def __ne__(self, other):
return not (self == other)
def __str__(self):
return self.state.name
def __repr__(self):
return '<%s: %r>' % (self.__class__.__name__, self.state)
def __getattr__(self, attr):
if attr == 'state':
raise AttributeError(
'Trying to access attribute %s of a non-initialized %r object!'
% (attr, self.__class__))
else:
return getattr(self.state, attr)
if not is_python3:
def __unicode__(self):
return u(str(self))
def __hash__(self):
# A StateWrapper should compare equal to its name.
return hash(self.state.name)
def transitions(self):
"""Retrieve a list of transitions available from this state."""
return self.workflow.transitions.available_from(self.state)
class StateProperty(object):
"""Property-like attribute holding the state of a WorkflowEnabled object.
The state is stored in the internal __dict__ of the instance.
"""
def __init__(self, workflow, state_field_name):
super(StateProperty, self).__init__()
self.workflow = workflow
self.field_name = state_field_name
def __get__(self, instance, owner):
"""Retrieve the current state of the 'instance' object."""
if instance is None:
return self
state = instance.__dict__.get(self.field_name,
self.workflow.initial_state)
return StateWrapper(state, self.workflow)
def __set__(self, instance, value):
"""Set the current state of the 'instance' object."""
try:
state = self.workflow.states[value]
except KeyError:
raise ValueError("Value %s is not a valid state for workflow %s." % (value, self.workflow))
instance.__dict__[self.field_name] = state
def __str__(self):
return 'StateProperty(%s, %s)' % (self.workflow, self.field_name)
class StateField(object):
"""Indicates that a given class attribute is actually a workflow state."""
def __init__(self, workflow):
self.workflow = workflow
class WorkflowEnabledMeta(type):
"""Base metaclass for all Workflow Enabled objects.
Defines:
- one class attribute for each the attached workflows,
- a '_workflows' attribute, a dict mapping each field_name to the related
Workflow,
- a '_xworkflows_implems' attribute, a dict mapping each field_name to a
dict of related ImplementationProperty.
- one class attribute for each transition for each attached workflow
"""
@classmethod
def _add_workflow(mcs, field_name, state_field, attrs):
"""Attach a workflow to the attribute list (create a StateProperty)."""
attrs[field_name] = StateProperty(state_field.workflow, field_name)
@classmethod
def _find_workflows(mcs, attrs):
"""Finds all occurrences of a workflow in the attributes definitions.
Returns:
dict(str => StateField): maps an attribute name to a StateField
describing the related Workflow.
"""
workflows = {}
for attribute, value in attrs.items():
if isinstance(value, Workflow):
workflows[attribute] = StateField(value)
return workflows
@classmethod
def _add_transitions(mcs, field_name, workflow, attrs, implems=None):
"""Collect and enhance transition definitions to a workflow.
Modifies the 'attrs' dict in-place.
Args:
field_name (str): name of the field transitions should update
workflow (Workflow): workflow we're working on
attrs (dict): dictionary of attributes to be updated.
implems (ImplementationList): Implementation list from parent
classes (optional)
Returns:
ImplementationList: The new implementation list for this field.
"""
new_implems = ImplementationList(field_name, workflow)
if implems:
new_implems.load_parent_implems(implems)
new_implems.transform(attrs)
return new_implems
@classmethod
def _register_hooks(mcs, cls, implems):
for implem_list in implems.values():
implem_list.register_hooks(cls)
def __new__(mcs, name, bases, attrs):
# Map field_name => StateField
workflows = {}
# Map field_name => ImplementationList
implems = {}
# Collect workflows and implementations from parents
for base in reversed(bases):
if hasattr(base, '_workflows'):
workflows.update(base._workflows)
implems.update(base._xworkflows_implems)
workflows.update(mcs._find_workflows(attrs))
# Update attributes with workflow descriptions, and collect
# implementation declarations.
for field, state_field in workflows.items():
mcs._add_workflow(field, state_field, attrs)
implems[field] = mcs._add_transitions(
field, state_field.workflow, attrs, implems.get(field))
# Set specific attributes for children
attrs['_workflows'] = workflows
attrs['_xworkflows_implems'] = implems
cls = super(WorkflowEnabledMeta, mcs).__new__(mcs, name, bases, attrs)
mcs._register_hooks(cls, implems)
return cls
class BaseWorkflowEnabled(object):
"""Base class for all objects using a workflow.
Attributes:
workflows (dict(str, StateField)): Maps the name of a 'state_field' to
the related Workflow
"""
# Workaround for metaclasses on python2/3.
# Equivalent to:
# Python2
#
# class WorkflowEnabled(BaseWorkflowEnabled):
# __metaclass__ = WorkflowEnabledMeta
#
# Python3
#
# class WorkflowEnabled(metaclass=WorkflowEnabledMeta):
# pass
WorkflowEnabled = WorkflowEnabledMeta('WorkflowEnabled', (BaseWorkflowEnabled,), {})
|
rbarrois/xworkflows | src/xworkflows/base.py | Hook._match_state | python | def _match_state(self, state):
return (self.names == '*'
or state in self.names
or state.name in self.names) | Checks whether a given State matches self.names. | train | https://github.com/rbarrois/xworkflows/blob/4a94b04ba83cb43f61d4b0f7db6964a667c86b5b/src/xworkflows/base.py#L256-L260 | null | class Hook(object):
"""A hook to run when a transition occurs.
Attributes:
kind (str): the kind of hook
priority (int): the priority of the hook (higher values run first)
function (callable): the actual function to call
names (str list): name of the transitions or states to which the hook
relates. The special value '*' means 'applies to all transitions/
states'.
Hooks are sortable by descending priority and ascending function name.
Hook kinds are as follow:
- HOOK_BEFORE: run before the related transitions
- HOOK_AFTER: run after the related transitions
- HOOK_CHECK: run as part of pre-transition checks (return value matters)
- HOOK_ON_ENTER: run just after a transition entering a related state
- HOOK_ON_LEAVE: run just before a transition leaving from a related state
"""
def __init__(self, kind, function, *names, **kwargs):
assert kind in (
HOOK_BEFORE, HOOK_AFTER, HOOK_CHECK,
HOOK_ON_ENTER, HOOK_ON_LEAVE)
self.kind = kind
self.priority = kwargs.get('priority', 0)
self.function = function
self.names = names or ('*',)
def _match_transition(self, transition):
"""Checks whether a given Transition matches self.names."""
return (self.names == '*'
or transition in self.names
or transition.name in self.names)
def applies_to(self, transition, from_state=None):
"""Whether this hook applies to the given transition/state.
Args:
transition (Transition): the transition to check
from_state (State or None): the state to check. If absent, the check
is 'might this hook apply to the related transition, given a
valid source state'.
"""
if '*' in self.names:
return True
elif self.kind in (HOOK_BEFORE, HOOK_AFTER, HOOK_CHECK):
return self._match_transition(transition)
elif self.kind == HOOK_ON_ENTER:
return self._match_state(transition.target)
elif from_state is None:
# Testing whether the hook may apply to at least one source of the
# transition
return any(self._match_state(src) for src in transition.source)
else:
return self._match_state(from_state)
def __call__(self, *args, **kwargs):
return self.function(*args, **kwargs)
def __eq__(self, other):
"""Equality is based on priority, function and kind."""
if not isinstance(other, Hook):
return NotImplemented
return (
self.priority == other.priority
and self.function == other.function
and self.kind == other.kind
and self.names == other.names
)
def __ne__(self, other):
if not isinstance(other, Hook):
return NotImplemented
return not (self == other)
def __lt__(self, other):
"""Compare hooks of the same kind."""
if not isinstance(other, Hook):
return NotImplemented
return (
(other.priority, self.function.__name__)
< (self.priority, other.function.__name__))
def __gt__(self, other):
"""Compare hooks of the same kind."""
if not isinstance(other, Hook):
return NotImplemented
return (
(other.priority, self.function.__name__)
> (self.priority, other.function.__name__))
def __repr__(self):
return '<%s: %s %r>' % (
self.__class__.__name__, self.kind, self.function)
|
rbarrois/xworkflows | src/xworkflows/base.py | Hook._match_transition | python | def _match_transition(self, transition):
return (self.names == '*'
or transition in self.names
or transition.name in self.names) | Checks whether a given Transition matches self.names. | train | https://github.com/rbarrois/xworkflows/blob/4a94b04ba83cb43f61d4b0f7db6964a667c86b5b/src/xworkflows/base.py#L262-L266 | null | class Hook(object):
"""A hook to run when a transition occurs.
Attributes:
kind (str): the kind of hook
priority (int): the priority of the hook (higher values run first)
function (callable): the actual function to call
names (str list): name of the transitions or states to which the hook
relates. The special value '*' means 'applies to all transitions/
states'.
Hooks are sortable by descending priority and ascending function name.
Hook kinds are as follow:
- HOOK_BEFORE: run before the related transitions
- HOOK_AFTER: run after the related transitions
- HOOK_CHECK: run as part of pre-transition checks (return value matters)
- HOOK_ON_ENTER: run just after a transition entering a related state
- HOOK_ON_LEAVE: run just before a transition leaving from a related state
"""
def __init__(self, kind, function, *names, **kwargs):
assert kind in (
HOOK_BEFORE, HOOK_AFTER, HOOK_CHECK,
HOOK_ON_ENTER, HOOK_ON_LEAVE)
self.kind = kind
self.priority = kwargs.get('priority', 0)
self.function = function
self.names = names or ('*',)
def _match_state(self, state):
"""Checks whether a given State matches self.names."""
return (self.names == '*'
or state in self.names
or state.name in self.names)
def applies_to(self, transition, from_state=None):
"""Whether this hook applies to the given transition/state.
Args:
transition (Transition): the transition to check
from_state (State or None): the state to check. If absent, the check
is 'might this hook apply to the related transition, given a
valid source state'.
"""
if '*' in self.names:
return True
elif self.kind in (HOOK_BEFORE, HOOK_AFTER, HOOK_CHECK):
return self._match_transition(transition)
elif self.kind == HOOK_ON_ENTER:
return self._match_state(transition.target)
elif from_state is None:
# Testing whether the hook may apply to at least one source of the
# transition
return any(self._match_state(src) for src in transition.source)
else:
return self._match_state(from_state)
def __call__(self, *args, **kwargs):
return self.function(*args, **kwargs)
def __eq__(self, other):
"""Equality is based on priority, function and kind."""
if not isinstance(other, Hook):
return NotImplemented
return (
self.priority == other.priority
and self.function == other.function
and self.kind == other.kind
and self.names == other.names
)
def __ne__(self, other):
if not isinstance(other, Hook):
return NotImplemented
return not (self == other)
def __lt__(self, other):
"""Compare hooks of the same kind."""
if not isinstance(other, Hook):
return NotImplemented
return (
(other.priority, self.function.__name__)
< (self.priority, other.function.__name__))
def __gt__(self, other):
"""Compare hooks of the same kind."""
if not isinstance(other, Hook):
return NotImplemented
return (
(other.priority, self.function.__name__)
> (self.priority, other.function.__name__))
def __repr__(self):
return '<%s: %s %r>' % (
self.__class__.__name__, self.kind, self.function)
|
rbarrois/xworkflows | src/xworkflows/base.py | Hook.applies_to | python | def applies_to(self, transition, from_state=None):
if '*' in self.names:
return True
elif self.kind in (HOOK_BEFORE, HOOK_AFTER, HOOK_CHECK):
return self._match_transition(transition)
elif self.kind == HOOK_ON_ENTER:
return self._match_state(transition.target)
elif from_state is None:
# Testing whether the hook may apply to at least one source of the
# transition
return any(self._match_state(src) for src in transition.source)
else:
return self._match_state(from_state) | Whether this hook applies to the given transition/state.
Args:
transition (Transition): the transition to check
from_state (State or None): the state to check. If absent, the check
is 'might this hook apply to the related transition, given a
valid source state'. | train | https://github.com/rbarrois/xworkflows/blob/4a94b04ba83cb43f61d4b0f7db6964a667c86b5b/src/xworkflows/base.py#L268-L288 | [
"def _match_state(self, state):\n \"\"\"Checks whether a given State matches self.names.\"\"\"\n return (self.names == '*'\n or state in self.names\n or state.name in self.names)\n",
"def _match_transition(self, transition):\n \"\"\"Checks whether a given Transition matches self.nam... | class Hook(object):
"""A hook to run when a transition occurs.
Attributes:
kind (str): the kind of hook
priority (int): the priority of the hook (higher values run first)
function (callable): the actual function to call
names (str list): name of the transitions or states to which the hook
relates. The special value '*' means 'applies to all transitions/
states'.
Hooks are sortable by descending priority and ascending function name.
Hook kinds are as follow:
- HOOK_BEFORE: run before the related transitions
- HOOK_AFTER: run after the related transitions
- HOOK_CHECK: run as part of pre-transition checks (return value matters)
- HOOK_ON_ENTER: run just after a transition entering a related state
- HOOK_ON_LEAVE: run just before a transition leaving from a related state
"""
def __init__(self, kind, function, *names, **kwargs):
assert kind in (
HOOK_BEFORE, HOOK_AFTER, HOOK_CHECK,
HOOK_ON_ENTER, HOOK_ON_LEAVE)
self.kind = kind
self.priority = kwargs.get('priority', 0)
self.function = function
self.names = names or ('*',)
def _match_state(self, state):
"""Checks whether a given State matches self.names."""
return (self.names == '*'
or state in self.names
or state.name in self.names)
def _match_transition(self, transition):
"""Checks whether a given Transition matches self.names."""
return (self.names == '*'
or transition in self.names
or transition.name in self.names)
def __call__(self, *args, **kwargs):
return self.function(*args, **kwargs)
def __eq__(self, other):
"""Equality is based on priority, function and kind."""
if not isinstance(other, Hook):
return NotImplemented
return (
self.priority == other.priority
and self.function == other.function
and self.kind == other.kind
and self.names == other.names
)
def __ne__(self, other):
if not isinstance(other, Hook):
return NotImplemented
return not (self == other)
def __lt__(self, other):
"""Compare hooks of the same kind."""
if not isinstance(other, Hook):
return NotImplemented
return (
(other.priority, self.function.__name__)
< (self.priority, other.function.__name__))
def __gt__(self, other):
"""Compare hooks of the same kind."""
if not isinstance(other, Hook):
return NotImplemented
return (
(other.priority, self.function.__name__)
> (self.priority, other.function.__name__))
def __repr__(self):
return '<%s: %s %r>' % (
self.__class__.__name__, self.kind, self.function)
|
rbarrois/xworkflows | src/xworkflows/base.py | ImplementationWrapper._pre_transition_checks | python | def _pre_transition_checks(self):
current_state = getattr(self.instance, self.field_name)
if current_state not in self.transition.source:
raise InvalidTransitionError(
"Transition '%s' isn't available from state '%s'." %
(self.transition.name, current_state.name))
for check in self._filter_hooks(HOOK_CHECK):
if not check(self.instance):
raise ForbiddenTransition(
"Transition '%s' was forbidden by "
"custom pre-transition check." % self.transition.name) | Run the pre-transition checks. | train | https://github.com/rbarrois/xworkflows/blob/4a94b04ba83cb43f61d4b0f7db6964a667c86b5b/src/xworkflows/base.py#L363-L375 | [
"def _filter_hooks(self, *hook_kinds):\n \"\"\"Filter a list of hooks, keeping only applicable ones.\"\"\"\n hooks = sum((self.hooks.get(kind, []) for kind in hook_kinds), [])\n return sorted(hook for hook in hooks\n if hook.applies_to(self.transition, self.current_state))\n"
] | class ImplementationWrapper(object):
"""Wraps a transition implementation.
Emulates a function behaviour, but provides a few extra features.
Attributes:
instance (WorkflowEnabled): the instance to update
.
field_name (str): the name of the field of the instance to update.
transition (Transition): the transition to perform
workflow (Workflow): the workflow to which this is related.
hooks (Hook list): optional hooks to call during the transition
implementation (callable): the code to invoke between 'before' and the
state update.
"""
def __init__(self, instance, field_name, transition, workflow,
implementation, hooks=None):
self.instance = instance
self.field_name = field_name
self.transition = transition
self.workflow = workflow
self.hooks = hooks or {}
self.implementation = implementation
self.__doc__ = implementation.__doc__
@property
def current_state(self):
return getattr(self.instance, self.field_name)
def _filter_hooks(self, *hook_kinds):
"""Filter a list of hooks, keeping only applicable ones."""
hooks = sum((self.hooks.get(kind, []) for kind in hook_kinds), [])
return sorted(hook for hook in hooks
if hook.applies_to(self.transition, self.current_state))
def _pre_transition(self, *args, **kwargs):
for hook in self._filter_hooks(HOOK_BEFORE, HOOK_ON_LEAVE):
hook(self.instance, *args, **kwargs)
def _during_transition(self, *args, **kwargs):
return self.implementation(self.instance, *args, **kwargs)
def _log_transition(self, from_state, *args, **kwargs):
self.workflow.log_transition(
self.transition, from_state, self.instance,
*args, **kwargs)
def _post_transition(self, result, *args, **kwargs):
"""Performs post-transition actions."""
for hook in self._filter_hooks(HOOK_AFTER, HOOK_ON_ENTER):
hook(self.instance, result, *args, **kwargs)
def __call__(self, *args, **kwargs):
"""Run the transition, with all checks."""
self._pre_transition_checks()
# Call hooks.
self._pre_transition(*args, **kwargs)
result = self._during_transition(*args, **kwargs)
from_state = getattr(self.instance, self.field_name)
setattr(self.instance, self.field_name, self.transition.target)
# Call hooks.
self._log_transition(from_state, *args, **kwargs)
self._post_transition(result, *args, **kwargs)
return result
def is_available(self):
"""Check whether this transition is available on the current object.
Returns:
bool
"""
try:
self._pre_transition_checks()
except (InvalidTransitionError, ForbiddenTransition):
return False
return True
def __repr__(self):
return "<%s for %r on %r: %r>" % (
self.__class__.__name__,
self.transition.name, self.field_name, self.implementation)
|
rbarrois/xworkflows | src/xworkflows/base.py | ImplementationWrapper._filter_hooks | python | def _filter_hooks(self, *hook_kinds):
hooks = sum((self.hooks.get(kind, []) for kind in hook_kinds), [])
return sorted(hook for hook in hooks
if hook.applies_to(self.transition, self.current_state)) | Filter a list of hooks, keeping only applicable ones. | train | https://github.com/rbarrois/xworkflows/blob/4a94b04ba83cb43f61d4b0f7db6964a667c86b5b/src/xworkflows/base.py#L377-L381 | null | class ImplementationWrapper(object):
"""Wraps a transition implementation.
Emulates a function behaviour, but provides a few extra features.
Attributes:
instance (WorkflowEnabled): the instance to update
.
field_name (str): the name of the field of the instance to update.
transition (Transition): the transition to perform
workflow (Workflow): the workflow to which this is related.
hooks (Hook list): optional hooks to call during the transition
implementation (callable): the code to invoke between 'before' and the
state update.
"""
def __init__(self, instance, field_name, transition, workflow,
implementation, hooks=None):
self.instance = instance
self.field_name = field_name
self.transition = transition
self.workflow = workflow
self.hooks = hooks or {}
self.implementation = implementation
self.__doc__ = implementation.__doc__
@property
def current_state(self):
return getattr(self.instance, self.field_name)
def _pre_transition_checks(self):
"""Run the pre-transition checks."""
current_state = getattr(self.instance, self.field_name)
if current_state not in self.transition.source:
raise InvalidTransitionError(
"Transition '%s' isn't available from state '%s'." %
(self.transition.name, current_state.name))
for check in self._filter_hooks(HOOK_CHECK):
if not check(self.instance):
raise ForbiddenTransition(
"Transition '%s' was forbidden by "
"custom pre-transition check." % self.transition.name)
def _pre_transition(self, *args, **kwargs):
for hook in self._filter_hooks(HOOK_BEFORE, HOOK_ON_LEAVE):
hook(self.instance, *args, **kwargs)
def _during_transition(self, *args, **kwargs):
return self.implementation(self.instance, *args, **kwargs)
def _log_transition(self, from_state, *args, **kwargs):
self.workflow.log_transition(
self.transition, from_state, self.instance,
*args, **kwargs)
def _post_transition(self, result, *args, **kwargs):
"""Performs post-transition actions."""
for hook in self._filter_hooks(HOOK_AFTER, HOOK_ON_ENTER):
hook(self.instance, result, *args, **kwargs)
def __call__(self, *args, **kwargs):
"""Run the transition, with all checks."""
self._pre_transition_checks()
# Call hooks.
self._pre_transition(*args, **kwargs)
result = self._during_transition(*args, **kwargs)
from_state = getattr(self.instance, self.field_name)
setattr(self.instance, self.field_name, self.transition.target)
# Call hooks.
self._log_transition(from_state, *args, **kwargs)
self._post_transition(result, *args, **kwargs)
return result
def is_available(self):
"""Check whether this transition is available on the current object.
Returns:
bool
"""
try:
self._pre_transition_checks()
except (InvalidTransitionError, ForbiddenTransition):
return False
return True
def __repr__(self):
return "<%s for %r on %r: %r>" % (
self.__class__.__name__,
self.transition.name, self.field_name, self.implementation)
|
rbarrois/xworkflows | src/xworkflows/base.py | ImplementationWrapper._post_transition | python | def _post_transition(self, result, *args, **kwargs):
for hook in self._filter_hooks(HOOK_AFTER, HOOK_ON_ENTER):
hook(self.instance, result, *args, **kwargs) | Performs post-transition actions. | train | https://github.com/rbarrois/xworkflows/blob/4a94b04ba83cb43f61d4b0f7db6964a667c86b5b/src/xworkflows/base.py#L395-L398 | [
"def _filter_hooks(self, *hook_kinds):\n \"\"\"Filter a list of hooks, keeping only applicable ones.\"\"\"\n hooks = sum((self.hooks.get(kind, []) for kind in hook_kinds), [])\n return sorted(hook for hook in hooks\n if hook.applies_to(self.transition, self.current_state))\n"
] | class ImplementationWrapper(object):
"""Wraps a transition implementation.
Emulates a function behaviour, but provides a few extra features.
Attributes:
instance (WorkflowEnabled): the instance to update
.
field_name (str): the name of the field of the instance to update.
transition (Transition): the transition to perform
workflow (Workflow): the workflow to which this is related.
hooks (Hook list): optional hooks to call during the transition
implementation (callable): the code to invoke between 'before' and the
state update.
"""
def __init__(self, instance, field_name, transition, workflow,
implementation, hooks=None):
self.instance = instance
self.field_name = field_name
self.transition = transition
self.workflow = workflow
self.hooks = hooks or {}
self.implementation = implementation
self.__doc__ = implementation.__doc__
@property
def current_state(self):
return getattr(self.instance, self.field_name)
def _pre_transition_checks(self):
"""Run the pre-transition checks."""
current_state = getattr(self.instance, self.field_name)
if current_state not in self.transition.source:
raise InvalidTransitionError(
"Transition '%s' isn't available from state '%s'." %
(self.transition.name, current_state.name))
for check in self._filter_hooks(HOOK_CHECK):
if not check(self.instance):
raise ForbiddenTransition(
"Transition '%s' was forbidden by "
"custom pre-transition check." % self.transition.name)
def _filter_hooks(self, *hook_kinds):
"""Filter a list of hooks, keeping only applicable ones."""
hooks = sum((self.hooks.get(kind, []) for kind in hook_kinds), [])
return sorted(hook for hook in hooks
if hook.applies_to(self.transition, self.current_state))
def _pre_transition(self, *args, **kwargs):
for hook in self._filter_hooks(HOOK_BEFORE, HOOK_ON_LEAVE):
hook(self.instance, *args, **kwargs)
def _during_transition(self, *args, **kwargs):
return self.implementation(self.instance, *args, **kwargs)
def _log_transition(self, from_state, *args, **kwargs):
self.workflow.log_transition(
self.transition, from_state, self.instance,
*args, **kwargs)
def __call__(self, *args, **kwargs):
"""Run the transition, with all checks."""
self._pre_transition_checks()
# Call hooks.
self._pre_transition(*args, **kwargs)
result = self._during_transition(*args, **kwargs)
from_state = getattr(self.instance, self.field_name)
setattr(self.instance, self.field_name, self.transition.target)
# Call hooks.
self._log_transition(from_state, *args, **kwargs)
self._post_transition(result, *args, **kwargs)
return result
def is_available(self):
"""Check whether this transition is available on the current object.
Returns:
bool
"""
try:
self._pre_transition_checks()
except (InvalidTransitionError, ForbiddenTransition):
return False
return True
def __repr__(self):
return "<%s for %r on %r: %r>" % (
self.__class__.__name__,
self.transition.name, self.field_name, self.implementation)
|
rbarrois/xworkflows | src/xworkflows/base.py | ImplementationList.load_parent_implems | python | def load_parent_implems(self, parent_implems):
for trname, attr, implem in parent_implems.get_custom_implementations():
self.implementations[trname] = implem.copy()
self.transitions_at[trname] = attr
self.custom_implems.add(trname) | Import previously defined implementations.
Args:
parent_implems (ImplementationList): List of implementations defined
in a parent class. | train | https://github.com/rbarrois/xworkflows/blob/4a94b04ba83cb43f61d4b0f7db6964a667c86b5b/src/xworkflows/base.py#L664-L674 | null | class ImplementationList(object):
"""Stores all implementations.
Attributes:
state_field (str): the name of the field holding the state of objects.
implementations (dict(str => ImplementationProperty)): maps a transition
name to the associated implementation.
workflow (Workflow): the related workflow
transitions_at (dict(str => str)): maps a transition name to the
name of the attribute holding the related implementation.
custom_implems (str set): list of transition names for which a custom
implementation has been defined.
"""
def __init__(self, state_field, workflow):
self.state_field = state_field
self.workflow = workflow
self.implementations = {}
self.transitions_at = {}
self.custom_implems = set()
def add_implem(self, transition, attribute, function, **kwargs):
"""Add an implementation.
Args:
transition (Transition): the transition for which the implementation
is added
attribute (str): the name of the attribute where the implementation
will be available
function (callable): the actual implementation function
**kwargs: extra arguments for the related ImplementationProperty.
"""
implem = ImplementationProperty(
field_name=self.state_field,
transition=transition,
workflow=self.workflow,
implementation=function,
**kwargs)
self.implementations[transition.name] = implem
self.transitions_at[transition.name] = attribute
return implem
def should_collect(self, value):
"""Decide whether a given value should be collected."""
return (
# decorated with @transition
isinstance(value, TransitionWrapper)
# Relates to a compatible transition
and value.trname in self.workflow.transitions
# Either not bound to a state field or bound to the current one
and (not value.field or value.field == self.state_field))
def collect(self, attrs):
"""Collect the implementations from a given attributes dict."""
for name, value in attrs.items():
if self.should_collect(value):
transition = self.workflow.transitions[value.trname]
if (
value.trname in self.implementations
and value.trname in self.custom_implems
and name != self.transitions_at[value.trname]):
# We already have an implementation registered.
other_implem_at = self.transitions_at[value.trname]
raise ValueError(
"Error for attribute %s: it defines implementation "
"%s for transition %s, which is already implemented "
"at %s." % (name, value, transition, other_implem_at))
implem = self.add_implem(transition, name, value.func)
self.custom_implems.add(transition.name)
if value.check:
implem.add_hook(Hook(HOOK_CHECK, value.check))
if value.before:
implem.add_hook(Hook(HOOK_BEFORE, value.before))
if value.after:
implem.add_hook(Hook(HOOK_AFTER, value.after))
def get_custom_implementations(self):
"""Retrieve a list of cutom implementations.
Yields:
(str, str, ImplementationProperty) tuples: The name of the attribute
an implementation lives at, the name of the related transition,
and the related implementation.
"""
for trname in self.custom_implems:
attr = self.transitions_at[trname]
implem = self.implementations[trname]
yield (trname, attr, implem)
def add_missing_implementations(self):
for transition in self.workflow.transitions:
if transition.name not in self.implementations:
self.add_implem(transition, transition.name, noop)
def register_hooks(self, cls):
for field, value in utils.iterclass(cls):
if is_callable(value) and hasattr(value, 'xworkflows_hook'):
self.register_function_hooks(value)
def register_function_hooks(self, func):
"""Looks at an object method and registers it for relevent transitions."""
for hook_kind, hooks in func.xworkflows_hook.items():
for field_name, hook in hooks:
if field_name and field_name != self.state_field:
continue
for transition in self.workflow.transitions:
if hook.applies_to(transition):
implem = self.implementations[transition.name]
implem.add_hook(hook)
def _may_override(self, implem, other):
"""Checks whether an ImplementationProperty may override an attribute."""
if isinstance(other, ImplementationProperty):
# Overriding another custom implementation for the same transition
# and field
return (other.transition == implem.transition and other.field_name == self.state_field)
elif isinstance(other, TransitionWrapper):
# Overriding the definition that led to adding the current
# ImplementationProperty.
return (
other.trname == implem.transition.name
and (not other.field or other.field == self.state_field)
and other.func == implem.implementation)
return False
def fill_attrs(self, attrs):
"""Update the 'attrs' dict with generated ImplementationProperty."""
for trname, attrname in self.transitions_at.items():
implem = self.implementations[trname]
if attrname in attrs:
conflicting = attrs[attrname]
if not self._may_override(implem, conflicting):
raise ValueError(
"Can't override transition implementation %s=%r with %r" %
(attrname, conflicting, implem))
attrs[attrname] = implem
return attrs
def transform(self, attrs):
"""Perform all actions on a given attribute dict."""
self.collect(attrs)
self.add_missing_implementations()
self.fill_attrs(attrs)
|
rbarrois/xworkflows | src/xworkflows/base.py | ImplementationList.add_implem | python | def add_implem(self, transition, attribute, function, **kwargs):
implem = ImplementationProperty(
field_name=self.state_field,
transition=transition,
workflow=self.workflow,
implementation=function,
**kwargs)
self.implementations[transition.name] = implem
self.transitions_at[transition.name] = attribute
return implem | Add an implementation.
Args:
transition (Transition): the transition for which the implementation
is added
attribute (str): the name of the attribute where the implementation
will be available
function (callable): the actual implementation function
**kwargs: extra arguments for the related ImplementationProperty. | train | https://github.com/rbarrois/xworkflows/blob/4a94b04ba83cb43f61d4b0f7db6964a667c86b5b/src/xworkflows/base.py#L676-L695 | null | class ImplementationList(object):
"""Stores all implementations.
Attributes:
state_field (str): the name of the field holding the state of objects.
implementations (dict(str => ImplementationProperty)): maps a transition
name to the associated implementation.
workflow (Workflow): the related workflow
transitions_at (dict(str => str)): maps a transition name to the
name of the attribute holding the related implementation.
custom_implems (str set): list of transition names for which a custom
implementation has been defined.
"""
def __init__(self, state_field, workflow):
self.state_field = state_field
self.workflow = workflow
self.implementations = {}
self.transitions_at = {}
self.custom_implems = set()
def load_parent_implems(self, parent_implems):
"""Import previously defined implementations.
Args:
parent_implems (ImplementationList): List of implementations defined
in a parent class.
"""
for trname, attr, implem in parent_implems.get_custom_implementations():
self.implementations[trname] = implem.copy()
self.transitions_at[trname] = attr
self.custom_implems.add(trname)
def should_collect(self, value):
"""Decide whether a given value should be collected."""
return (
# decorated with @transition
isinstance(value, TransitionWrapper)
# Relates to a compatible transition
and value.trname in self.workflow.transitions
# Either not bound to a state field or bound to the current one
and (not value.field or value.field == self.state_field))
def collect(self, attrs):
"""Collect the implementations from a given attributes dict."""
for name, value in attrs.items():
if self.should_collect(value):
transition = self.workflow.transitions[value.trname]
if (
value.trname in self.implementations
and value.trname in self.custom_implems
and name != self.transitions_at[value.trname]):
# We already have an implementation registered.
other_implem_at = self.transitions_at[value.trname]
raise ValueError(
"Error for attribute %s: it defines implementation "
"%s for transition %s, which is already implemented "
"at %s." % (name, value, transition, other_implem_at))
implem = self.add_implem(transition, name, value.func)
self.custom_implems.add(transition.name)
if value.check:
implem.add_hook(Hook(HOOK_CHECK, value.check))
if value.before:
implem.add_hook(Hook(HOOK_BEFORE, value.before))
if value.after:
implem.add_hook(Hook(HOOK_AFTER, value.after))
def get_custom_implementations(self):
"""Retrieve a list of cutom implementations.
Yields:
(str, str, ImplementationProperty) tuples: The name of the attribute
an implementation lives at, the name of the related transition,
and the related implementation.
"""
for trname in self.custom_implems:
attr = self.transitions_at[trname]
implem = self.implementations[trname]
yield (trname, attr, implem)
def add_missing_implementations(self):
for transition in self.workflow.transitions:
if transition.name not in self.implementations:
self.add_implem(transition, transition.name, noop)
def register_hooks(self, cls):
for field, value in utils.iterclass(cls):
if is_callable(value) and hasattr(value, 'xworkflows_hook'):
self.register_function_hooks(value)
def register_function_hooks(self, func):
"""Looks at an object method and registers it for relevent transitions."""
for hook_kind, hooks in func.xworkflows_hook.items():
for field_name, hook in hooks:
if field_name and field_name != self.state_field:
continue
for transition in self.workflow.transitions:
if hook.applies_to(transition):
implem = self.implementations[transition.name]
implem.add_hook(hook)
def _may_override(self, implem, other):
"""Checks whether an ImplementationProperty may override an attribute."""
if isinstance(other, ImplementationProperty):
# Overriding another custom implementation for the same transition
# and field
return (other.transition == implem.transition and other.field_name == self.state_field)
elif isinstance(other, TransitionWrapper):
# Overriding the definition that led to adding the current
# ImplementationProperty.
return (
other.trname == implem.transition.name
and (not other.field or other.field == self.state_field)
and other.func == implem.implementation)
return False
def fill_attrs(self, attrs):
"""Update the 'attrs' dict with generated ImplementationProperty."""
for trname, attrname in self.transitions_at.items():
implem = self.implementations[trname]
if attrname in attrs:
conflicting = attrs[attrname]
if not self._may_override(implem, conflicting):
raise ValueError(
"Can't override transition implementation %s=%r with %r" %
(attrname, conflicting, implem))
attrs[attrname] = implem
return attrs
def transform(self, attrs):
"""Perform all actions on a given attribute dict."""
self.collect(attrs)
self.add_missing_implementations()
self.fill_attrs(attrs)
|
rbarrois/xworkflows | src/xworkflows/base.py | ImplementationList.should_collect | python | def should_collect(self, value):
return (
# decorated with @transition
isinstance(value, TransitionWrapper)
# Relates to a compatible transition
and value.trname in self.workflow.transitions
# Either not bound to a state field or bound to the current one
and (not value.field or value.field == self.state_field)) | Decide whether a given value should be collected. | train | https://github.com/rbarrois/xworkflows/blob/4a94b04ba83cb43f61d4b0f7db6964a667c86b5b/src/xworkflows/base.py#L697-L705 | null | class ImplementationList(object):
"""Stores all implementations.
Attributes:
state_field (str): the name of the field holding the state of objects.
implementations (dict(str => ImplementationProperty)): maps a transition
name to the associated implementation.
workflow (Workflow): the related workflow
transitions_at (dict(str => str)): maps a transition name to the
name of the attribute holding the related implementation.
custom_implems (str set): list of transition names for which a custom
implementation has been defined.
"""
def __init__(self, state_field, workflow):
self.state_field = state_field
self.workflow = workflow
self.implementations = {}
self.transitions_at = {}
self.custom_implems = set()
def load_parent_implems(self, parent_implems):
"""Import previously defined implementations.
Args:
parent_implems (ImplementationList): List of implementations defined
in a parent class.
"""
for trname, attr, implem in parent_implems.get_custom_implementations():
self.implementations[trname] = implem.copy()
self.transitions_at[trname] = attr
self.custom_implems.add(trname)
def add_implem(self, transition, attribute, function, **kwargs):
"""Add an implementation.
Args:
transition (Transition): the transition for which the implementation
is added
attribute (str): the name of the attribute where the implementation
will be available
function (callable): the actual implementation function
**kwargs: extra arguments for the related ImplementationProperty.
"""
implem = ImplementationProperty(
field_name=self.state_field,
transition=transition,
workflow=self.workflow,
implementation=function,
**kwargs)
self.implementations[transition.name] = implem
self.transitions_at[transition.name] = attribute
return implem
def collect(self, attrs):
"""Collect the implementations from a given attributes dict."""
for name, value in attrs.items():
if self.should_collect(value):
transition = self.workflow.transitions[value.trname]
if (
value.trname in self.implementations
and value.trname in self.custom_implems
and name != self.transitions_at[value.trname]):
# We already have an implementation registered.
other_implem_at = self.transitions_at[value.trname]
raise ValueError(
"Error for attribute %s: it defines implementation "
"%s for transition %s, which is already implemented "
"at %s." % (name, value, transition, other_implem_at))
implem = self.add_implem(transition, name, value.func)
self.custom_implems.add(transition.name)
if value.check:
implem.add_hook(Hook(HOOK_CHECK, value.check))
if value.before:
implem.add_hook(Hook(HOOK_BEFORE, value.before))
if value.after:
implem.add_hook(Hook(HOOK_AFTER, value.after))
def get_custom_implementations(self):
"""Retrieve a list of cutom implementations.
Yields:
(str, str, ImplementationProperty) tuples: The name of the attribute
an implementation lives at, the name of the related transition,
and the related implementation.
"""
for trname in self.custom_implems:
attr = self.transitions_at[trname]
implem = self.implementations[trname]
yield (trname, attr, implem)
def add_missing_implementations(self):
for transition in self.workflow.transitions:
if transition.name not in self.implementations:
self.add_implem(transition, transition.name, noop)
def register_hooks(self, cls):
for field, value in utils.iterclass(cls):
if is_callable(value) and hasattr(value, 'xworkflows_hook'):
self.register_function_hooks(value)
def register_function_hooks(self, func):
"""Looks at an object method and registers it for relevent transitions."""
for hook_kind, hooks in func.xworkflows_hook.items():
for field_name, hook in hooks:
if field_name and field_name != self.state_field:
continue
for transition in self.workflow.transitions:
if hook.applies_to(transition):
implem = self.implementations[transition.name]
implem.add_hook(hook)
def _may_override(self, implem, other):
"""Checks whether an ImplementationProperty may override an attribute."""
if isinstance(other, ImplementationProperty):
# Overriding another custom implementation for the same transition
# and field
return (other.transition == implem.transition and other.field_name == self.state_field)
elif isinstance(other, TransitionWrapper):
# Overriding the definition that led to adding the current
# ImplementationProperty.
return (
other.trname == implem.transition.name
and (not other.field or other.field == self.state_field)
and other.func == implem.implementation)
return False
def fill_attrs(self, attrs):
"""Update the 'attrs' dict with generated ImplementationProperty."""
for trname, attrname in self.transitions_at.items():
implem = self.implementations[trname]
if attrname in attrs:
conflicting = attrs[attrname]
if not self._may_override(implem, conflicting):
raise ValueError(
"Can't override transition implementation %s=%r with %r" %
(attrname, conflicting, implem))
attrs[attrname] = implem
return attrs
def transform(self, attrs):
"""Perform all actions on a given attribute dict."""
self.collect(attrs)
self.add_missing_implementations()
self.fill_attrs(attrs)
|
rbarrois/xworkflows | src/xworkflows/base.py | ImplementationList.collect | python | def collect(self, attrs):
for name, value in attrs.items():
if self.should_collect(value):
transition = self.workflow.transitions[value.trname]
if (
value.trname in self.implementations
and value.trname in self.custom_implems
and name != self.transitions_at[value.trname]):
# We already have an implementation registered.
other_implem_at = self.transitions_at[value.trname]
raise ValueError(
"Error for attribute %s: it defines implementation "
"%s for transition %s, which is already implemented "
"at %s." % (name, value, transition, other_implem_at))
implem = self.add_implem(transition, name, value.func)
self.custom_implems.add(transition.name)
if value.check:
implem.add_hook(Hook(HOOK_CHECK, value.check))
if value.before:
implem.add_hook(Hook(HOOK_BEFORE, value.before))
if value.after:
implem.add_hook(Hook(HOOK_AFTER, value.after)) | Collect the implementations from a given attributes dict. | train | https://github.com/rbarrois/xworkflows/blob/4a94b04ba83cb43f61d4b0f7db6964a667c86b5b/src/xworkflows/base.py#L707-L732 | [
"def should_collect(self, value):\n \"\"\"Decide whether a given value should be collected.\"\"\"\n return (\n # decorated with @transition\n isinstance(value, TransitionWrapper)\n # Relates to a compatible transition\n and value.trname in self.workflow.transitions\n # Eithe... | class ImplementationList(object):
"""Stores all implementations.
Attributes:
state_field (str): the name of the field holding the state of objects.
implementations (dict(str => ImplementationProperty)): maps a transition
name to the associated implementation.
workflow (Workflow): the related workflow
transitions_at (dict(str => str)): maps a transition name to the
name of the attribute holding the related implementation.
custom_implems (str set): list of transition names for which a custom
implementation has been defined.
"""
def __init__(self, state_field, workflow):
self.state_field = state_field
self.workflow = workflow
self.implementations = {}
self.transitions_at = {}
self.custom_implems = set()
def load_parent_implems(self, parent_implems):
"""Import previously defined implementations.
Args:
parent_implems (ImplementationList): List of implementations defined
in a parent class.
"""
for trname, attr, implem in parent_implems.get_custom_implementations():
self.implementations[trname] = implem.copy()
self.transitions_at[trname] = attr
self.custom_implems.add(trname)
def add_implem(self, transition, attribute, function, **kwargs):
"""Add an implementation.
Args:
transition (Transition): the transition for which the implementation
is added
attribute (str): the name of the attribute where the implementation
will be available
function (callable): the actual implementation function
**kwargs: extra arguments for the related ImplementationProperty.
"""
implem = ImplementationProperty(
field_name=self.state_field,
transition=transition,
workflow=self.workflow,
implementation=function,
**kwargs)
self.implementations[transition.name] = implem
self.transitions_at[transition.name] = attribute
return implem
def should_collect(self, value):
"""Decide whether a given value should be collected."""
return (
# decorated with @transition
isinstance(value, TransitionWrapper)
# Relates to a compatible transition
and value.trname in self.workflow.transitions
# Either not bound to a state field or bound to the current one
and (not value.field or value.field == self.state_field))
def get_custom_implementations(self):
"""Retrieve a list of cutom implementations.
Yields:
(str, str, ImplementationProperty) tuples: The name of the attribute
an implementation lives at, the name of the related transition,
and the related implementation.
"""
for trname in self.custom_implems:
attr = self.transitions_at[trname]
implem = self.implementations[trname]
yield (trname, attr, implem)
def add_missing_implementations(self):
for transition in self.workflow.transitions:
if transition.name not in self.implementations:
self.add_implem(transition, transition.name, noop)
def register_hooks(self, cls):
for field, value in utils.iterclass(cls):
if is_callable(value) and hasattr(value, 'xworkflows_hook'):
self.register_function_hooks(value)
def register_function_hooks(self, func):
"""Looks at an object method and registers it for relevent transitions."""
for hook_kind, hooks in func.xworkflows_hook.items():
for field_name, hook in hooks:
if field_name and field_name != self.state_field:
continue
for transition in self.workflow.transitions:
if hook.applies_to(transition):
implem = self.implementations[transition.name]
implem.add_hook(hook)
def _may_override(self, implem, other):
"""Checks whether an ImplementationProperty may override an attribute."""
if isinstance(other, ImplementationProperty):
# Overriding another custom implementation for the same transition
# and field
return (other.transition == implem.transition and other.field_name == self.state_field)
elif isinstance(other, TransitionWrapper):
# Overriding the definition that led to adding the current
# ImplementationProperty.
return (
other.trname == implem.transition.name
and (not other.field or other.field == self.state_field)
and other.func == implem.implementation)
return False
def fill_attrs(self, attrs):
"""Update the 'attrs' dict with generated ImplementationProperty."""
for trname, attrname in self.transitions_at.items():
implem = self.implementations[trname]
if attrname in attrs:
conflicting = attrs[attrname]
if not self._may_override(implem, conflicting):
raise ValueError(
"Can't override transition implementation %s=%r with %r" %
(attrname, conflicting, implem))
attrs[attrname] = implem
return attrs
def transform(self, attrs):
"""Perform all actions on a given attribute dict."""
self.collect(attrs)
self.add_missing_implementations()
self.fill_attrs(attrs)
|
rbarrois/xworkflows | src/xworkflows/base.py | ImplementationList.get_custom_implementations | python | def get_custom_implementations(self):
for trname in self.custom_implems:
attr = self.transitions_at[trname]
implem = self.implementations[trname]
yield (trname, attr, implem) | Retrieve a list of cutom implementations.
Yields:
(str, str, ImplementationProperty) tuples: The name of the attribute
an implementation lives at, the name of the related transition,
and the related implementation. | train | https://github.com/rbarrois/xworkflows/blob/4a94b04ba83cb43f61d4b0f7db6964a667c86b5b/src/xworkflows/base.py#L734-L745 | null | class ImplementationList(object):
"""Stores all implementations.
Attributes:
state_field (str): the name of the field holding the state of objects.
implementations (dict(str => ImplementationProperty)): maps a transition
name to the associated implementation.
workflow (Workflow): the related workflow
transitions_at (dict(str => str)): maps a transition name to the
name of the attribute holding the related implementation.
custom_implems (str set): list of transition names for which a custom
implementation has been defined.
"""
def __init__(self, state_field, workflow):
self.state_field = state_field
self.workflow = workflow
self.implementations = {}
self.transitions_at = {}
self.custom_implems = set()
def load_parent_implems(self, parent_implems):
"""Import previously defined implementations.
Args:
parent_implems (ImplementationList): List of implementations defined
in a parent class.
"""
for trname, attr, implem in parent_implems.get_custom_implementations():
self.implementations[trname] = implem.copy()
self.transitions_at[trname] = attr
self.custom_implems.add(trname)
def add_implem(self, transition, attribute, function, **kwargs):
"""Add an implementation.
Args:
transition (Transition): the transition for which the implementation
is added
attribute (str): the name of the attribute where the implementation
will be available
function (callable): the actual implementation function
**kwargs: extra arguments for the related ImplementationProperty.
"""
implem = ImplementationProperty(
field_name=self.state_field,
transition=transition,
workflow=self.workflow,
implementation=function,
**kwargs)
self.implementations[transition.name] = implem
self.transitions_at[transition.name] = attribute
return implem
def should_collect(self, value):
"""Decide whether a given value should be collected."""
return (
# decorated with @transition
isinstance(value, TransitionWrapper)
# Relates to a compatible transition
and value.trname in self.workflow.transitions
# Either not bound to a state field or bound to the current one
and (not value.field or value.field == self.state_field))
def collect(self, attrs):
"""Collect the implementations from a given attributes dict."""
for name, value in attrs.items():
if self.should_collect(value):
transition = self.workflow.transitions[value.trname]
if (
value.trname in self.implementations
and value.trname in self.custom_implems
and name != self.transitions_at[value.trname]):
# We already have an implementation registered.
other_implem_at = self.transitions_at[value.trname]
raise ValueError(
"Error for attribute %s: it defines implementation "
"%s for transition %s, which is already implemented "
"at %s." % (name, value, transition, other_implem_at))
implem = self.add_implem(transition, name, value.func)
self.custom_implems.add(transition.name)
if value.check:
implem.add_hook(Hook(HOOK_CHECK, value.check))
if value.before:
implem.add_hook(Hook(HOOK_BEFORE, value.before))
if value.after:
implem.add_hook(Hook(HOOK_AFTER, value.after))
def add_missing_implementations(self):
for transition in self.workflow.transitions:
if transition.name not in self.implementations:
self.add_implem(transition, transition.name, noop)
def register_hooks(self, cls):
for field, value in utils.iterclass(cls):
if is_callable(value) and hasattr(value, 'xworkflows_hook'):
self.register_function_hooks(value)
def register_function_hooks(self, func):
"""Looks at an object method and registers it for relevent transitions."""
for hook_kind, hooks in func.xworkflows_hook.items():
for field_name, hook in hooks:
if field_name and field_name != self.state_field:
continue
for transition in self.workflow.transitions:
if hook.applies_to(transition):
implem = self.implementations[transition.name]
implem.add_hook(hook)
def _may_override(self, implem, other):
"""Checks whether an ImplementationProperty may override an attribute."""
if isinstance(other, ImplementationProperty):
# Overriding another custom implementation for the same transition
# and field
return (other.transition == implem.transition and other.field_name == self.state_field)
elif isinstance(other, TransitionWrapper):
# Overriding the definition that led to adding the current
# ImplementationProperty.
return (
other.trname == implem.transition.name
and (not other.field or other.field == self.state_field)
and other.func == implem.implementation)
return False
def fill_attrs(self, attrs):
"""Update the 'attrs' dict with generated ImplementationProperty."""
for trname, attrname in self.transitions_at.items():
implem = self.implementations[trname]
if attrname in attrs:
conflicting = attrs[attrname]
if not self._may_override(implem, conflicting):
raise ValueError(
"Can't override transition implementation %s=%r with %r" %
(attrname, conflicting, implem))
attrs[attrname] = implem
return attrs
def transform(self, attrs):
"""Perform all actions on a given attribute dict."""
self.collect(attrs)
self.add_missing_implementations()
self.fill_attrs(attrs)
|
rbarrois/xworkflows | src/xworkflows/base.py | ImplementationList.register_function_hooks | python | def register_function_hooks(self, func):
for hook_kind, hooks in func.xworkflows_hook.items():
for field_name, hook in hooks:
if field_name and field_name != self.state_field:
continue
for transition in self.workflow.transitions:
if hook.applies_to(transition):
implem = self.implementations[transition.name]
implem.add_hook(hook) | Looks at an object method and registers it for relevent transitions. | train | https://github.com/rbarrois/xworkflows/blob/4a94b04ba83cb43f61d4b0f7db6964a667c86b5b/src/xworkflows/base.py#L757-L766 | null | class ImplementationList(object):
"""Stores all implementations.
Attributes:
state_field (str): the name of the field holding the state of objects.
implementations (dict(str => ImplementationProperty)): maps a transition
name to the associated implementation.
workflow (Workflow): the related workflow
transitions_at (dict(str => str)): maps a transition name to the
name of the attribute holding the related implementation.
custom_implems (str set): list of transition names for which a custom
implementation has been defined.
"""
def __init__(self, state_field, workflow):
self.state_field = state_field
self.workflow = workflow
self.implementations = {}
self.transitions_at = {}
self.custom_implems = set()
def load_parent_implems(self, parent_implems):
"""Import previously defined implementations.
Args:
parent_implems (ImplementationList): List of implementations defined
in a parent class.
"""
for trname, attr, implem in parent_implems.get_custom_implementations():
self.implementations[trname] = implem.copy()
self.transitions_at[trname] = attr
self.custom_implems.add(trname)
def add_implem(self, transition, attribute, function, **kwargs):
"""Add an implementation.
Args:
transition (Transition): the transition for which the implementation
is added
attribute (str): the name of the attribute where the implementation
will be available
function (callable): the actual implementation function
**kwargs: extra arguments for the related ImplementationProperty.
"""
implem = ImplementationProperty(
field_name=self.state_field,
transition=transition,
workflow=self.workflow,
implementation=function,
**kwargs)
self.implementations[transition.name] = implem
self.transitions_at[transition.name] = attribute
return implem
def should_collect(self, value):
"""Decide whether a given value should be collected."""
return (
# decorated with @transition
isinstance(value, TransitionWrapper)
# Relates to a compatible transition
and value.trname in self.workflow.transitions
# Either not bound to a state field or bound to the current one
and (not value.field or value.field == self.state_field))
def collect(self, attrs):
"""Collect the implementations from a given attributes dict."""
for name, value in attrs.items():
if self.should_collect(value):
transition = self.workflow.transitions[value.trname]
if (
value.trname in self.implementations
and value.trname in self.custom_implems
and name != self.transitions_at[value.trname]):
# We already have an implementation registered.
other_implem_at = self.transitions_at[value.trname]
raise ValueError(
"Error for attribute %s: it defines implementation "
"%s for transition %s, which is already implemented "
"at %s." % (name, value, transition, other_implem_at))
implem = self.add_implem(transition, name, value.func)
self.custom_implems.add(transition.name)
if value.check:
implem.add_hook(Hook(HOOK_CHECK, value.check))
if value.before:
implem.add_hook(Hook(HOOK_BEFORE, value.before))
if value.after:
implem.add_hook(Hook(HOOK_AFTER, value.after))
def get_custom_implementations(self):
"""Retrieve a list of cutom implementations.
Yields:
(str, str, ImplementationProperty) tuples: The name of the attribute
an implementation lives at, the name of the related transition,
and the related implementation.
"""
for trname in self.custom_implems:
attr = self.transitions_at[trname]
implem = self.implementations[trname]
yield (trname, attr, implem)
def add_missing_implementations(self):
for transition in self.workflow.transitions:
if transition.name not in self.implementations:
self.add_implem(transition, transition.name, noop)
def register_hooks(self, cls):
for field, value in utils.iterclass(cls):
if is_callable(value) and hasattr(value, 'xworkflows_hook'):
self.register_function_hooks(value)
def _may_override(self, implem, other):
"""Checks whether an ImplementationProperty may override an attribute."""
if isinstance(other, ImplementationProperty):
# Overriding another custom implementation for the same transition
# and field
return (other.transition == implem.transition and other.field_name == self.state_field)
elif isinstance(other, TransitionWrapper):
# Overriding the definition that led to adding the current
# ImplementationProperty.
return (
other.trname == implem.transition.name
and (not other.field or other.field == self.state_field)
and other.func == implem.implementation)
return False
def fill_attrs(self, attrs):
"""Update the 'attrs' dict with generated ImplementationProperty."""
for trname, attrname in self.transitions_at.items():
implem = self.implementations[trname]
if attrname in attrs:
conflicting = attrs[attrname]
if not self._may_override(implem, conflicting):
raise ValueError(
"Can't override transition implementation %s=%r with %r" %
(attrname, conflicting, implem))
attrs[attrname] = implem
return attrs
def transform(self, attrs):
"""Perform all actions on a given attribute dict."""
self.collect(attrs)
self.add_missing_implementations()
self.fill_attrs(attrs)
|
rbarrois/xworkflows | src/xworkflows/base.py | ImplementationList._may_override | python | def _may_override(self, implem, other):
if isinstance(other, ImplementationProperty):
# Overriding another custom implementation for the same transition
# and field
return (other.transition == implem.transition and other.field_name == self.state_field)
elif isinstance(other, TransitionWrapper):
# Overriding the definition that led to adding the current
# ImplementationProperty.
return (
other.trname == implem.transition.name
and (not other.field or other.field == self.state_field)
and other.func == implem.implementation)
return False | Checks whether an ImplementationProperty may override an attribute. | train | https://github.com/rbarrois/xworkflows/blob/4a94b04ba83cb43f61d4b0f7db6964a667c86b5b/src/xworkflows/base.py#L768-L783 | null | class ImplementationList(object):
"""Stores all implementations.
Attributes:
state_field (str): the name of the field holding the state of objects.
implementations (dict(str => ImplementationProperty)): maps a transition
name to the associated implementation.
workflow (Workflow): the related workflow
transitions_at (dict(str => str)): maps a transition name to the
name of the attribute holding the related implementation.
custom_implems (str set): list of transition names for which a custom
implementation has been defined.
"""
def __init__(self, state_field, workflow):
self.state_field = state_field
self.workflow = workflow
self.implementations = {}
self.transitions_at = {}
self.custom_implems = set()
def load_parent_implems(self, parent_implems):
"""Import previously defined implementations.
Args:
parent_implems (ImplementationList): List of implementations defined
in a parent class.
"""
for trname, attr, implem in parent_implems.get_custom_implementations():
self.implementations[trname] = implem.copy()
self.transitions_at[trname] = attr
self.custom_implems.add(trname)
def add_implem(self, transition, attribute, function, **kwargs):
"""Add an implementation.
Args:
transition (Transition): the transition for which the implementation
is added
attribute (str): the name of the attribute where the implementation
will be available
function (callable): the actual implementation function
**kwargs: extra arguments for the related ImplementationProperty.
"""
implem = ImplementationProperty(
field_name=self.state_field,
transition=transition,
workflow=self.workflow,
implementation=function,
**kwargs)
self.implementations[transition.name] = implem
self.transitions_at[transition.name] = attribute
return implem
def should_collect(self, value):
"""Decide whether a given value should be collected."""
return (
# decorated with @transition
isinstance(value, TransitionWrapper)
# Relates to a compatible transition
and value.trname in self.workflow.transitions
# Either not bound to a state field or bound to the current one
and (not value.field or value.field == self.state_field))
def collect(self, attrs):
"""Collect the implementations from a given attributes dict."""
for name, value in attrs.items():
if self.should_collect(value):
transition = self.workflow.transitions[value.trname]
if (
value.trname in self.implementations
and value.trname in self.custom_implems
and name != self.transitions_at[value.trname]):
# We already have an implementation registered.
other_implem_at = self.transitions_at[value.trname]
raise ValueError(
"Error for attribute %s: it defines implementation "
"%s for transition %s, which is already implemented "
"at %s." % (name, value, transition, other_implem_at))
implem = self.add_implem(transition, name, value.func)
self.custom_implems.add(transition.name)
if value.check:
implem.add_hook(Hook(HOOK_CHECK, value.check))
if value.before:
implem.add_hook(Hook(HOOK_BEFORE, value.before))
if value.after:
implem.add_hook(Hook(HOOK_AFTER, value.after))
def get_custom_implementations(self):
"""Retrieve a list of cutom implementations.
Yields:
(str, str, ImplementationProperty) tuples: The name of the attribute
an implementation lives at, the name of the related transition,
and the related implementation.
"""
for trname in self.custom_implems:
attr = self.transitions_at[trname]
implem = self.implementations[trname]
yield (trname, attr, implem)
def add_missing_implementations(self):
for transition in self.workflow.transitions:
if transition.name not in self.implementations:
self.add_implem(transition, transition.name, noop)
def register_hooks(self, cls):
for field, value in utils.iterclass(cls):
if is_callable(value) and hasattr(value, 'xworkflows_hook'):
self.register_function_hooks(value)
def register_function_hooks(self, func):
"""Looks at an object method and registers it for relevent transitions."""
for hook_kind, hooks in func.xworkflows_hook.items():
for field_name, hook in hooks:
if field_name and field_name != self.state_field:
continue
for transition in self.workflow.transitions:
if hook.applies_to(transition):
implem = self.implementations[transition.name]
implem.add_hook(hook)
def fill_attrs(self, attrs):
"""Update the 'attrs' dict with generated ImplementationProperty."""
for trname, attrname in self.transitions_at.items():
implem = self.implementations[trname]
if attrname in attrs:
conflicting = attrs[attrname]
if not self._may_override(implem, conflicting):
raise ValueError(
"Can't override transition implementation %s=%r with %r" %
(attrname, conflicting, implem))
attrs[attrname] = implem
return attrs
def transform(self, attrs):
"""Perform all actions on a given attribute dict."""
self.collect(attrs)
self.add_missing_implementations()
self.fill_attrs(attrs)
|
rbarrois/xworkflows | src/xworkflows/base.py | ImplementationList.fill_attrs | python | def fill_attrs(self, attrs):
for trname, attrname in self.transitions_at.items():
implem = self.implementations[trname]
if attrname in attrs:
conflicting = attrs[attrname]
if not self._may_override(implem, conflicting):
raise ValueError(
"Can't override transition implementation %s=%r with %r" %
(attrname, conflicting, implem))
attrs[attrname] = implem
return attrs | Update the 'attrs' dict with generated ImplementationProperty. | train | https://github.com/rbarrois/xworkflows/blob/4a94b04ba83cb43f61d4b0f7db6964a667c86b5b/src/xworkflows/base.py#L785-L799 | [
"def _may_override(self, implem, other):\n \"\"\"Checks whether an ImplementationProperty may override an attribute.\"\"\"\n if isinstance(other, ImplementationProperty):\n # Overriding another custom implementation for the same transition\n # and field\n return (other.transition == imple... | class ImplementationList(object):
"""Stores all implementations.
Attributes:
state_field (str): the name of the field holding the state of objects.
implementations (dict(str => ImplementationProperty)): maps a transition
name to the associated implementation.
workflow (Workflow): the related workflow
transitions_at (dict(str => str)): maps a transition name to the
name of the attribute holding the related implementation.
custom_implems (str set): list of transition names for which a custom
implementation has been defined.
"""
def __init__(self, state_field, workflow):
self.state_field = state_field
self.workflow = workflow
self.implementations = {}
self.transitions_at = {}
self.custom_implems = set()
def load_parent_implems(self, parent_implems):
"""Import previously defined implementations.
Args:
parent_implems (ImplementationList): List of implementations defined
in a parent class.
"""
for trname, attr, implem in parent_implems.get_custom_implementations():
self.implementations[trname] = implem.copy()
self.transitions_at[trname] = attr
self.custom_implems.add(trname)
def add_implem(self, transition, attribute, function, **kwargs):
"""Add an implementation.
Args:
transition (Transition): the transition for which the implementation
is added
attribute (str): the name of the attribute where the implementation
will be available
function (callable): the actual implementation function
**kwargs: extra arguments for the related ImplementationProperty.
"""
implem = ImplementationProperty(
field_name=self.state_field,
transition=transition,
workflow=self.workflow,
implementation=function,
**kwargs)
self.implementations[transition.name] = implem
self.transitions_at[transition.name] = attribute
return implem
def should_collect(self, value):
"""Decide whether a given value should be collected."""
return (
# decorated with @transition
isinstance(value, TransitionWrapper)
# Relates to a compatible transition
and value.trname in self.workflow.transitions
# Either not bound to a state field or bound to the current one
and (not value.field or value.field == self.state_field))
def collect(self, attrs):
"""Collect the implementations from a given attributes dict."""
for name, value in attrs.items():
if self.should_collect(value):
transition = self.workflow.transitions[value.trname]
if (
value.trname in self.implementations
and value.trname in self.custom_implems
and name != self.transitions_at[value.trname]):
# We already have an implementation registered.
other_implem_at = self.transitions_at[value.trname]
raise ValueError(
"Error for attribute %s: it defines implementation "
"%s for transition %s, which is already implemented "
"at %s." % (name, value, transition, other_implem_at))
implem = self.add_implem(transition, name, value.func)
self.custom_implems.add(transition.name)
if value.check:
implem.add_hook(Hook(HOOK_CHECK, value.check))
if value.before:
implem.add_hook(Hook(HOOK_BEFORE, value.before))
if value.after:
implem.add_hook(Hook(HOOK_AFTER, value.after))
def get_custom_implementations(self):
"""Retrieve a list of cutom implementations.
Yields:
(str, str, ImplementationProperty) tuples: The name of the attribute
an implementation lives at, the name of the related transition,
and the related implementation.
"""
for trname in self.custom_implems:
attr = self.transitions_at[trname]
implem = self.implementations[trname]
yield (trname, attr, implem)
def add_missing_implementations(self):
for transition in self.workflow.transitions:
if transition.name not in self.implementations:
self.add_implem(transition, transition.name, noop)
def register_hooks(self, cls):
for field, value in utils.iterclass(cls):
if is_callable(value) and hasattr(value, 'xworkflows_hook'):
self.register_function_hooks(value)
def register_function_hooks(self, func):
"""Looks at an object method and registers it for relevent transitions."""
for hook_kind, hooks in func.xworkflows_hook.items():
for field_name, hook in hooks:
if field_name and field_name != self.state_field:
continue
for transition in self.workflow.transitions:
if hook.applies_to(transition):
implem = self.implementations[transition.name]
implem.add_hook(hook)
def _may_override(self, implem, other):
"""Checks whether an ImplementationProperty may override an attribute."""
if isinstance(other, ImplementationProperty):
# Overriding another custom implementation for the same transition
# and field
return (other.transition == implem.transition and other.field_name == self.state_field)
elif isinstance(other, TransitionWrapper):
# Overriding the definition that led to adding the current
# ImplementationProperty.
return (
other.trname == implem.transition.name
and (not other.field or other.field == self.state_field)
and other.func == implem.implementation)
return False
def transform(self, attrs):
"""Perform all actions on a given attribute dict."""
self.collect(attrs)
self.add_missing_implementations()
self.fill_attrs(attrs)
|
rbarrois/xworkflows | src/xworkflows/base.py | ImplementationList.transform | python | def transform(self, attrs):
self.collect(attrs)
self.add_missing_implementations()
self.fill_attrs(attrs) | Perform all actions on a given attribute dict. | train | https://github.com/rbarrois/xworkflows/blob/4a94b04ba83cb43f61d4b0f7db6964a667c86b5b/src/xworkflows/base.py#L801-L805 | [
"def collect(self, attrs):\n \"\"\"Collect the implementations from a given attributes dict.\"\"\"\n\n for name, value in attrs.items():\n if self.should_collect(value):\n transition = self.workflow.transitions[value.trname]\n\n if (\n value.trname in self.imple... | class ImplementationList(object):
"""Stores all implementations.
Attributes:
state_field (str): the name of the field holding the state of objects.
implementations (dict(str => ImplementationProperty)): maps a transition
name to the associated implementation.
workflow (Workflow): the related workflow
transitions_at (dict(str => str)): maps a transition name to the
name of the attribute holding the related implementation.
custom_implems (str set): list of transition names for which a custom
implementation has been defined.
"""
def __init__(self, state_field, workflow):
self.state_field = state_field
self.workflow = workflow
self.implementations = {}
self.transitions_at = {}
self.custom_implems = set()
def load_parent_implems(self, parent_implems):
"""Import previously defined implementations.
Args:
parent_implems (ImplementationList): List of implementations defined
in a parent class.
"""
for trname, attr, implem in parent_implems.get_custom_implementations():
self.implementations[trname] = implem.copy()
self.transitions_at[trname] = attr
self.custom_implems.add(trname)
def add_implem(self, transition, attribute, function, **kwargs):
"""Add an implementation.
Args:
transition (Transition): the transition for which the implementation
is added
attribute (str): the name of the attribute where the implementation
will be available
function (callable): the actual implementation function
**kwargs: extra arguments for the related ImplementationProperty.
"""
implem = ImplementationProperty(
field_name=self.state_field,
transition=transition,
workflow=self.workflow,
implementation=function,
**kwargs)
self.implementations[transition.name] = implem
self.transitions_at[transition.name] = attribute
return implem
def should_collect(self, value):
"""Decide whether a given value should be collected."""
return (
# decorated with @transition
isinstance(value, TransitionWrapper)
# Relates to a compatible transition
and value.trname in self.workflow.transitions
# Either not bound to a state field or bound to the current one
and (not value.field or value.field == self.state_field))
def collect(self, attrs):
"""Collect the implementations from a given attributes dict."""
for name, value in attrs.items():
if self.should_collect(value):
transition = self.workflow.transitions[value.trname]
if (
value.trname in self.implementations
and value.trname in self.custom_implems
and name != self.transitions_at[value.trname]):
# We already have an implementation registered.
other_implem_at = self.transitions_at[value.trname]
raise ValueError(
"Error for attribute %s: it defines implementation "
"%s for transition %s, which is already implemented "
"at %s." % (name, value, transition, other_implem_at))
implem = self.add_implem(transition, name, value.func)
self.custom_implems.add(transition.name)
if value.check:
implem.add_hook(Hook(HOOK_CHECK, value.check))
if value.before:
implem.add_hook(Hook(HOOK_BEFORE, value.before))
if value.after:
implem.add_hook(Hook(HOOK_AFTER, value.after))
def get_custom_implementations(self):
"""Retrieve a list of cutom implementations.
Yields:
(str, str, ImplementationProperty) tuples: The name of the attribute
an implementation lives at, the name of the related transition,
and the related implementation.
"""
for trname in self.custom_implems:
attr = self.transitions_at[trname]
implem = self.implementations[trname]
yield (trname, attr, implem)
def add_missing_implementations(self):
for transition in self.workflow.transitions:
if transition.name not in self.implementations:
self.add_implem(transition, transition.name, noop)
def register_hooks(self, cls):
for field, value in utils.iterclass(cls):
if is_callable(value) and hasattr(value, 'xworkflows_hook'):
self.register_function_hooks(value)
def register_function_hooks(self, func):
"""Looks at an object method and registers it for relevent transitions."""
for hook_kind, hooks in func.xworkflows_hook.items():
for field_name, hook in hooks:
if field_name and field_name != self.state_field:
continue
for transition in self.workflow.transitions:
if hook.applies_to(transition):
implem = self.implementations[transition.name]
implem.add_hook(hook)
def _may_override(self, implem, other):
"""Checks whether an ImplementationProperty may override an attribute."""
if isinstance(other, ImplementationProperty):
# Overriding another custom implementation for the same transition
# and field
return (other.transition == implem.transition and other.field_name == self.state_field)
elif isinstance(other, TransitionWrapper):
# Overriding the definition that led to adding the current
# ImplementationProperty.
return (
other.trname == implem.transition.name
and (not other.field or other.field == self.state_field)
and other.func == implem.implementation)
return False
def fill_attrs(self, attrs):
"""Update the 'attrs' dict with generated ImplementationProperty."""
for trname, attrname in self.transitions_at.items():
implem = self.implementations[trname]
if attrname in attrs:
conflicting = attrs[attrname]
if not self._may_override(implem, conflicting):
raise ValueError(
"Can't override transition implementation %s=%r with %r" %
(attrname, conflicting, implem))
attrs[attrname] = implem
return attrs
|
rbarrois/xworkflows | src/xworkflows/base.py | BaseWorkflow.log_transition | python | def log_transition(self, transition, from_state, instance, *args, **kwargs):
logger = logging.getLogger('xworkflows.transitions')
try:
instance_repr = u(repr(instance), 'ignore')
except (UnicodeEncodeError, UnicodeDecodeError):
instance_repr = u("<bad repr>")
logger.info(
u("%s performed transition %s.%s (%s -> %s)"), instance_repr,
self.__class__.__name__, transition.name, from_state.name,
transition.target.name) | Log a transition.
Args:
transition (Transition): the name of the performed transition
from_state (State): the source state
instance (object): the modified object
Kwargs:
Any passed when calling the transition | train | https://github.com/rbarrois/xworkflows/blob/4a94b04ba83cb43f61d4b0f7db6964a667c86b5b/src/xworkflows/base.py#L850-L869 | [
"def u(text, errors=''):\n return str(text)\n"
] | class BaseWorkflow(object):
"""Base class for all workflows.
Attributes:
states (StateList): list of states of this Workflow
transitions (TransitionList): list of Transitions of this Workflow
initial_state (State): initial state for the Workflow
implementation_class (ImplementationWrapper subclass): class to use
for transition implementation wrapping.
For each transition, a ImplementationWrapper with the same name (unless
another name has been specified through the use of the @transition
decorator) is provided to perform the specified transition.
"""
implementation_class = ImplementationWrapper
|
rbarrois/xworkflows | src/xworkflows/base.py | WorkflowEnabledMeta._add_workflow | python | def _add_workflow(mcs, field_name, state_field, attrs):
attrs[field_name] = StateProperty(state_field.workflow, field_name) | Attach a workflow to the attribute list (create a StateProperty). | train | https://github.com/rbarrois/xworkflows/blob/4a94b04ba83cb43f61d4b0f7db6964a667c86b5b/src/xworkflows/base.py#L988-L990 | null | class WorkflowEnabledMeta(type):
"""Base metaclass for all Workflow Enabled objects.
Defines:
- one class attribute for each the attached workflows,
- a '_workflows' attribute, a dict mapping each field_name to the related
Workflow,
- a '_xworkflows_implems' attribute, a dict mapping each field_name to a
dict of related ImplementationProperty.
- one class attribute for each transition for each attached workflow
"""
@classmethod
@classmethod
def _find_workflows(mcs, attrs):
"""Finds all occurrences of a workflow in the attributes definitions.
Returns:
dict(str => StateField): maps an attribute name to a StateField
describing the related Workflow.
"""
workflows = {}
for attribute, value in attrs.items():
if isinstance(value, Workflow):
workflows[attribute] = StateField(value)
return workflows
@classmethod
def _add_transitions(mcs, field_name, workflow, attrs, implems=None):
"""Collect and enhance transition definitions to a workflow.
Modifies the 'attrs' dict in-place.
Args:
field_name (str): name of the field transitions should update
workflow (Workflow): workflow we're working on
attrs (dict): dictionary of attributes to be updated.
implems (ImplementationList): Implementation list from parent
classes (optional)
Returns:
ImplementationList: The new implementation list for this field.
"""
new_implems = ImplementationList(field_name, workflow)
if implems:
new_implems.load_parent_implems(implems)
new_implems.transform(attrs)
return new_implems
@classmethod
def _register_hooks(mcs, cls, implems):
for implem_list in implems.values():
implem_list.register_hooks(cls)
def __new__(mcs, name, bases, attrs):
# Map field_name => StateField
workflows = {}
# Map field_name => ImplementationList
implems = {}
# Collect workflows and implementations from parents
for base in reversed(bases):
if hasattr(base, '_workflows'):
workflows.update(base._workflows)
implems.update(base._xworkflows_implems)
workflows.update(mcs._find_workflows(attrs))
# Update attributes with workflow descriptions, and collect
# implementation declarations.
for field, state_field in workflows.items():
mcs._add_workflow(field, state_field, attrs)
implems[field] = mcs._add_transitions(
field, state_field.workflow, attrs, implems.get(field))
# Set specific attributes for children
attrs['_workflows'] = workflows
attrs['_xworkflows_implems'] = implems
cls = super(WorkflowEnabledMeta, mcs).__new__(mcs, name, bases, attrs)
mcs._register_hooks(cls, implems)
return cls
|
rbarrois/xworkflows | src/xworkflows/base.py | WorkflowEnabledMeta._find_workflows | python | def _find_workflows(mcs, attrs):
workflows = {}
for attribute, value in attrs.items():
if isinstance(value, Workflow):
workflows[attribute] = StateField(value)
return workflows | Finds all occurrences of a workflow in the attributes definitions.
Returns:
dict(str => StateField): maps an attribute name to a StateField
describing the related Workflow. | train | https://github.com/rbarrois/xworkflows/blob/4a94b04ba83cb43f61d4b0f7db6964a667c86b5b/src/xworkflows/base.py#L993-L1004 | null | class WorkflowEnabledMeta(type):
"""Base metaclass for all Workflow Enabled objects.
Defines:
- one class attribute for each the attached workflows,
- a '_workflows' attribute, a dict mapping each field_name to the related
Workflow,
- a '_xworkflows_implems' attribute, a dict mapping each field_name to a
dict of related ImplementationProperty.
- one class attribute for each transition for each attached workflow
"""
@classmethod
def _add_workflow(mcs, field_name, state_field, attrs):
"""Attach a workflow to the attribute list (create a StateProperty)."""
attrs[field_name] = StateProperty(state_field.workflow, field_name)
@classmethod
@classmethod
def _add_transitions(mcs, field_name, workflow, attrs, implems=None):
"""Collect and enhance transition definitions to a workflow.
Modifies the 'attrs' dict in-place.
Args:
field_name (str): name of the field transitions should update
workflow (Workflow): workflow we're working on
attrs (dict): dictionary of attributes to be updated.
implems (ImplementationList): Implementation list from parent
classes (optional)
Returns:
ImplementationList: The new implementation list for this field.
"""
new_implems = ImplementationList(field_name, workflow)
if implems:
new_implems.load_parent_implems(implems)
new_implems.transform(attrs)
return new_implems
@classmethod
def _register_hooks(mcs, cls, implems):
for implem_list in implems.values():
implem_list.register_hooks(cls)
def __new__(mcs, name, bases, attrs):
# Map field_name => StateField
workflows = {}
# Map field_name => ImplementationList
implems = {}
# Collect workflows and implementations from parents
for base in reversed(bases):
if hasattr(base, '_workflows'):
workflows.update(base._workflows)
implems.update(base._xworkflows_implems)
workflows.update(mcs._find_workflows(attrs))
# Update attributes with workflow descriptions, and collect
# implementation declarations.
for field, state_field in workflows.items():
mcs._add_workflow(field, state_field, attrs)
implems[field] = mcs._add_transitions(
field, state_field.workflow, attrs, implems.get(field))
# Set specific attributes for children
attrs['_workflows'] = workflows
attrs['_xworkflows_implems'] = implems
cls = super(WorkflowEnabledMeta, mcs).__new__(mcs, name, bases, attrs)
mcs._register_hooks(cls, implems)
return cls
|
rbarrois/xworkflows | src/xworkflows/base.py | WorkflowEnabledMeta._add_transitions | python | def _add_transitions(mcs, field_name, workflow, attrs, implems=None):
new_implems = ImplementationList(field_name, workflow)
if implems:
new_implems.load_parent_implems(implems)
new_implems.transform(attrs)
return new_implems | Collect and enhance transition definitions to a workflow.
Modifies the 'attrs' dict in-place.
Args:
field_name (str): name of the field transitions should update
workflow (Workflow): workflow we're working on
attrs (dict): dictionary of attributes to be updated.
implems (ImplementationList): Implementation list from parent
classes (optional)
Returns:
ImplementationList: The new implementation list for this field. | train | https://github.com/rbarrois/xworkflows/blob/4a94b04ba83cb43f61d4b0f7db6964a667c86b5b/src/xworkflows/base.py#L1007-L1027 | [
"def load_parent_implems(self, parent_implems):\n \"\"\"Import previously defined implementations.\n\n Args:\n parent_implems (ImplementationList): List of implementations defined\n in a parent class.\n \"\"\"\n for trname, attr, implem in parent_implems.get_custom_implementations():\n... | class WorkflowEnabledMeta(type):
"""Base metaclass for all Workflow Enabled objects.
Defines:
- one class attribute for each the attached workflows,
- a '_workflows' attribute, a dict mapping each field_name to the related
Workflow,
- a '_xworkflows_implems' attribute, a dict mapping each field_name to a
dict of related ImplementationProperty.
- one class attribute for each transition for each attached workflow
"""
@classmethod
def _add_workflow(mcs, field_name, state_field, attrs):
"""Attach a workflow to the attribute list (create a StateProperty)."""
attrs[field_name] = StateProperty(state_field.workflow, field_name)
@classmethod
def _find_workflows(mcs, attrs):
"""Finds all occurrences of a workflow in the attributes definitions.
Returns:
dict(str => StateField): maps an attribute name to a StateField
describing the related Workflow.
"""
workflows = {}
for attribute, value in attrs.items():
if isinstance(value, Workflow):
workflows[attribute] = StateField(value)
return workflows
@classmethod
@classmethod
def _register_hooks(mcs, cls, implems):
for implem_list in implems.values():
implem_list.register_hooks(cls)
def __new__(mcs, name, bases, attrs):
# Map field_name => StateField
workflows = {}
# Map field_name => ImplementationList
implems = {}
# Collect workflows and implementations from parents
for base in reversed(bases):
if hasattr(base, '_workflows'):
workflows.update(base._workflows)
implems.update(base._xworkflows_implems)
workflows.update(mcs._find_workflows(attrs))
# Update attributes with workflow descriptions, and collect
# implementation declarations.
for field, state_field in workflows.items():
mcs._add_workflow(field, state_field, attrs)
implems[field] = mcs._add_transitions(
field, state_field.workflow, attrs, implems.get(field))
# Set specific attributes for children
attrs['_workflows'] = workflows
attrs['_xworkflows_implems'] = implems
cls = super(WorkflowEnabledMeta, mcs).__new__(mcs, name, bases, attrs)
mcs._register_hooks(cls, implems)
return cls
|
rbarrois/xworkflows | src/xworkflows/utils.py | iterclass | python | def iterclass(cls):
for field in dir(cls):
if hasattr(cls, field):
value = getattr(cls, field)
yield field, value | Iterates over (valid) attributes of a class.
Args:
cls (object): the class to iterate over
Yields:
(str, obj) tuples: the class-level attributes. | train | https://github.com/rbarrois/xworkflows/blob/4a94b04ba83cb43f61d4b0f7db6964a667c86b5b/src/xworkflows/utils.py#L9-L21 | null | # -*- coding: utf-8 -*-
# Copyright (c) 2011-2013 Raphaël Barrois
# This code is distributed under the two-clause BSD License.
"""Base components of XWorkflows."""
|
roanuz/py-cricket | src/pycricket_storagehandler.py | RcaFileStorageHandler.set_value | python | def set_value(self, key, value):
file_cache = self.read_file()
if file_cache:
file_cache[key] = value
else:
file_cache = {}
file_cache[key] = value
self.update_file(file_cache) | Set key value to the file.
The fuction will be make the key and value to dictinary formate.
If its exist then it will update the current new key value to
the file.
Arg:
key : cache key
value : cache value | train | https://github.com/roanuz/py-cricket/blob/fa47fe2e92915fc58db38898213e974742af55d4/src/pycricket_storagehandler.py#L56-L73 | [
"def read_file(self):\n \"\"\"\n Open the file and assiging the permission to read/write and\n return the content in json formate.\n\n Return : json data\n \"\"\"\n file_obj = open(self.file, 'r')\n content = file_obj.read()\n file_obj.close()\n if content:\n content = json.loads(c... | class RcaFileStorageHandler():
"""
The RcaFileStorageHandler create a text file and save required access
details as a form of string of dictinary.
The file will contains following
access_token : string
expires : timestamp
device_id : string
Example:
'{ "access_token": "xxxxxxxxxxxxxxxxxxxxxxxxx",
"expires": "1456571889.0",
"device_id": "9e6f5ec8-dc7a-11e5-aab3-4cbb5882d7c3"
}'
"""
def __init__(self, path=None, name='token.txt'):
"""
Initialize the file path and name.
Arg:
path (optinal) : You have to pass the file path otherwise file
will create on current running path
name (optinal) : File name to your file, defult it will the
name "token.txt".
"""
if path and name:
self.file = path + name
else:
self.file = name
def get_value(self, key):
"""
Return the file key value from file.
Arg:
key : cache key
Return:
value of the key
"""
file_cache = self.read_file()
return file_cache[key]
def has_value(self, key):
"""Checking the available of key and return True if it's exist
otherwise will be False.
Arg:
key : cache key
Return:
Boolean True/False
"""
file_cache = self.read_file()
return key in file_cache
def delete_value(self, key):
"""
Delete the key if the token is expired.
Arg:
key : cache key
"""
response = {}
response['status'] = False
response['msg'] = "key does not exist"
file_cache = self.read_file()
if key in file_cache:
del file_cache[key]
self.update_file(file_cache)
response['status'] = True
response['msg'] = "success"
return response
# TODO : If key does not exist
def new_device_id(self):
"""
Creating a new device_id for user.
"""
return str(uuid.uuid1()) # create unique device id.
def read_file(self):
"""
Open the file and assiging the permission to read/write and
return the content in json formate.
Return : json data
"""
file_obj = open(self.file, 'r')
content = file_obj.read()
file_obj.close()
if content:
content = json.loads(content)
return content
else:
return {}
def update_file(self, content):
"""
It will convert json content to json string and update into file.
Return:
Boolean True/False
"""
updated_content = json.dumps(content)
file_obj = open(self.file, 'r+')
file_obj.write(str(updated_content))
file_obj.close()
return True
|
roanuz/py-cricket | src/pycricket_storagehandler.py | RcaFileStorageHandler.delete_value | python | def delete_value(self, key):
response = {}
response['status'] = False
response['msg'] = "key does not exist"
file_cache = self.read_file()
if key in file_cache:
del file_cache[key]
self.update_file(file_cache)
response['status'] = True
response['msg'] = "success"
return response | Delete the key if the token is expired.
Arg:
key : cache key | train | https://github.com/roanuz/py-cricket/blob/fa47fe2e92915fc58db38898213e974742af55d4/src/pycricket_storagehandler.py#L101-L118 | [
"def read_file(self):\n \"\"\"\n Open the file and assiging the permission to read/write and\n return the content in json formate.\n\n Return : json data\n \"\"\"\n file_obj = open(self.file, 'r')\n content = file_obj.read()\n file_obj.close()\n if content:\n content = json.loads(c... | class RcaFileStorageHandler():
"""
The RcaFileStorageHandler create a text file and save required access
details as a form of string of dictinary.
The file will contains following
access_token : string
expires : timestamp
device_id : string
Example:
'{ "access_token": "xxxxxxxxxxxxxxxxxxxxxxxxx",
"expires": "1456571889.0",
"device_id": "9e6f5ec8-dc7a-11e5-aab3-4cbb5882d7c3"
}'
"""
def __init__(self, path=None, name='token.txt'):
"""
Initialize the file path and name.
Arg:
path (optinal) : You have to pass the file path otherwise file
will create on current running path
name (optinal) : File name to your file, defult it will the
name "token.txt".
"""
if path and name:
self.file = path + name
else:
self.file = name
def set_value(self, key, value):
"""
Set key value to the file.
The fuction will be make the key and value to dictinary formate.
If its exist then it will update the current new key value to
the file.
Arg:
key : cache key
value : cache value
"""
file_cache = self.read_file()
if file_cache:
file_cache[key] = value
else:
file_cache = {}
file_cache[key] = value
self.update_file(file_cache)
def get_value(self, key):
"""
Return the file key value from file.
Arg:
key : cache key
Return:
value of the key
"""
file_cache = self.read_file()
return file_cache[key]
def has_value(self, key):
"""Checking the available of key and return True if it's exist
otherwise will be False.
Arg:
key : cache key
Return:
Boolean True/False
"""
file_cache = self.read_file()
return key in file_cache
# TODO : If key does not exist
def new_device_id(self):
"""
Creating a new device_id for user.
"""
return str(uuid.uuid1()) # create unique device id.
def read_file(self):
"""
Open the file and assiging the permission to read/write and
return the content in json formate.
Return : json data
"""
file_obj = open(self.file, 'r')
content = file_obj.read()
file_obj.close()
if content:
content = json.loads(content)
return content
else:
return {}
def update_file(self, content):
"""
It will convert json content to json string and update into file.
Return:
Boolean True/False
"""
updated_content = json.dumps(content)
file_obj = open(self.file, 'r+')
file_obj.write(str(updated_content))
file_obj.close()
return True
|
roanuz/py-cricket | src/pycricket_storagehandler.py | RcaFileStorageHandler.read_file | python | def read_file(self):
file_obj = open(self.file, 'r')
content = file_obj.read()
file_obj.close()
if content:
content = json.loads(content)
return content
else:
return {} | Open the file and assiging the permission to read/write and
return the content in json formate.
Return : json data | train | https://github.com/roanuz/py-cricket/blob/fa47fe2e92915fc58db38898213e974742af55d4/src/pycricket_storagehandler.py#L128-L142 | null | class RcaFileStorageHandler():
"""
The RcaFileStorageHandler create a text file and save required access
details as a form of string of dictinary.
The file will contains following
access_token : string
expires : timestamp
device_id : string
Example:
'{ "access_token": "xxxxxxxxxxxxxxxxxxxxxxxxx",
"expires": "1456571889.0",
"device_id": "9e6f5ec8-dc7a-11e5-aab3-4cbb5882d7c3"
}'
"""
def __init__(self, path=None, name='token.txt'):
"""
Initialize the file path and name.
Arg:
path (optinal) : You have to pass the file path otherwise file
will create on current running path
name (optinal) : File name to your file, defult it will the
name "token.txt".
"""
if path and name:
self.file = path + name
else:
self.file = name
def set_value(self, key, value):
"""
Set key value to the file.
The fuction will be make the key and value to dictinary formate.
If its exist then it will update the current new key value to
the file.
Arg:
key : cache key
value : cache value
"""
file_cache = self.read_file()
if file_cache:
file_cache[key] = value
else:
file_cache = {}
file_cache[key] = value
self.update_file(file_cache)
def get_value(self, key):
"""
Return the file key value from file.
Arg:
key : cache key
Return:
value of the key
"""
file_cache = self.read_file()
return file_cache[key]
def has_value(self, key):
"""Checking the available of key and return True if it's exist
otherwise will be False.
Arg:
key : cache key
Return:
Boolean True/False
"""
file_cache = self.read_file()
return key in file_cache
def delete_value(self, key):
"""
Delete the key if the token is expired.
Arg:
key : cache key
"""
response = {}
response['status'] = False
response['msg'] = "key does not exist"
file_cache = self.read_file()
if key in file_cache:
del file_cache[key]
self.update_file(file_cache)
response['status'] = True
response['msg'] = "success"
return response
# TODO : If key does not exist
def new_device_id(self):
"""
Creating a new device_id for user.
"""
return str(uuid.uuid1()) # create unique device id.
def update_file(self, content):
"""
It will convert json content to json string and update into file.
Return:
Boolean True/False
"""
updated_content = json.dumps(content)
file_obj = open(self.file, 'r+')
file_obj.write(str(updated_content))
file_obj.close()
return True
|
roanuz/py-cricket | src/pycricket_storagehandler.py | RcaFileStorageHandler.update_file | python | def update_file(self, content):
updated_content = json.dumps(content)
file_obj = open(self.file, 'r+')
file_obj.write(str(updated_content))
file_obj.close()
return True | It will convert json content to json string and update into file.
Return:
Boolean True/False | train | https://github.com/roanuz/py-cricket/blob/fa47fe2e92915fc58db38898213e974742af55d4/src/pycricket_storagehandler.py#L144-L155 | null | class RcaFileStorageHandler():
"""
The RcaFileStorageHandler create a text file and save required access
details as a form of string of dictinary.
The file will contains following
access_token : string
expires : timestamp
device_id : string
Example:
'{ "access_token": "xxxxxxxxxxxxxxxxxxxxxxxxx",
"expires": "1456571889.0",
"device_id": "9e6f5ec8-dc7a-11e5-aab3-4cbb5882d7c3"
}'
"""
def __init__(self, path=None, name='token.txt'):
"""
Initialize the file path and name.
Arg:
path (optinal) : You have to pass the file path otherwise file
will create on current running path
name (optinal) : File name to your file, defult it will the
name "token.txt".
"""
if path and name:
self.file = path + name
else:
self.file = name
def set_value(self, key, value):
"""
Set key value to the file.
The fuction will be make the key and value to dictinary formate.
If its exist then it will update the current new key value to
the file.
Arg:
key : cache key
value : cache value
"""
file_cache = self.read_file()
if file_cache:
file_cache[key] = value
else:
file_cache = {}
file_cache[key] = value
self.update_file(file_cache)
def get_value(self, key):
"""
Return the file key value from file.
Arg:
key : cache key
Return:
value of the key
"""
file_cache = self.read_file()
return file_cache[key]
def has_value(self, key):
"""Checking the available of key and return True if it's exist
otherwise will be False.
Arg:
key : cache key
Return:
Boolean True/False
"""
file_cache = self.read_file()
return key in file_cache
def delete_value(self, key):
"""
Delete the key if the token is expired.
Arg:
key : cache key
"""
response = {}
response['status'] = False
response['msg'] = "key does not exist"
file_cache = self.read_file()
if key in file_cache:
del file_cache[key]
self.update_file(file_cache)
response['status'] = True
response['msg'] = "success"
return response
# TODO : If key does not exist
def new_device_id(self):
"""
Creating a new device_id for user.
"""
return str(uuid.uuid1()) # create unique device id.
def read_file(self):
"""
Open the file and assiging the permission to read/write and
return the content in json formate.
Return : json data
"""
file_obj = open(self.file, 'r')
content = file_obj.read()
file_obj.close()
if content:
content = json.loads(content)
return content
else:
return {}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.