code
stringlengths 52
7.75k
| docs
stringlengths 1
5.85k
|
---|---|
def delete(self, photo_id, album_id=0):
if isinstance(photo_id, Info):
photo_id = photo_id.id
return self._session.okc_post('photoupload', data={
'albumid': album_id,
'picid': photo_id,
'authcode': self._authcode,
'picture.delete_ajax': 1
}) | Delete a photo from the logged in users account.
:param photo_id: The okcupid id of the photo to delete.
:param album_id: The album from which to delete the photo. |
def add_command_line_options(add_argument, use_short_options=True):
logger_args = ("--enable-logger",)
credentials_args = ("--credentials",)
if use_short_options:
logger_args += ('-l',)
credentials_args += ('-c',)
add_argument(*logger_args, dest='enabled_loggers',
action="append", default=[],
help="Enable the specified logger.")
add_argument(*credentials_args, dest='credential_files',
action="append", default=[],
help="Use the specified credentials module to update "
"the values in okcupyd.settings.")
add_argument('--echo', dest='echo', action='store_true', default=False,
help="Echo SQL.") | :param add_argument: The add_argument method of an ArgParser.
:param use_short_options: Whether or not to add short options. |
def handle_command_line_options(args):
for enabled_log in args.enabled_loggers:
enable_logger(enabled_log)
for credential_file in args.credential_files:
settings.load_credentials_from_filepath(credential_file)
if args.echo:
from okcupyd import db
db.echo = True
db.Session.kw['bind'].echo = True
return args | :param args: The args returned from an ArgParser |
def IndexedREMap(*re_strings, **kwargs):
default = kwargs.get('default', 0)
offset = kwargs.get('offset', 1)
string_index_pairs = []
for index, string_or_tuple in enumerate(re_strings, offset):
if isinstance(string_or_tuple, six.string_types):
string_or_tuple = (string_or_tuple,)
for re_string in string_or_tuple:
string_index_pairs.append((re_string, index))
remap = REMap.from_string_pairs(string_index_pairs,
default=default)
return remap | Build a :class:`~.REMap` from the provided regular expression string.
Each string will be associated with the index corresponding to its position
in the argument list.
:param re_strings: The re_strings that will serve as keys in the map.
:param default: The value to return if none of the regular expressions match
:param offset: The offset at which to start indexing for regular expressions
defaults to 1. |
def bust_self(self, obj):
if self.func.__name__ in obj.__dict__:
delattr(obj, self.func.__name__) | Remove the value that is being stored on `obj` for this
:class:`.cached_property`
object.
:param obj: The instance on which to bust the cache. |
def bust_caches(cls, obj, excludes=()):
for name, _ in cls.get_cached_properties(obj):
if name in obj.__dict__ and not name in excludes:
delattr(obj, name) | Bust the cache for all :class:`.cached_property` objects on `obj`
:param obj: The instance on which to bust the caches. |
def from_string_pairs(cls, string_value_pairs, **kwargs):
return cls(re_value_pairs=[(re.compile(s), v)
for s, v in string_value_pairs],
**kwargs) | Build an :class:`~.REMap` from str, value pairs by applying
`re.compile` to each string and calling the __init__ of :class:`~.REMap` |
def __get_dbms_version(self, make_connection=True):
if not self.connection and make_connection:
self.connect()
with self.connection.cursor() as cursor:
cursor.execute("SELECT SERVERPROPERTY('productversion')")
return cursor.fetchone()[0] | Returns the 'DBMS Version' string, or ''. If a connection to the
database has not already been established, a connection will be made
when `make_connection` is True. |
def sender(self):
return (self._message_thread.user_profile
if 'from_me' in self._message_element.attrib['class']
else self._message_thread.correspondent_profile) | :returns: A :class:`~okcupyd.profile.Profile` instance belonging
to the sender of this message. |
def recipient(self):
return (self._message_thread.correspondent_profile
if 'from_me' in self._message_element.attrib['class']
else self._message_thread.user_profile) | :returns: A :class:`~okcupyd.profile.Profile` instance belonging
to the recipient of this message. |
def content(self):
# The code that follows is obviously pretty disgusting.
# It seems like it might be impossible to completely replicate
# the text of the original message if it has trailing whitespace
message = self._content_xpb.one_(self._message_element)
first_line = message.text
if message.text[:2] == ' ':
first_line = message.text[2:]
else:
log.debug("message did not have expected leading whitespace")
subsequent_lines = ''.join([
html.tostring(child, encoding='unicode').replace('<br>', '\n')
for child in message.iterchildren()
])
message_text = first_line + subsequent_lines
if len(message_text) > 0 and message_text[-1] == ' ':
message_text = message_text[:-1]
else:
log.debug("message did not have expected leading whitespace")
return message_text | :returns: The text body of the message. |
def delete_threads(cls, session, thread_ids_or_threads, authcode=None):
thread_ids = [thread.id if isinstance(thread, cls) else thread
for thread in thread_ids_or_threads]
if not authcode:
authcode = helpers.get_authcode(html.fromstring(
session.okc_get('messages').content
))
data = {'access_token': authcode,
'threadids': simplejson.dumps(thread_ids)}
return session.okc_delete('apitun/messages/threads',
params=data, data=data) | :param session: A logged in :class:`~okcupyd.session.Session`.
:param thread_ids_or_threads: A list whose members are either
:class:`~.MessageThread` instances
or okc_ids of message threads.
:param authcode: Authcode to use for this request. If none is provided
A request to the logged in user's messages page
will be made to retrieve one. |
def correspondent_id(self):
try:
return int(self._thread_element.attrib['data-personid'])
except (ValueError, KeyError):
try:
return int(self.correspondent_profile.id)
except:
pass | :returns: The id assigned to the correspondent of this message. |
def correspondent(self):
try:
return self._correspondent_xpb.one_(self._thread_element).strip()
except IndexError:
raise errors.NoCorrespondentError() | :returns: The username of the user with whom the logged in user is
conversing in this :class:`~.MessageThread`. |
def got_response(self):
return any(message.sender != self.initiator
for message in self.messages) | :returns: Whether or not the :class:`~.MessageThread`. has received a
response. |
def get_answer_id_for_question(self, question):
assert question.id == self.id
for answer_option in self.answer_options:
if answer_option.text == question.their_answer:
return answer_option.id | Get the answer_id corresponding to the answer given for question
by looking at this :class:`~.UserQuestion`'s answer_options.
The given :class:`~.Question` instance must have the same id as this
:class:`~.UserQuestion`.
That this method exists is admittedly somewhat weird. Unfortunately, it
seems to be the only way to retrieve this information. |
def answer_options(self):
return [
AnswerOption(element)
for element in self._answer_option_xpb.apply_(
self._question_element
)
] | :returns: A list of :class:`~.AnswerOption` instances representing the
available answers to this question. |
def respond_from_user_question(self, user_question, importance):
user_response_ids = [option.id
for option in user_question.answer_options
if option.is_users]
match_response_ids = [option.id
for option in user_question.answer_options
if option.is_match]
if len(match_response_ids) == len(user_question.answer_options):
match_response_ids = 'irrelevant'
return self.respond(user_question.id, user_response_ids,
match_response_ids, importance,
note=user_question.explanation or '') | Respond to a question in exactly the way that is described by
the given user_question.
:param user_question: The user question to respond with.
:type user_question: :class:`.UserQuestion`
:param importance: The importance that should be used in responding to
the question.
:type importance: int see :attr:`.importance_name_to_number` |
def respond_from_question(self, question, user_question, importance):
option_index = user_question.answer_text_to_option[
question.their_answer
].id
self.respond(question.id, [option_index], [option_index], importance) | Copy the answer given in `question` to the logged in user's
profile.
:param question: A :class:`~.Question` instance to copy.
:param user_question: An instance of :class:`~.UserQuestion` that
corresponds to the same question as `question`.
This is needed to retrieve the answer id from
the question text answer on question.
:param importance: The importance to assign to the response to the
answered question. |
def respond(self, question_id, user_response_ids, match_response_ids,
importance, note='', is_public=1, is_new=1):
form_data = {
'ajax': 1,
'submit': 1,
'answer_question': 1,
'skip': 0,
'show_all': 0,
'targetid': self._user_id,
'qid': question_id,
'answers': user_response_ids,
'matchanswers': match_response_ids,
'is_new': is_new,
'is_public': is_public,
'note': note,
'importance': importance,
'delete_note': 0
}
return self._session.okc_post(
self.path, data=form_data, headers=self.headers
) | Respond to an okcupid.com question.
:param question_id: The okcupid id used to identify this question.
:param user_response_ids: The answer id(s) to provide to this question.
:param match_response_ids: The answer id(s) that the user considers
acceptable.
:param importance: The importance to attribute to this question. See
:attr:`.importance_name_to_number` for details.
:param note: The explanation note to add to this question.
:param is_public: Whether or not the question answer should be made
public. |
def message(self, username, message_text):
# Try to reply to an existing thread.
if not isinstance(username, six.string_types):
username = username.username
for mailbox in (self.inbox, self.outbox):
for thread in mailbox:
if thread.correspondent.lower() == username.lower():
thread.reply(message_text)
return
return self._message_sender.send(username, message_text) | Message an okcupid user. If an existing conversation between the
logged in user and the target user can be found, reply to that thread
instead of starting a new one.
:param username: The username of the user to which the message should
be sent.
:type username: str
:param message_text: The body of the message.
:type message_text: str |
def search(self, **kwargs):
kwargs.setdefault('gender', self.profile.gender[0])
gentation = helpers.get_default_gentation(self.profile.gender,
self.profile.orientation)
kwargs.setdefault('gentation', gentation)
# We are no longer setting location by default because the
# query api that okcupid offers seems to have gotten much
# stricter. This should be revisited so that search gives good
# default results. This is issue #85.
# kwargs.setdefault('location', self.profile.location)
kwargs.setdefault('radius', 25)
kwargs.setdefault('location_cache', self.location_cache)
if 'count' in kwargs:
count = kwargs.pop('count')
return search(session=self._session, count=count, **kwargs)
return SearchFetchable(self._session, **kwargs) | Call :func:`~okcupyd.json_search.SearchFetchable` to get a
:class:`~okcupyd.util.fetchable.Fetchable` object that will lazily
perform okcupid searches to provide :class:`~okcupyd.profile.Profile`
objects matching the search criteria.
Defaults for `gender`, `gentation`, `location` and `radius` will
be provided if none are given.
:param kwargs: See the :func:`~okcupyd.json_search.SearchFetchable`
docstring for details about what parameters are
available. |
def get_question_answer_id(self, question, fast=False,
bust_questions_cache=False):
if hasattr(question, 'answer_id'):
# Guard to handle incoming user_question.
return question.answer_id
user_question = self.get_user_question(
question, fast=fast, bust_questions_cache=bust_questions_cache
)
# Look at recently answered questions
return user_question.get_answer_id_for_question(question) | Get the index of the answer that was given to `question`
See the documentation for :meth:`~.get_user_question` for important
caveats about the use of this function.
:param question: The question whose `answer_id` should be retrieved.
:type question: :class:`~okcupyd.question.BaseQuestion`
:param fast: Don't try to look through the users existing questions to
see if arbitrarily answering the question can be avoided.
:type fast: bool
:param bust_questions_cache: :param bust_questions_cache: clear the
:attr:`~okcupyd.profile.Profile.questions`
attribute of this users
:class:`~okcupyd.profile.Profile`
before looking for an existing answer.
Be aware that even this does not eliminate
all race conditions.
:type bust_questions_cache: bool |
def quickmatch(self):
response = self._session.okc_get('quickmatch', params={'okc_api': 1})
return Profile(self._session, response.json()['sn']) | Return a :class:`~okcupyd.profile.Profile` obtained by visiting the
quickmatch page. |
def SearchFetchable(session=None, **kwargs):
session = session or Session.login()
return util.Fetchable(
SearchManager(
SearchJSONFetcher(session, **kwargs),
ProfileBuilder(session)
)
) | Search okcupid.com with the given parameters. Parameters are
registered to this function through
:meth:`~okcupyd.filter.Filters.register_filter_builder` of
:data:`~okcupyd.json_search.search_filters`.
:returns: A :class:`~okcupyd.util.fetchable.Fetchable` of
:class:`~okcupyd.profile.Profile` instances.
:param session: A logged in session.
:type session: :class:`~okcupyd.session.Session` |
def refresh(self, nice_repr=True, **kwargs):
for key, value in self._kwargs.items():
kwargs.setdefault(key, value)
# No real good reason to hold on to this. DONT TOUCH.
self._original_iterable = self._fetcher.fetch(**kwargs)
self.exhausted = False
if nice_repr:
self._accumulated = []
self._original_iterable = self._make_nice_repr_iterator(
self._original_iterable, self._accumulated
)
else:
self._accumulated = None
self._clonable, = itertools.tee(self._original_iterable, 1)
return self | :param nice_repr: Append the repr of a list containing the items that
have been fetched to this point by the fetcher.
:type nice_repr: bool
:param kwargs: kwargs that should be passed to the fetcher when its
fetch method is called. These are merged with the values
provided to the constructor, with the ones provided here
taking precedence if there is a conflict. |
def build_documentation_lines(self):
return [
line_string for key in sorted(self.keys)
for line_string in self.build_paramter_string(key)
] | Build a parameter documentation string that can appended to the
docstring of a function that uses this :class:`~.Filters` instance
to build filters. |
def register_filter_builder(self, function, **kwargs):
kwargs['transform'] = function
if kwargs.get('decider'):
kwargs['decide'] = kwargs.get('decider')
return type('filter', (self.filter_class,), kwargs) | Register a filter function with this :class:`~.Filters` instance.
This function is curried with :class:`~okcupyd.util.currying.curry`
-- that is, it can be invoked partially before it is fully evaluated.
This allows us to pass kwargs to this function when it is used as a
decorator:
.. code-block:: python
@register_filter_builder(keys=('real_name',),
decider=Filters.any_decider)
def my_filter_function(argument):
return '4,{0}'.format(argument)
:param function: The filter function to register.
:param keys: Keys that should be used as the argument names for
`function`, if none are provided, the filter functions
argument names will be used instead.
:param decider: a function of signature
`(function, incoming_keys, accepted_keys)` that returns
True if the filter function should be called and False
otherwise. Defaults to
:meth:`~.all_not_none_decider`
:param acceptable_values: A list of acceptable values for the parameter
of the filter function (or a list of lists if
the filter function takes multiple parameters)
:param types: The type of the parameter accepted by the incoming filter
function (or a list of types if the function takes
multiple parameters)
:param descriptions: A description for the incoming filter function's
argument (or a list of descriptions if the filter
function takes multiple arguments)
:param output_key: The key to use to output the provided value. Will
default to the only value in keys if keys has
length 1. |
def get_locid(session, location):
locid = 0
query_parameters = {
'func': 'query',
'query': location,
}
loc_query = session.get('http://www.okcupid.com/locquery',
params=query_parameters)
p = html.fromstring(loc_query.content.decode('utf8'))
js = loads(p.text)
if 'results' in js and len(js['results']):
locid = js['results'][0]['locid']
return locid | Make a request to locquery resource to translate a string location
search into an int locid.
Returns
----------
int
An int that OKCupid maps to a particular geographical location. |
def format_last_online(last_online):
if isinstance(last_online, str):
if last_online.lower() in ('day', 'today'):
last_online_int = 86400 # 3600 * 24
elif last_online.lower() == 'week':
last_online_int = 604800 # 3600 * 24 * 7
elif last_online.lower() == 'month':
last_online_int = 2678400 # 3600 * 24 * 31
elif last_online.lower() == 'year':
last_online_int = 31536000 # 3600 * 365
elif last_online.lower() == 'decade':
last_online_int = 315360000 # 3600 * 365 * 10
else: # Defaults any other strings to last hour
last_online_int = 3600
else:
last_online_int = last_online
return last_online_int | Return the upper limit in seconds that a profile may have been
online. If last_online is an int, return that int. Otherwise if
last_online is a str, convert the string into an int.
Returns
----------
int |
def update_looking_for(profile_tree, looking_for):
div = profile_tree.xpath("//div[@id = 'what_i_want']")[0]
looking_for['gentation'] = div.xpath(".//li[@id = 'ajax_gentation']/text()")[0].strip()
looking_for['ages'] = replace_chars(div.xpath(".//li[@id = 'ajax_ages']/text()")[0].strip())
looking_for['near'] = div.xpath(".//li[@id = 'ajax_near']/text()")[0].strip()
looking_for['single'] = div.xpath(".//li[@id = 'ajax_single']/text()")[0].strip()
try:
looking_for['seeking'] = div.xpath(".//li[@id = 'ajax_lookingfor']/text()")[0].strip()
except:
pass | Update looking_for attribute of a Profile. |
def update_details(profile_tree, details):
div = profile_tree.xpath("//div[@id = 'profile_details']")[0]
for dl in div.iter('dl'):
title = dl.find('dt').text
item = dl.find('dd')
if title == 'Last Online' and item.find('span') is not None:
details[title.lower()] = item.find('span').text.strip()
elif title.lower() in details and len(item.text):
details[title.lower()] = item.text.strip()
else:
continue
details[title.lower()] = replace_chars(details[title.lower()]) | Update details attribute of a Profile. |
def get_default_gentation(gender, orientation):
gender = gender.lower()[0]
orientation = orientation.lower()
return gender_to_orientation_to_gentation[gender][orientation] | Return the default gentation for the given gender and orientation. |
def replace_chars(astring):
for k, v in CHAR_REPLACE.items():
astring = astring.replace(k, v)
return astring | Replace certain unicode characters to avoid errors when trying
to read various strings.
Returns
----------
str |
def add_newlines(tree):
for br in tree.xpath("*//br"):
br.tail = u"\n" + br.tail if br.tail else u"\n" | Add a newline character to the end of each <br> element. |
def find_attractiveness(self, username, accuracy=1000,
_lower=0, _higher=10000):
average = (_higher + _lower)//2
if _higher - _lower <= accuracy:
return average
results = search(self._session,
count=9,
gentation='everybody',
keywords=username,
attractiveness_min=average,
attractiveness_max=_higher,)
found_match = False
if results:
for profile in results:
if profile.username.lower() == username:
found_match = True
break
if found_match:
return self.find_attractiveness(username, accuracy,
average, _higher)
else:
return self.find_attractiveness(username, accuracy,
_lower, average) | :param username: The username to lookup attractiveness for.
:param accuracy: The accuracy required to return a result.
:param _lower: The lower bound of the search.
:param _higher: The upper bound of the search. |
def update_mailbox(self, mailbox_name='inbox'):
with txn() as session:
last_updated_name = '{0}_last_updated'.format(mailbox_name)
okcupyd_user = session.query(model.OKCupydUser).join(model.User).filter(
model.User.okc_id == self._user.profile.id
).with_for_update().one()
log.info(simplejson.dumps({
'{0}_last_updated'.format(mailbox_name): helpers.datetime_to_string(
getattr(okcupyd_user, last_updated_name)
)
}))
res = self._sync_mailbox_until(
getattr(self._user, mailbox_name)(),
getattr(okcupyd_user, last_updated_name)
)
if not res:
return None, None
last_updated, threads, new_messages = res
if last_updated:
setattr(okcupyd_user, last_updated_name, last_updated)
return threads, new_messages | Update the mailbox associated with the given mailbox name. |
def photos(self):
# Reverse because pictures appear in inverse chronological order.
for photo_info in self.dest_user.profile.photo_infos:
self.dest_user.photo.delete(photo_info)
return [self.dest_user.photo.upload_and_confirm(info)
for info in reversed(self.source_profile.photo_infos)] | Copy photos to the destination user. |
def essays(self):
for essay_name in self.dest_user.profile.essays.essay_names:
setattr(self.dest_user.profile.essays, essay_name,
getattr(self.source_profile.essays, essay_name)) | Copy essays from the source profile to the destination profile. |
def looking_for(self):
looking_for = self.source_profile.looking_for
return self.dest_user.profile.looking_for.update(
gentation=looking_for.gentation,
single=looking_for.single,
near_me=looking_for.near_me,
kinds=looking_for.kinds,
ages=looking_for.ages
) | Copy looking for attributes from the source profile to the
destination profile. |
def details(self):
return self.dest_user.profile.details.convert_and_update(
self.source_profile.details.as_dict
) | Copy details from the source profile to the destination profile. |
def SearchFetchable(session=None, **kwargs):
session = session or Session.login()
return util.Fetchable.fetch_marshall(
SearchHTMLFetcher(session, **kwargs),
util.SimpleProcessor(
session,
lambda match_card_div: Profile(
session=session,
**MatchCardExtractor(match_card_div).as_dict
),
_match_card_xpb
)
) | Search okcupid.com with the given parameters. Parameters are registered
to this function through :meth:`~okcupyd.filter.Filters.register_filter_builder`
of :data:`~okcupyd.html_search.search_filters`.
:returns: A :class:`~okcupyd.util.fetchable.Fetchable` of
:class:`~okcupyd.profile.Profile` instances.
:param session: A logged in session.
:type session: :class:`~okcupyd.session.Session`
:param location: A location string which will be used to filter results.
:param gender: The gender of the user performing the search.
:param keywords: A list or space delimeted string of words to search for.
:param order_by: The criteria to use for ordering results. expected_values:
'match', 'online', 'special_blend' |
def refresh(self, reload=False):
util.cached_property.bust_caches(self, excludes=('authcode'))
self.questions = self.question_fetchable()
if reload:
return self.profile_tree | :param reload: Make the request to return a new profile tree. This will
result in the caching of the profile_tree attribute. The
new profile_tree will be returned. |
def photo_infos(self):
from . import photo
pics_request = self._session.okc_get(
u'profile/{0}/album/0'.format(self.username),
)
pics_tree = html.fromstring(u'{0}{1}{2}'.format(
u'<div>', pics_request.json()['fulls'], u'</div>'
))
return [photo.Info.from_cdn_uri(uri)
for uri in self._photo_info_xpb.apply_(pics_tree)] | :returns: list of :class:`~okcupyd.photo.Info` instances for each photo
displayed on okcupid. |
def liked(self):
if self.is_logged_in_user: return False
classes = self._liked_xpb.one_(self.profile_tree).attrib['class'].split()
return 'liked' in classes | :returns: Whether or not the logged in user liked this profile |
def contacted(self):
try:
contacted_span = self._contacted_xpb.one_(self.profile_tree)
except:
return False
else:
timestamp = contacted_span.replace('Last contacted ', '')
return helpers.parse_date_updated(timestamp) | :retuns: A boolean indicating whether the logged in user has contacted
the owner of this profile. |
def responds(self):
contacted_text = self._contacted_xpb.\
get_text_(self.profile_tree).lower()
if 'contacted' not in contacted_text:
return contacted_text.strip().replace('replies ', '') | :returns: The frequency with which the user associated with this profile
responds to messages. |
def id(self):
if self.is_logged_in_user: return self._current_user_id
return int(self._id_xpb.one_(self.profile_tree)) | :returns: The id that okcupid.com associates with this profile. |
def age(self):
if self.is_logged_in_user:
# Retrieve the logged-in user's profile age
return int(self._user_age_xpb.get_text_(self.profile_tree).strip())
else:
# Retrieve a non logged-in user's profile age
return int(self._age_xpb.get_text_(self.profile_tree)) | :returns: The age of the user associated with this profile. |
def match_percentage(self):
return int(self._percentages_and_ratings_xpb.
div.with_class('matchgraph--match').
div.with_class('matchgraph-graph').
canvas.select_attribute_('data-pct').
one_(self.profile_tree)) | :returns: The match percentage of the logged in user and the user
associated with this object. |
def location(self):
if self.is_logged_in_user:
# Retrieve the logged-in user's profile location
return self._user_location_xpb.get_text_(self.profile_tree)
else:
# Retrieve a non logged-in user's profile location
return self._location_xpb.get_text_(self.profile_tree) | :returns: The location of the user associated with this profile. |
def message(self, message, thread_id=None):
return_value = helpers.Messager(self._session).send(
self.username, message, self.authcode, thread_id
)
self.refresh(reload=False)
return return_value | Message the user associated with this profile.
:param message: The message to send to this user.
:param thread_id: The id of the thread to respond to, if any. |
def rate(self, rating):
parameters = {
'voterid': self._current_user_id,
'target_userid': self.id,
'type': 'vote',
'cf': 'profile2',
'target_objectid': 0,
'vote_type': 'personality',
'score': rating,
}
response = self._session.okc_post('vote_handler',
data=parameters)
response_json = response.json()
log_function = log.info if response_json.get('status', False) \
else log.error
log_function(simplejson.dumps({'rate_response': response_json,
'sent_parameters': parameters,
'headers': dict(self._session.headers)}))
self.refresh(reload=False) | Rate this profile as the user that was logged in with the session
that this object was instantiated with.
:param rating: The rating to give this user. |
def find_question(self, question_id, question_fetchable=None):
question_fetchable = question_fetchable or self.questions
for question in question_fetchable:
if int(question.id) == int(question_id):
return question | :param question_id: The id of the question to search for
:param question_fetchable: The question fetchable to iterate through
if none is provided `self.questions`
will be used. |
def question_fetchable(self, **kwargs):
return util.Fetchable(QuestionFetcher(
self._session, self.username,
is_user=self.is_logged_in_user, **kwargs
)) | :returns: A :class:`~okcupyd.util.fetchable.Fetchable` instance that
contains objects representing the answers that the user
associated with this profile has given to okcupid.com match
questions. |
def authcode_get(self, path, **kwargs):
kwargs.setdefault('params', {})['authcode'] = self.authcode
return self._session.okc_get(path, **kwargs) | Perform an HTTP GET to okcupid.com using this profiles session
where the authcode is automatically added as a query parameter. |
def authcode_post(self, path, **kwargs):
kwargs.setdefault('data', {})['authcode'] = self.authcode
return self._session.okc_post(path, **kwargs) | Perform an HTTP POST to okcupid.com using this profiles session
where the authcode is automatically added as a form item. |
def arity_evaluation_checker(function):
is_class = inspect.isclass(function)
if is_class:
function = function.__init__
function_info = inspect.getargspec(function)
function_args = function_info.args
if is_class:
# This is to handle the fact that self will get passed in
# automatically.
function_args = function_args[1:]
def evaluation_checker(*args, **kwargs):
kwarg_keys = set(kwargs.keys())
if function_info.keywords is None:
acceptable_kwargs = function_args[len(args):]
# Make sure that we didn't get an argument we can't handle.
if not kwarg_keys.issubset(acceptable_kwargs):
TypeError("Unrecognized Arguments: {0}".format(
[key for key in kwarg_keys
if key not in acceptable_kwargs]
))
needed_args = function_args[len(args):]
if function_info.defaults:
needed_args = needed_args[:-len(function_info.defaults)]
return not needed_args or kwarg_keys.issuperset(needed_args)
return evaluation_checker | Build an evaluation checker that will return True when it is
guaranteed that all positional arguments have been accounted for. |
def rerecord(ctx, rest):
run('tox -e py27 -- --cassette-mode all --record --credentials {0} -s'
.format(rest), pty=True)
run('tox -e py27 -- --resave --scrub --credentials test_credentials {0} -s'
.format(rest), pty=True) | Rerecord tests. |
def login(
cls, username=None, password=None, requests_session=None,
rate_limit=None
):
requests_session = requests_session or requests.Session()
session = cls(requests_session, rate_limit)
# settings.USERNAME and settings.PASSWORD should not be made
# the defaults to their respective arguments because doing so
# would prevent this function from picking up any changes made
# to those values after import time.
username = username or settings.USERNAME
password = password or settings.PASSWORD
session.do_login(username, password)
return session | Get a session that has authenticated with okcupid.com.
If no username and password is supplied, the ones stored in
:class:`okcupyd.settings` will be used.
:param username: The username to log in with.
:type username: str
:param password: The password to log in with.
:type password: str
:param rate_limit: Average time in seconds to wait between requests to OKC.
:type rate_limit: float |
def getRoles(self):
# no need to retrieve all the entries from _get_paged_resources
# role raw data is very simple that contains no other links
self.log.info("Get all the roles in <ProjectArea %s>",
self)
roles_url = "/".join([self.rtc_obj.url,
"process/project-areas/%s/roles" % self.id])
resp = self.get(roles_url,
verify=False,
proxies=self.rtc_obj.proxies,
headers=self.rtc_obj.headers)
roles_list = list()
raw_data = xmltodict.parse(resp.content)
roles_raw = raw_data['jp06:roles']['jp06:role']
if not roles_raw:
self.log.warning("There are no roles in <ProjectArea %s>",
self)
return None
for role_raw in roles_raw:
role = Role(role_raw.get("jp06:url"),
self.rtc_obj,
raw_data=role_raw)
roles_list.append(role)
return roles_list | Get all :class:`rtcclient.models.Role` objects in this project
area
If no :class:`Roles` are retrieved, `None` is returned.
:return: a :class:`list` that contains all
:class:`rtcclient.models.Role` objects
:rtype: list |
def getRole(self, label):
if not isinstance(label, six.string_types) or not label:
excp_msg = "Please specify a valid role label"
self.log.error(excp_msg)
raise exception.BadValue(excp_msg)
roles = self.getRoles()
if roles is not None:
for role in roles:
if role.label == label:
self.log.info("Get <Role %s> in <ProjectArea %s>",
role, self)
return role
excp_msg = "No role's label is %s in <ProjectArea %s>" % (label,
self)
self.log.error(excp_msg)
raise exception.NotFound(excp_msg) | Get the :class:`rtcclient.models.Role` object by the label name
:param label: the label name of the role
:return: the :class:`rtcclient.models.Role` object
:rtype: :class:`rtcclient.models.Role` |
def getMember(self, email, returned_properties=None):
if not isinstance(email, six.string_types) or "@" not in email:
excp_msg = "Please specify a valid email address name"
self.log.error(excp_msg)
raise exception.BadValue(excp_msg)
self.log.debug("Try to get Member whose email is %s>", email)
members = self._getMembers(returned_properties=returned_properties,
email=email)
if members is not None:
member = members[0]
self.log.info("Get <Member %s> in <ProjectArea %s>",
member, self)
return member
excp_msg = "No member's email is %s in <ProjectArea %s>" % (email,
self)
self.log.error(excp_msg)
raise exception.NotFound(excp_msg) | Get the :class:`rtcclient.models.Member` object by the
email address
:param email: the email address (e.g. [email protected])
:param returned_properties: the returned properties that you want.
Refer to :class:`rtcclient.client.RTCClient` for more explanations
:return: the :class:`rtcclient.models.Member` object
:rtype: rtcclient.models.Member |
def getItemType(self, title, returned_properties=None):
if not isinstance(title, six.string_types) or not title:
excp_msg = "Please specify a valid email address name"
self.log.error(excp_msg)
raise exception.BadValue(excp_msg)
self.log.debug("Try to get <ItemType %s>", title)
itemtypes = self._getItemTypes(returned_properties=returned_properties,
title=title)
if itemtypes is not None:
itemtype = itemtypes[0]
self.log.info("Get <ItemType %s> in <ProjectArea %s>",
itemtype, self)
return itemtype
excp_msg = "No itemtype's name is %s in <ProjectArea %s>" % (title,
self)
self.log.error(excp_msg)
raise exception.NotFound(excp_msg) | Get the :class:`rtcclient.models.ItemType` object by the title
:param title: the title (e.g. Story/Epic/..)
:param returned_properties: the returned properties that you want.
Refer to :class:`rtcclient.client.RTCClient` for more explanations
:return: the :class:`rtcclient.models.ItemType` object
:rtype: rtcclient.models.ItemType |
def getAdministrator(self, email, returned_properties=None):
if not isinstance(email, six.string_types) or "@" not in email:
excp_msg = "Please specify a valid email address name"
self.log.error(excp_msg)
raise exception.BadValue(excp_msg)
self.log.debug("Try to get Administrator whose email is %s",
email)
rp = returned_properties
administrators = self._getAdministrators(returned_properties=rp,
email=email)
if administrators is not None:
administrator = administrators[0]
self.log.info("Get <Administrator %s> in <ProjectArea %s>",
administrator, self)
return administrator
msg = "No administrator's email is %s in <ProjectArea %s>" % (email,
self)
self.log.error(msg)
raise exception.NotFound(msg) | Get the :class:`rtcclient.models.Administrator` object
by the email address
:param email: the email address (e.g. [email protected])
:param returned_properties: the returned properties that you want.
Refer to :class:`rtcclient.client.RTCClient` for more explanations
:return: the :class:`rtcclient.models.Administrator` object
:rtype: rtcclient.models.Administrator |
def queryWorkitems(self, query_str, projectarea_id=None,
projectarea_name=None, returned_properties=None,
archived=False):
pa_id = (self.rtc_obj
._pre_get_resource(projectarea_id=projectarea_id,
projectarea_name=projectarea_name))
self.log.info("Start to query workitems with query string: %s",
query_str)
query_str = urlquote(query_str)
rp = returned_properties
return (self.rtc_obj
._get_paged_resources("Query",
projectarea_id=pa_id,
customized_attr=query_str,
page_size="100",
returned_properties=rp,
archived=archived)) | Query workitems with the query string in a certain
:class:`rtcclient.project_area.ProjectArea`
At least either of `projectarea_id` and `projectarea_name` is given
:param query_str: a valid query string
:param projectarea_id: the :class:`rtcclient.project_area.ProjectArea`
id
:param projectarea_name: the
:class:`rtcclient.project_area.ProjectArea` name
:param returned_properties: the returned properties that you want.
Refer to :class:`rtcclient.client.RTCClient` for more explanations
:param archived: (default is False) whether the
:class:`rtcclient.workitem.Workitem` is archived
:return: a :class:`list` that contains the queried
:class:`rtcclient.workitem.Workitem` objects
:rtype: list |
def getSavedQueriesByName(self, saved_query_name, projectarea_id=None,
projectarea_name=None, creator=None):
self.log.info("Start to fetch all saved queries with the name %s",
saved_query_name)
return self.getAllSavedQueries(projectarea_id=projectarea_id,
projectarea_name=projectarea_name,
creator=creator,
saved_query_name=saved_query_name) | Get all saved queries match the name created by somebody (optional)
in a certain project area (optional, either `projectarea_id`
or `projectarea_name` is needed if specified)
Note: only if `creator` is added as a member, the saved queries
can be found. Otherwise None will be returned.
WARNING: now the RTC server cannot correctly list all the saved queries
It seems to be a bug of RTC. Recommend using `runSavedQueryByUrl` to
query all the workitems if the query is saved.
:param saved_query_name: the saved query name
:param projectarea_id: the :class:`rtcclient.project_area.ProjectArea`
id
:param projectarea_name: the
:class:`rtcclient.project_area.ProjectArea` name
:param creator: the creator email address
:return: a :class:`list` that contains the saved queried
:class:`rtcclient.models.SavedQuery` objects
:rtype: list |
def getMySavedQueries(self, projectarea_id=None, projectarea_name=None,
saved_query_name=None):
self.log.info("Start to fetch my saved queries")
return self.getAllSavedQueries(projectarea_id=projectarea_id,
projectarea_name=projectarea_name,
creator=self.rtc_obj.username,
saved_query_name=saved_query_name) | Get all saved queries created by me in a certain project
area (optional, either `projectarea_id` or `projectarea_name` is
needed if specified)
Note: only if myself is added as a member, the saved queries
can be found. Otherwise None will be returned.
WARNING: now the RTC server cannot correctly list all the saved queries
It seems to be a bug of RTC. Recommend using `runSavedQueryByUrl` to
query all the workitems if the query is saved.
:param projectarea_id: the :class:`rtcclient.project_area.ProjectArea`
id
:param projectarea_name: the
:class:`rtcclient.project_area.ProjectArea` name
:param saved_query_name: the saved query name
:return: a :class:`list` that contains the saved queried
:class:`rtcclient.models.SavedQuery` objects
:rtype: list |
def runSavedQueryByUrl(self, saved_query_url, returned_properties=None):
try:
if "=" not in saved_query_url:
raise exception.BadValue()
saved_query_id = saved_query_url.split("=")[-1]
if not saved_query_id:
raise exception.BadValue()
except:
error_msg = "No saved query id is found in the url"
self.log.error(error_msg)
raise exception.BadValue(error_msg)
return self._runSavedQuery(saved_query_id,
returned_properties=returned_properties) | Query workitems using the saved query url
:param saved_query_url: the saved query url
:param returned_properties: the returned properties that you want.
Refer to :class:`rtcclient.client.RTCClient` for more explanations
:return: a :class:`list` that contains the queried
:class:`rtcclient.workitem.Workitem` objects
:rtype: list |
def runSavedQueryByID(self, saved_query_id, returned_properties=None):
if not isinstance(saved_query_id,
six.string_types) or not saved_query_id:
excp_msg = "Please specify a valid saved query id"
self.log.error(excp_msg)
raise exception.BadValue(excp_msg)
return self._runSavedQuery(saved_query_id,
returned_properties=returned_properties) | Query workitems using the saved query id
This saved query id can be obtained by below two methods:
1. :class:`rtcclient.models.SavedQuery` object (e.g.
mysavedquery.id)
2. your saved query url (e.g.
https://myrtc:9443/jazz/web/xxx#action=xxxx%id=_mGYe0CWgEeGofp83pg),
where the last "_mGYe0CWgEeGofp83pg" is the saved query id.
:param saved_query_id: the saved query id
:param returned_properties: the returned properties that you want.
Refer to :class:`rtcclient.client.RTCClient` for more explanations
:return: a :class:`list` that contains the queried
:class:`rtcclient.workitem.Workitem` objects
:rtype: list |
def runSavedQuery(self, saved_query_obj, returned_properties=None):
try:
saved_query_id = saved_query_obj.results.split("/")[-2]
except:
error_msg = "Cannot get the correct saved query id"
self.log.error(error_msg)
raise exception.RTCException(error_msg)
return self._runSavedQuery(saved_query_id,
returned_properties=returned_properties) | Query workitems using the :class:`rtcclient.models.SavedQuery`
object
:param saved_query_obj: the :class:`rtcclient.models.SavedQuery`
object
:param returned_properties: the returned properties that you want.
Refer to :class:`rtcclient.client.RTCClient` for more explanations
:return: a :class:`list` that contains the queried
:class:`rtcclient.workitem.Workitem` objects
:rtype: list |
def put(self, url, data=None, verify=False,
headers=None, proxies=None, timeout=60, **kwargs):
self.log.debug("Put a request to %s with data: %s",
url, data)
response = requests.put(url, data=data,
verify=verify, headers=headers,
proxies=proxies, timeout=timeout, **kwargs)
if response.status_code not in [200, 201]:
self.log.error('Failed PUT request at <%s> with response: %s',
url,
response.content)
response.raise_for_status()
return response | Sends a PUT request. Refactor from requests module
:param url: URL for the new :class:`Request` object.
:param data: (optional) Dictionary, bytes, or file-like object to
send in the body of the :class:`Request`.
:param verify: (optional) if ``True``, the SSL cert will be verified.
A CA_BUNDLE path can also be provided.
:param headers: (optional) Dictionary of HTTP Headers to send with
the :class:`Request`.
:param proxies: (optional) Dictionary mapping protocol to the URL of
the proxy.
:param timeout: (optional) How long to wait for the server to send data
before giving up, as a float, or a :ref:`(connect timeout, read
timeout) <timeouts>` tuple.
:type timeout: float or tuple
:param \*\*kwargs: Optional arguments that ``request`` takes.
:return: :class:`Response <Response>` object
:rtype: requests.Response |
def validate_url(cls, url):
if url is None:
return None
url = url.strip()
while url.endswith('/'):
url = url[:-1]
return url | Strip and trailing slash to validate a url
:param url: the url address
:return: the valid url address
:rtype: string |
def _initialize(self):
self.log.debug("Start initializing data from %s",
self.url)
resp = self.get(self.url,
verify=False,
proxies=self.rtc_obj.proxies,
headers=self.rtc_obj.headers)
self.__initialize(resp)
self.log.info("Finish the initialization for <%s %s>",
self.__class__.__name__, self) | Initialize the object from the request |
def __initialize(self, resp):
raw_data = xmltodict.parse(resp.content)
root_key = list(raw_data.keys())[0]
self.raw_data = raw_data.get(root_key)
self.__initializeFromRaw() | Initialize from the response |
def __initializeFromRaw(self):
for (key, value) in self.raw_data.items():
if key.startswith("@"):
# be compatible with IncludedInBuild
if "@oslc_cm:label" != key:
continue
attr = key.split(":")[-1].replace("-", "_")
attr_list = attr.split(".")
# ignore long attributes
if len(attr_list) > 1:
# attr = "_".join([attr_list[-2],
# attr_list[-1]])
continue
self.field_alias[attr] = key
if isinstance(value, OrderedDict):
value_text = value.get("#text")
if value_text is not None:
value = value_text
else:
# request detailed info using rdf:resource
value = list(value.values())[0]
try:
value = self.__get_rdf_resource_title(value)
except (exception.RTCException, Exception):
self.log.error("Unable to handle %s", value)
self.setattr(attr, value) | Initialze from raw data (OrderedDict) |
def relogin(self):
self.log.info("Cookie expires. Relogin to get a new cookie.")
self.headers = None
self.headers = self._get_headers()
self.log.debug("Successfully relogin.") | Relogin the RTC Server/Jazz when the token expires |
def getProjectAreas(self, archived=False, returned_properties=None):
return self._getProjectAreas(archived=archived,
returned_properties=returned_properties) | Get all :class:`rtcclient.project_area.ProjectArea` objects
If no :class:`rtcclient.project_area.ProjectArea` objects are
retrieved, `None` is returned.
:param archived: (default is False) whether the project area
is archived
:param returned_properties: the returned properties that you want.
Refer to :class:`rtcclient.client.RTCClient` for more explanations
:return: A :class:`list` that contains all the
:class:`rtcclient.project_area.ProjectArea` objects
:rtype: list |
def getProjectArea(self, projectarea_name, archived=False,
returned_properties=None):
if not isinstance(projectarea_name,
six.string_types) or not projectarea_name:
excp_msg = "Please specify a valid ProjectArea name"
self.log.error(excp_msg)
raise exception.BadValue(excp_msg)
self.log.debug("Try to get <ProjectArea %s>", projectarea_name)
rp = returned_properties
proj_areas = self._getProjectAreas(archived=archived,
returned_properties=rp,
projectarea_name=projectarea_name)
if proj_areas is not None:
proj_area = proj_areas[0]
self.log.info("Find <ProjectArea %s>", proj_area)
return proj_area
self.log.error("No ProjectArea named %s", projectarea_name)
raise exception.NotFound("No ProjectArea named %s" % projectarea_name) | Get :class:`rtcclient.project_area.ProjectArea` object by its name
:param projectarea_name: the project area name
:param archived: (default is False) whether the project area
is archived
:param returned_properties: the returned properties that you want.
Refer to :class:`rtcclient.client.RTCClient` for more explanations
:return: the :class:`rtcclient.project_area.ProjectArea` object
:rtype: rtcclient.project_area.ProjectArea |
def getProjectAreaByID(self, projectarea_id, archived=False,
returned_properties=None):
if not isinstance(projectarea_id,
six.string_types) or not projectarea_id:
excp_msg = "Please specify a valid ProjectArea ID"
self.log.error(excp_msg)
raise exception.BadValue(excp_msg)
self.log.debug("Try to get <ProjectArea> by its id: %s",
projectarea_id)
rp = returned_properties
proj_areas = self._getProjectAreas(archived=archived,
returned_properties=rp,
projectarea_id=projectarea_id)
if proj_areas is not None:
proj_area = proj_areas[0]
self.log.info("Find <ProjectArea %s>", proj_area)
return proj_area
self.log.error("No ProjectArea's ID is %s", projectarea_id)
raise exception.NotFound("No ProjectArea's ID is %s" % projectarea_id) | Get :class:`rtcclient.project_area.ProjectArea` object by its id
:param projectarea_id: the :class:`rtcclient.project_area.ProjectArea`
id
:param archived: (default is False) whether the project area
is archived
:param returned_properties: the returned properties that you want.
Refer to :class:`rtcclient.client.RTCClient` for more explanations
:return: the :class:`rtcclient.project_area.ProjectArea` object
:rtype: rtcclient.project_area.ProjectArea |
def getProjectAreaID(self, projectarea_name, archived=False):
self.log.debug("Get the ProjectArea id by its name: %s",
projectarea_name)
proj_area = self.getProjectArea(projectarea_name,
archived=archived)
if proj_area:
return proj_area.id
raise exception.NotFound("No ProjectArea named %s" % projectarea_name) | Get :class:`rtcclient.project_area.ProjectArea` id by its name
:param projectarea_name: the project area name
:param archived: (default is False) whether the project area
is archived
:return: the :class:`string` object
:rtype: string |
def getProjectAreaIDs(self, projectarea_name=None, archived=False):
projectarea_ids = list()
if projectarea_name and isinstance(projectarea_name,
six.string_types):
projectarea_id = self.getProjectAreaID(projectarea_name,
archived=archived)
projectarea_ids.append(projectarea_id)
elif projectarea_name is None:
projectareas = self.getProjectAreas(archived=archived)
if projectareas is None:
return None
projectarea_ids = [proj_area.id for proj_area in projectareas]
else:
error_msg = "Invalid ProjectArea name: [%s]" % projectarea_name
self.log.error(error_msg)
raise exception.BadValue(error_msg)
return projectarea_ids | Get all :class:`rtcclient.project_area.ProjectArea` id(s)
by project area name
If `projectarea_name` is `None`, all the
:class:`rtcclient.project_area.ProjectArea` id(s) will be returned.
:param projectarea_name: the project area name
:param archived: (default is False) whether the project area
is archived
:return: a :class:`list` that contains all the :class:`ProjectArea` ids
:rtype: list |
def checkProjectAreaID(self, projectarea_id, archived=False):
self.log.debug("Check the validity of the ProjectArea id: %s",
projectarea_id)
proj_areas = self._getProjectAreas(archived=archived,
projectarea_id=projectarea_id)
if proj_areas is not None:
proj_area = proj_areas[0]
self.log.info("Find <ProjectArea %s> whose id is: %s",
proj_area,
projectarea_id)
return True
self.log.error("No ProjectArea whose id is: %s",
projectarea_id)
return False | Check the validity of :class:`rtcclient.project_area.ProjectArea` id
:param projectarea_id: the :class:`rtcclient.project_area.ProjectArea`
id
:param archived: (default is False) whether the project area is
archived
:return: `True` or `False`
:rtype: bool |
def getTeamArea(self, teamarea_name, projectarea_id=None,
projectarea_name=None, archived=False,
returned_properties=None):
if not isinstance(teamarea_name,
six.string_types) or not teamarea_name:
excp_msg = "Please specify a valid TeamArea name"
self.log.error(excp_msg)
raise exception.BadValue(excp_msg)
self.log.debug("Try to get <TeamArea %s>", teamarea_name)
teamareas = self._getTeamAreas(projectarea_id=projectarea_id,
projectarea_name=projectarea_name,
archived=archived,
returned_properties=returned_properties,
teamarea_name=teamarea_name)
if teamareas is not None:
teamarea = teamareas[0]
self.log.info("Find <TeamArea %s>", teamarea)
return teamarea
self.log.error("No TeamArea named %s", teamarea_name)
raise exception.NotFound("No TeamArea named %s" % teamarea_name) | Get :class:`rtcclient.models.TeamArea` object by its name
If `projectarea_id` or `projectarea_name` is
specified, then the matched :class:`rtcclient.models.TeamArea`
in that project area will be returned.
Otherwise, only return the first found
:class:`rtcclient.models.TeamArea` with that name.
:param teamarea_name: the team area name
:param projectarea_id: the :class:`rtcclient.project_area.ProjectArea`
id
:param projectarea_name: the project area name
:param archived: (default is False) whether the team area
is archived
:param returned_properties: the returned properties that you want.
Refer to :class:`rtcclient.client.RTCClient` for more explanations
:return: the :class:`rtcclient.models.TeamArea` object
:rtype: rtcclient.models.TeamArea |
def getTeamAreas(self, projectarea_id=None, projectarea_name=None,
archived=False, returned_properties=None):
return self._getTeamAreas(projectarea_id=projectarea_id,
projectarea_name=projectarea_name,
archived=archived,
returned_properties=returned_properties) | Get all :class:`rtcclient.models.TeamArea` objects by
project area id or name
If both `projectarea_id` and `projectarea_name` are `None`,
all team areas in all project areas will be returned.
If no :class:`rtcclient.models.TeamArea` objects are retrieved,
`None` is returned.
:param projectarea_id: the :class:`rtcclient.project_area.ProjectArea`
id
:param projectarea_name: the project area name
:param archived: (default is False) whether the team areas
are archived
:param returned_properties: the returned properties that you want.
Refer to :class:`rtcclient.client.RTCClient` for more explanations
:return: a :class:`list` that contains all the
:class:`rtcclient.models.TeamArea` objects
:rtype: list |
def getPlannedFor(self, plannedfor_name, projectarea_id=None,
projectarea_name=None, archived=False,
returned_properties=None):
if not isinstance(plannedfor_name,
six.string_types) or not plannedfor_name:
excp_msg = "Please specify a valid PlannedFor name"
self.log.error(excp_msg)
raise exception.BadValue(excp_msg)
self.log.debug("Try to get <PlannedFor %s>", plannedfor_name)
rp = returned_properties
plannedfors = self._getPlannedFors(projectarea_id=projectarea_id,
projectarea_name=projectarea_name,
archived=archived,
returned_properties=rp,
plannedfor_name=plannedfor_name)
if plannedfors is not None:
plannedfor = plannedfors[0]
self.log.info("Find <PlannedFor %s>", plannedfor)
return plannedfor
self.log.error("No PlannedFor named %s", plannedfor_name)
raise exception.NotFound("No PlannedFor named %s" % plannedfor_name) | Get :class:`rtcclient.models.PlannedFor` object by its name
:param plannedfor_name: the plannedfor name
:param projectarea_id: the :class:`rtcclient.project_area.ProjectArea`
id
:param projectarea_name: the project area name
:param archived: (default is False) whether the plannedfor
is archived
:param returned_properties: the returned properties that you want.
Refer to :class:`rtcclient.client.RTCClient` for more explanations
:return: the :class:`rtcclient.models.PlannedFor` object
:rtype: rtcclient.models.PlannedFor |
def getPlannedFors(self, projectarea_id=None, projectarea_name=None,
archived=False, returned_properties=None):
return self._getPlannedFors(projectarea_id=projectarea_id,
projectarea_name=projectarea_name,
archived=archived,
returned_properties=returned_properties) | Get all :class:`rtcclient.models.PlannedFor` objects by
project area id or name
If both `projectarea_id` and `projectarea_name` are None,
all the plannedfors in all project areas will be returned.
If no :class:`rtcclient.models.PlannedFor` objecs are retrieved,
`None` is returned.
:param projectarea_id: the :class:`rtcclient.project_area.ProjectArea`
id
:param projectarea_name: the project area name
:param archived: (default is False) whether the plannedfors
are archived
:param returned_properties: the returned properties that you want.
Refer to :class:`rtcclient.client.RTCClient` for more explanations
:return: a :class:`list` that contains all the
:class:`rtcclient.models.PlannedFor` objects
:rtype: list |
def getSeverity(self, severity_name, projectarea_id=None,
projectarea_name=None):
self.log.debug("Try to get <Severity %s>", severity_name)
if not isinstance(severity_name,
six.string_types) or not severity_name:
excp_msg = "Please specify a valid Severity name"
self.log.error(excp_msg)
raise exception.BadValue(excp_msg)
severities = self._getSeverities(projectarea_id=projectarea_id,
projectarea_name=projectarea_name,
severity_name=severity_name)
if severities is not None:
severity = severities[0]
self.log.info("Find <Severity %s>", severity)
return severity
self.log.error("No Severity named %s", severity_name)
raise exception.NotFound("No Severity named %s" % severity_name) | Get :class:`rtcclient.models.Severity` object by its name
At least either of `projectarea_id` and `projectarea_name` is given
:param severity_name: the severity name
:param projectarea_id: the :class:`rtcclient.project_area.ProjectArea`
id
:param projectarea_name: the project area name
:return: the :class:`rtcclient.models.Severity` object
:rtype: rtcclient.models.Severity |
def getSeverities(self, projectarea_id=None, projectarea_name=None):
return self._getSeverities(projectarea_id=projectarea_id,
projectarea_name=projectarea_name) | Get all :class:`rtcclient.models.Severity` objects by
project area id or name
At least either of `projectarea_id` and `projectarea_name` is given
If no :class:`rtcclient.models.Severity` is retrieved,
`None` is returned.
:param projectarea_id: the :class:`rtcclient.project_area.ProjectArea`
id
:param projectarea_name: the project area name
:return: a :class:`list` that contains all the
:class:`rtcclient.models.Severity` objects
:rtype: list |
def getPriority(self, priority_name, projectarea_id=None,
projectarea_name=None):
self.log.debug("Try to get <Priority %s>", priority_name)
if not isinstance(priority_name,
six.string_types) or not priority_name:
excp_msg = "Please specify a valid Priority name"
self.log.error(excp_msg)
raise exception.BadValue(excp_msg)
priorities = self._getPriorities(projectarea_id=projectarea_id,
projectarea_name=projectarea_name,
priority_name=priority_name)
if priorities is not None:
priority = priorities[0]
self.log.info("Find <Priority %s>", priority)
return priority
self.log.error("No Priority named %s", priority_name)
raise exception.NotFound("No Priority named %s" % priority_name) | Get :class:`rtcclient.models.Priority` object by its name
At least either of `projectarea_id` and `projectarea_name` is given
:param priority_name: the priority name
:param projectarea_id: the :class:`rtcclient.project_area.ProjectArea`
id
:param projectarea_name: the project area name
:return: the :class:`rtcclient.models.Priority` object
:rtype: rtcclient.models.Priority |
def getPriorities(self, projectarea_id=None, projectarea_name=None):
return self._getPriorities(projectarea_id=projectarea_id,
projectarea_name=projectarea_name) | Get all :class:`rtcclient.models.Priority` objects by
project area id or name
At least either of `projectarea_id` and `projectarea_name` is given.
If no :class:`rtcclient.models.Priority` is retrieved,
`None` is returned.
:param projectarea_id: the :class:`rtcclient.project_area.ProjectArea`
id
:param projectarea_name: the project area name
:return: a :class:`list` contains all the
:class:`rtcclient.models.Priority` objects
:rtype: list |
def getFoundIn(self, foundin_name, projectarea_id=None,
projectarea_name=None, archived=False):
self.log.debug("Try to get <FoundIn %s>", foundin_name)
if not isinstance(foundin_name,
six.string_types) or not foundin_name:
excp_msg = "Please specify a valid PlannedFor name"
self.log.error(excp_msg)
raise exception.BadValue(excp_msg)
foundins = self._getFoundIns(projectarea_id=projectarea_id,
projectarea_name=projectarea_name,
archived=archived,
foundin_name=foundin_name)
if foundins is not None:
foundin = foundins[0]
self.log.info("Find <FoundIn %s>", foundin)
return foundin
self.log.error("No FoundIn named %s", foundin_name)
raise exception.NotFound("No FoundIn named %s" % foundin_name) | Get :class:`rtcclient.models.FoundIn` object by its name
:param foundin_name: the foundin name
:param projectarea_id: the :class:`rtcclient.project_area.ProjectArea`
id
:param projectarea_name: the project area name
:param archived: (default is False) whether the foundin is archived
:return: the :class:`rtcclient.models.FoundIn` object
:rtype: rtcclient.models.FoundIn |
def getFoundIns(self, projectarea_id=None, projectarea_name=None,
archived=False):
return self._getFoundIns(projectarea_id=projectarea_id,
projectarea_name=projectarea_name,
archived=archived) | Get all :class:`rtcclient.models.FoundIn` objects by
project area id or name
If both `projectarea_id` and `projectarea_name` are `None`,
all the foundins in all project areas will be returned.
If no :class:`rtcclient.models.FoundIn` objects are retrieved,
`None` is returned.
:param projectarea_id: the :class:`rtcclient.project_area.ProjectArea`
id
:param projectarea_name: the project area name
:param archived: (default is False) whether the foundins are archived
:return: a :class:`list` that contains all the
:class:`rtcclient.models.FoundIn` objects
:rtype: list |
def getFiledAgainst(self, filedagainst_name, projectarea_id=None,
projectarea_name=None, archived=False):
self.log.debug("Try to get <FiledAgainst %s>", filedagainst_name)
if not isinstance(filedagainst_name,
six.string_types) or not filedagainst_name:
excp_msg = "Please specify a valid FiledAgainst name"
self.log.error(excp_msg)
raise exception.BadValue(excp_msg)
fas = self._getFiledAgainsts(projectarea_id=projectarea_id,
projectarea_name=projectarea_name,
archived=archived,
filedagainst_name=filedagainst_name)
if fas is not None:
filedagainst = fas[0]
self.log.info("Find <FiledAgainst %s>", filedagainst)
return filedagainst
error_msg = "No FiledAgainst named %s" % filedagainst_name
self.log.error(error_msg)
raise exception.NotFound(error_msg) | Get :class:`rtcclient.models.FiledAgainst` object by its name
:param filedagainst_name: the filedagainst name
:param projectarea_id: the :class:`rtcclient.project_area.ProjectArea`
id
:param projectarea_name: the project area name
:param archived: (default is False) whether the filedagainst is
archived
:return: the :class:`rtcclient.models.FiledAgainst` object
:rtype: rtcclient.models.FiledAgainst |
def getFiledAgainsts(self, projectarea_id=None, projectarea_name=None,
archived=False):
return self._getFiledAgainsts(projectarea_id=projectarea_id,
projectarea_name=projectarea_name,
archived=archived) | Get all :class:`rtcclient.models.FiledAgainst` objects by
project area id or name
If both `projectarea_id` and `projectarea_name` are `None`,
all the filedagainsts in all project areas will be returned.
If no :class:`rtcclient.models.FiledAgainst` objects are retrieved,
`None` is returned.
:param projectarea_id: the :class:`rtcclient.project_area.ProjectArea`
id
:param projectarea_name: the project area name
:param archived: (default is False) whether the filedagainsts are
archived
:return: a :class:`list` that contains all the
:class:`rtcclient.models.FiledAgainst` objects
:rtype: list |
def getTemplate(self, copied_from, template_name=None,
template_folder=None, keep=False, encoding="UTF-8"):
return self.templater.getTemplate(copied_from,
template_name=template_name,
template_folder=template_folder,
keep=keep,
encoding=encoding) | Get template from some to-be-copied workitems
More details, please refer to
:class:`rtcclient.template.Templater.getTemplate` |
def getTemplates(self, workitems, template_folder=None,
template_names=None, keep=False, encoding="UTF-8"):
self.templater.getTemplates(workitems,
template_folder=template_folder,
template_names=template_names,
keep=keep,
encoding=encoding) | Get templates from a group of to-be-copied workitems
and write them to files named after the names in `template_names`
respectively.
More details, please refer to
:class:`rtcclient.template.Templater.getTemplates` |
def listFieldsFromWorkitem(self, copied_from, keep=False):
return self.templater.listFieldsFromWorkitem(copied_from,
keep=keep) | List all the attributes to be rendered directly from some
to-be-copied workitems
More details, please refer to
:class:`rtcclient.template.Templater.listFieldsFromWorkitem` |
def getWorkitem(self, workitem_id, returned_properties=None):
try:
if isinstance(workitem_id, bool):
raise ValueError("Invalid Workitem id")
if isinstance(workitem_id, six.string_types):
workitem_id = int(workitem_id)
if not isinstance(workitem_id, int):
raise ValueError("Invalid Workitem id")
workitem_url = "/".join([self.url,
"oslc/workitems/%s" % workitem_id])
rp = self._validate_returned_properties(returned_properties)
if rp is not None:
req_url = "".join([workitem_url,
"?oslc_cm.properties=",
urlquote(rp)])
else:
req_url = workitem_url
resp = self.get(req_url,
verify=False,
proxies=self.proxies,
headers=self.headers)
raw_data = xmltodict.parse(resp.content)
workitem_raw = raw_data["oslc_cm:ChangeRequest"]
return Workitem(workitem_url,
self,
workitem_id=workitem_id,
raw_data=workitem_raw)
except ValueError:
excp_msg = "Please input a valid workitem id"
self.log.error(excp_msg)
raise exception.BadValue(excp_msg)
except Exception as excp:
self.log.error(excp)
raise exception.NotFound("Not found <Workitem %s>" % workitem_id) | Get :class:`rtcclient.workitem.Workitem` object by its id/number
:param workitem_id: the workitem id/number
(integer or equivalent string)
:param returned_properties: the returned properties that you want.
Refer to :class:`rtcclient.client.RTCClient` for more explanations
:return: the :class:`rtcclient.workitem.Workitem` object
:rtype: rtcclient.workitem.Workitem |
def copyWorkitem(self, copied_from, title=None, description=None,
prefix=None):
copied_wi = self.getWorkitem(copied_from)
if title is None:
title = copied_wi.title
if prefix is not None:
title = prefix + title
if description is None:
description = copied_wi.description
if prefix is not None:
description = prefix + description
self.log.info("Start to create a new <Workitem>, copied from ",
"<Workitem %s>", copied_from)
wi_url_post = "/".join([self.url,
"oslc/contexts/%s" % copied_wi.contextId,
"workitems",
"%s" % copied_wi.type.split("/")[-1]])
wi_raw = self.templater.renderFromWorkitem(copied_from,
keep=True,
encoding="UTF-8",
title=title,
description=description)
return self._createWorkitem(wi_url_post, wi_raw) | Create a workitem by copying from an existing one
:param copied_from: the to-be-copied workitem id
:param title: the new workitem title/summary.
If `None`, will copy that from a to-be-copied workitem
:param description: the new workitem description.
If `None`, will copy that from a to-be-copied workitem
:param prefix: used to add a prefix to the copied title and
description
:return: the :class:`rtcclient.workitem.Workitem` object
:rtype: rtcclient.workitem.Workitem |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.