desc
stringlengths
3
26.7k
decl
stringlengths
11
7.89k
bodies
stringlengths
8
553k
''
@excmd def do_touch(self, arg=None):
(res, resp) = ([], None) if (hasattr(self, 'target_url') and self.target_url): resp = self.head(self.target_url) res.append(('HEAD %s - %s' % (self.target_url, resp.status_code))) for (key, val) in resp.headers.items(): res.append(('Header: %s -- %s' % (key,...
''
@excmd def do_probe(self, arg=None):
res = self.probe() if (not res): self.log.info('Target is vulnerable. Safe to proceed.') else: self.log.error('Target appears not to be vulnerable.') self.log.error(('Reason given: %s' % res))
''
@excmd def do_survey(self, arg=None):
res = self.survey() if (not res): self.log.info('Survey complete.') else: self.log.error('Survey failed.') self.log.error(('Reason given: %s' % res))
''
@excmd def do_exploit(self, arg=None):
res = self.exploit() if (not res): self.log.info('Exploit complete. Got root?') else: self.log.error('Exploit failed') self.log.error(('Reason given: %s' % res))
''
@excmd def do_clean(self, arg=None):
res = self.clean() if (not res): self.log.info('Cleanup completed successfully.') else: self.log.error(('Cleanup failed: %s' % res))
''
def do_show(self, args=None):
if args: args = args.strip() try: print ('%s = %s :: %s' % (args, self.ns.__dict__[args], self.action_help[args])) except KeyError: self.log.warning('Variable does not exist.') else: print 'Exploit variables' print '========...
''
def do_set(self, args):
if args: args = split(args) if (len(args) >= 2): if (args[0] in self.ns.__dict__): try: self._update_var(args[0], args[1]) except ArgumentTypeError as e: self.log.warning(('Setting %s failed: %s' % (args[0],...
''
def do_guided(self, args=None):
for cmd in self.excmds: if (cmd in dir(self)): res = raw_input(('About to execute %s. Continue, skip, interact, or quit? (C/s/i/q) ' % cmd)) if (res.lower() == 's'): continue elif (res.lower() == 'q'): return ...
''
def request(self, mthd, url, **kwargs):
quiet = False if ('quiet' in kwargs): quiet = kwargs['quiet'] del kwargs['quiet'] if quiet: l = logging.getLogger('fosho.requests.packages.urllib3.connectionpool') old = l.getEffectiveLevel() l.setLevel(logging.ERROR) if (not self.multi): url = (self.targe...
''
def prompt_for_settings(self, names):
for name in names: try: res = getattr(self, ('_get_' + name))() except AttributeError as e: res = None if (not hasattr(self.ns, name)): self.ns.__dict__[name] = None if ((not self.ask) and (not res)): res = self.ns.__dict__[name] ...
''
def continue_prompt(self, msg, default='n'):
other = ('y' if (default == 'n') else 'n') opts = '(y/n)'.replace(default, default.upper()) res = raw_input(('%s %s ' % (msg, opts))) if (res.lower() != 'y'): try: self._do_finish() except: pass sys.exit('Stopping exploit...')
''
def get_etag(self, path):
res = self.head(path) return self._parse_etag(res.headers['etag'])
''
def _parse_etag(self, etag):
return (etag, 'Could not parse etag')
''
def _apply_settings(self):
for (key, val) in self.ns.__dict__.items(): if (key in ['quiet', 'debug']): level = logging.DEBUG if self.ns.quiet: level = logging.INFO self.log.setLevel(level) logging.getLogger('fosho.requests.packages.urllib3.connectionpool').setLevel(level...
''
def _update_var(self, key, val):
if (val == 'False'): val = False cur = self.ns.__dict__[key] if (cur == None): cur = '' t = type(self.ns.__dict__[key]) if ((key in self.action_types) and self.action_types[key]): t = self.action_types[key] try: self.ns.__dict__[key] = t(val) except TypeError:...
''
@classmethod def add_args(cur, cls):
parser = ArgumentParser(prog=sys.argv[0], description=('%s %s - %s' % (cls.name, cls.version, cls.desc))) subparsers = parser.add_subparsers(help='Exploit Commands') if cls.interact: inparse = subparsers.add_parser('interact', help='Run tool in interactive mode') inpa...
'Adds labels to an ad object. Args: labels: A list of ad label IDs Returns: The FacebookResponse object.'
def add_labels(self, labels=None):
return self.get_api_assured().call('POST', (self.get_id_assured(), 'adlabels'), params={'adlabels': [{'id': label} for label in labels]})
'Remove labels to an ad object. Args: labels: A list of ad label IDs Returns: The FacebookResponse object.'
def remove_labels(self, labels=None):
return self.get_api_assured().call('DELETE', (self.get_id_assured(), 'adlabels'), params={'adlabels': [{'id': label} for label in labels]})
'Initialize an ObjectParser. To Initialize, you need to provide either a resuse_object, target_class, or an custom_parse_method. Args: api: FacebookAdsApi object. target_class (optional): The expected return object type. reuse_object (optional): Reuse existing object to populate response. custom_parse_method (optional)...
def __init__(self, api=None, target_class=None, reuse_object=None, custom_parse_method=None):
if (not any([target_class, (reuse_object is not None), custom_parse_method])): raise FacebookBadObjectError(('Must specify either target class calling object' + 'or custom parse method for parser')) self._reuse_object = reuse_object self._target_class = target_class ...
'Initializes a CRUD object. Args: fbid (optional): The id of the object ont the Graph. parent_id (optional): The id of the object\'s parent. api (optional): An api object which all calls will go through. If an api object is not specified, api calls will revert to going through the default api.'
def __init__(self, fbid=None, parent_id=None, api=None):
super(AbstractCrudObject, self).__init__() self._api = (api or FacebookAdsApi.get_default_api()) self._changes = {} if (parent_id is not None): warning_message = 'parent_id as a parameter of constructor is being deprecated.' logging.warning(warning_message) se...
'Sets an item in this CRUD object while maintaining a changelog.'
def __setitem__(self, key, value):
if ((key not in self._data) or (self._data[key] != value)): self._changes[key] = value super(AbstractCrudObject, self).__setitem__(key, value) if ('_setitem_trigger' in dir(self)): self._setitem_trigger(key, value) return self
'Two objects are the same if they have the same fbid.'
def __eq__(self, other):
return (isinstance(other, self.__class__) and self.get_id() and other.get_id() and (self.get_id() == other.get_id()))
'Returns the object\'s fbid if set. Else, it returns None.'
def get_id(self):
return self[self.Field.id]
'Returns the object\'s parent\'s id.'
def get_parent_id(self):
return (self._parent_id or FacebookAdsApi.get_default_account_id())
'Returns the api associated with the object.'
def get_api(self):
return self._api
'Returns the fbid of the object. Raises: FacebookBadObjectError if the object does not have an id.'
def get_id_assured(self):
if (not self.get(self.Field.id)): raise FacebookBadObjectError(('%s object needs an id for this operation.' % self.__class__.__name__)) return self.get_id()
'Returns the object\'s parent\'s fbid. Raises: FacebookBadObjectError if the object does not have a parent id.'
def get_parent_id_assured(self):
if (not self.get_parent_id()): raise FacebookBadObjectError(('%s object needs a parent_id for this operation.' % self.__class__.__name__)) return self.get_parent_id()
'Returns the fbid of the object. Raises: FacebookBadObjectError if get_api returns None.'
def get_api_assured(self):
api = self.get_api() if (not api): raise FacebookBadObjectError(('%s does not yet have an associated api object.\nDid you forget to instantiate an API session with: FacebookAdsApi.init(app_id, app_secret, access_token)' % self.__class__.__name__))...
'Sets object\'s data as if it were read from the server. Warning: Does not log changes.'
def _set_data(self, data):
for key in map(str, data): self[key] = data[key] self._changes.pop(key, None) self._json = data return self
'Returns a dictionary of property names mapped to their values for properties modified from their original values.'
def export_changed_data(self):
return self.export_value(self._changes)
'Deprecated. Use export_all_data() or export_changed_data() instead.'
def export_data(self):
return self.export_changed_data()
'Clears the object\'s fbid.'
def clear_id(self):
del self[self.Field.id] return self
'Returns the node\'s relative path as a tuple of tokens.'
def get_node_path(self):
return (self.get_id_assured(),)
'Returns the node\'s path as a tuple.'
def get_node_path_string(self):
return '/'.join(self.get_node_path())
'Creates the object by calling the API. Args: batch (optional): A FacebookAdsApiBatch object. If specified, the call will be added to the batch. params (optional): A mapping of request parameters where a key is the parameter name and its value is a string or an object which can be JSON-encoded. files (optional): An opt...
def remote_create(self, batch=None, failure=None, files=None, params=None, success=None, api_version=None):
if self.get_id(): raise FacebookBadObjectError(('This %s object was already created.' % self.__class__.__name__)) if (not ('get_endpoint' in dir(self))): raise TypeError(('Cannot create object of type %s.' % self.__class__.__name__)) params = ({} if (not params)...
'Reads the object by calling the API. Args: batch (optional): A FacebookAdsApiBatch object. If specified, the call will be added to the batch. fields (optional): A list of fields to read. params (optional): A mapping of request parameters where a key is the parameter name and its value is a string or an object which ca...
def remote_read(self, batch=None, failure=None, fields=None, params=None, success=None, api_version=None):
params = dict((params or {})) if hasattr(self, 'api_get'): request = self.api_get(pending=True) else: request = FacebookRequest(node_id=self.get_id_assured(), method='GET', endpoint='/', api=self._api, target_class=self.__class__, response_parser=ObjectParser(reuse_object=self)) request....
'Updates the object by calling the API with only the changes recorded. Args: batch (optional): A FacebookAdsApiBatch object. If specified, the call will be added to the batch. params (optional): A mapping of request parameters where a key is the parameter name and its value is a string or an object which can be JSON-en...
def remote_update(self, batch=None, failure=None, files=None, params=None, success=None, api_version=None):
params = ({} if (not params) else params.copy()) params.update(self.export_changed_data()) self._set_data(params) if hasattr(self, 'api_update'): request = self.api_update(pending=True) else: request = FacebookRequest(node_id=self.get_id_assured(), method='POST', endpoint='/', api=se...
'Deletes the object by calling the API with the DELETE http method. Args: batch (optional): A FacebookAdsApiBatch object. If specified, the call will be added to the batch. params (optional): A mapping of request parameters where a key is the parameter name and its value is a string or an object which can be JSON-encod...
def remote_delete(self, batch=None, failure=None, params=None, success=None, api_version=None):
if hasattr(self, 'api_delete'): request = self.api_delete(pending=True) else: request = FacebookRequest(node_id=self.get_id_assured(), method='DELETE', endpoint='/', api=self._api) request.add_params(params) if (batch is not None): def callback_success(response): self...
'Calls remote_create method if object has not been created. Else, calls the remote_update method.'
def remote_save(self, *args, **kwargs):
if self.get_id(): return self.remote_update(*args, **kwargs) else: return self.remote_create(*args, **kwargs)
'Returns Cursor with argument self as source_object and the rest as given __init__ arguments. Note: list(iterate_edge(...)) can prefetch all the objects.'
def iterate_edge(self, target_objects_class, fields=None, params=None, fetch_first_page=True, include_summary=True, endpoint=None):
source_object = self cursor = Cursor(source_object, target_objects_class, fields=fields, params=params, include_summary=include_summary, endpoint=endpoint) if fetch_first_page: cursor.load_next_page() return cursor
'Returns first object when iterating over Cursor with argument self as source_object and the rest as given __init__ arguments.'
def edge_object(self, target_objects_class, fields=None, params=None, endpoint=None):
params = ({} if (not params) else params.copy()) params['limit'] = '1' for obj in self.iterate_edge(target_objects_class, fields=fields, params=params, endpoint=endpoint): return obj return None
'Returns all leadgen forms on the page'
def get_leadgen_forms(self, fields=None, params=None):
return self.iterate_edge(LeadgenForm, fields, params, endpoint='leadgen_forms')
'Returns all events on the page'
def get_events(self, fields=None, params=None):
return self.iterate_edge(Event, fields, params, endpoint='events')
'Returns info for fields that use enum values Should be implemented in subclasses'
@classmethod def _get_field_enum_info(cls):
return {}
'Returns the endpoint name. Raises: NotImplementedError if the method is not implemented in a class that derives from this abstract class.'
@classmethod def get_endpoint(cls):
raise NotImplementedError(('%s must have implemented get_endpoint.' % cls.__name__))
'Returns the class\'s list of default fields to read.'
@classmethod def get_default_read_fields(cls):
return cls._default_read_fields
'Sets the class\'s list of default fields to read. Args: fields: list of field names to read by default without specifying them explicitly during a read operation either via EdgeIterator or via AbstractCrudObject.read.'
@classmethod def set_default_read_fields(cls, fields):
cls._default_read_fields = fields
'Applies fields to params in a consistent manner.'
@classmethod def _assign_fields_to_params(cls, fields, params):
if (fields is None): fields = cls.get_default_read_fields() if fields: params['fields'] = ','.join(fields)
'For an AbstractObject, we do not need to keep history.'
def set_data(self, data):
self._set_data(data)
'Deprecated. Use export_all_data() instead.'
def export_data(self):
return self.export_all_data()
'Returns the preview html.'
def get_html(self):
return self[self.Field.body]
'`data` may have a different structure depending if you\'re creating new AdImages or iterating over existing ones using something like AdAccount.get_ad_images(). While reading existing images, _set_data from AbstractCrudObject handles everything correctly, but we need to treat the remote_create case. remote_create samp...
def _set_data(self, data):
if ('images' in data): (_, data) = data['images'].popitem() for key in map(str, data): self._data[key] = data[key] self._changes.pop(key, None) self._data[self.Field.id] = ('%s:%s' % (self.get_parent_id_assured()[4:], self[self.Field.hash])) return self el...
'Uploads filename and creates the AdImage object from it. It has same arguments as AbstractCrudObject.remote_create except it does not have the files argument but requires the \'filename\' property to be defined.'
def remote_create(self, batch=None, failure=None, files=None, params=None, success=None, api_version=None):
if (not self[self.Field.filename]): raise FacebookBadObjectError('AdImage required a filename to be defined.') filename = self[self.Field.filename] with open(filename, 'rb') as open_file: return_val = AbstractCrudObject.remote_create(self, files={filename: open_file}, batch...
'Returns the image hash to which AdCreative\'s can refer.'
def get_hash(self):
return self[self.Field.hash]
'Normalize the value based on the key'
@classmethod def normalize_key(cls, key_name, key_value=None):
if (key_value is None): return key_value if ((key_name == cls.Schema.MultiKeySchema.extern_id) or (key_name == cls.Schema.MultiKeySchema.email) or (key_name == cls.Schema.MultiKeySchema.madid)): return key_value if (key_name == cls.Schema.MultiKeySchema.phone): key_value = re.sub('[^...
'Adds users to this CustomAudience. Args: schema: A CustomAudience.Schema value specifying the type of values in the users list. users: A list of identities respecting the schema specified. Returns: The FacebookResponse object.'
def add_users(self, schema, users, is_raw=False, app_ids=None, pre_hashed=None, session=None):
return self.get_api_assured().call('POST', (self.get_id_assured(), 'users'), params=self.format_params(schema, users, is_raw, app_ids, pre_hashed, session))
'Deletes users from this CustomAudience. Args: schema: A CustomAudience.Schema value specifying the type of values in the users list. users: A list of identities respecting the schema specified. Returns: The FacebookResponse object.'
def remove_users(self, schema, users, is_raw=False, app_ids=None, pre_hashed=None, session=None):
return self.get_api_assured().call('DELETE', (self.get_id_assured(), 'users'), params=self.format_params(schema, users, is_raw, app_ids, pre_hashed, session))
'Shares this CustomAudience with the specified account_ids. Args: account_ids: A list of account ids. Returns: The FacebookResponse object.'
def share_audience(self, account_ids):
return self.get_api_assured().call('POST', (self.get_id_assured(), 'adaccounts'), params={'adaccounts': account_ids})
'Unshares this CustomAudience with the specified account_ids. Args: account_ids: A list of account ids. Returns: The FacebookResponse object.'
def unshare_audience(self, account_ids):
return self.get_api_assured().call('DELETE', (self.get_id_assured(), 'adaccounts'), params={'adaccounts': account_ids})
'Updates a product stored in a product catalog Args: retailer_id: product id from product feed. g:price tag in Google Shopping feed kwargs: key-value pairs to update on the object, being key the field name and value the updated value Returns: The FacebookResponse object.'
def update_product(self, retailer_id, **kwargs):
if (not kwargs): raise FacebookError("No fields to update provided. Example:\n catalog = ProductCatalog('catalog_id')\n catalog.update_pr...
'Associate ads pixel with another business'
def share_pixel_with_agency(self, business_id, agency_id):
return self.get_api_assured().call('POST', (self.get_id_assured(), 'shared_agencies'), params={'business': business_id, 'agency_id': agency_id})
'Returns a list of businesses associated with the ads pixel'
def get_agencies(self):
response = self.get_api_assured().call('GET', (self.get_id_assured(), 'shared_agencies')).json() ret_val = [] if response: keys = response['data'] for item in keys: search_obj = Business() search_obj.update(item) ret_val.append(search_obj) return ret_v...
'Returns list of adaccounts associated with the ads pixel'
def get_ad_accounts(self, business_id):
response = self.get_api_assured().call('GET', (self.get_id_assured(), 'shared_accounts'), params={'business': business_id}).json() ret_val = [] if response: keys = response['data'] for item in keys: search_obj = AdAccount() search_obj.update(item) ret_val....
'Returns iterator over AdAccounts associated with this user.'
def get_ad_accounts(self, fields=None, params=None):
return self.iterate_edge(AdAccount, fields, params, endpoint='adaccounts')
'Returns first AdAccount associated with this user.'
def get_ad_account(self, fields=None, params=None):
return self.edge_object(AdAccount, fields, params)
'Returns iterator over Pages\'s associated with this user.'
def get_pages(self, fields=None, params=None):
return self.iterate_edge(Page, fields, params)
'Gets the final result from an async job Accepts params such as limit'
def get_result(self, params=None):
return self.get_insights(params=params)
'Uploads filepath and creates the AdVideo object from it. It has same arguments as AbstractCrudObject.remote_create except it does not have the files argument but requires the \'filepath\' property to be defined.'
def remote_create(self, batch=None, failure=None, params=None, success=None):
if ((self.Field.slideshow_spec in self) and (self[self.Field.slideshow_spec] is not None)): request = VideoUploadRequest(self.get_api_assured()) request.setParams(params={'slideshow_spec': {'images_urls': self[self.Field.slideshow_spec]['images_urls'], 'duration_ms': self[self.Field.slideshow_spec][...
'Returns all the thumbnails associated with the ad video'
def get_thumbnails(self, fields=None, params=None):
return self.iterate_edge(VideoThumbnail, fields, params, endpoint='thumbnails')
'Initializes and populates the instance attributes with app_id, app_secret, access_token, appsecret_proof, proxies, timeout and requests given arguments app_id, app_secret, access_token, proxies and timeout.'
def __init__(self, app_id=None, app_secret=None, access_token=None, proxies=None, timeout=None):
self.app_id = app_id self.app_secret = app_secret self.access_token = access_token self.proxies = proxies self.timeout = timeout self.requests = requests.Session() self.requests.verify = os.path.join(os.path.dirname(__file__), 'fb_ca_chain_bundle.crt') params = {'access_token': self.acce...
'Upload the given video file. Args: video(required): The AdVideo object that will be uploaded wait_for_encoding: Whether to wait until encoding is finished.'
def upload(self, video, wait_for_encoding=False):
if self._session: raise FacebookError('There is already an upload session for this video uploader') self._session = VideoUploadSession(video, wait_for_encoding) result = self._session.start() self._session = None return result
'send upload request'
@abstractmethod def send_request(self, context):
pass
'get upload params from context'
@abstractmethod def getParamsFromContext(self, context):
pass
'send start request with the given context'
def send_request(self, context):
request = VideoUploadRequest(self._api) request.setParams(self.getParamsFromContext(context)) return request.send((context.account_id, 'advideos'))
'send transfer request with the given context'
def send_request(self, context):
request = VideoUploadRequest(self._api) self._start_offset = context.start_offset self._end_offset = context.end_offset filepath = context.file_path file_size = os.path.getsize(filepath) retry = max((file_size / ((1024 * 1024) * 10)), 2) f = open(filepath, 'rb') while (self._start_offset...
'send transfer request with the given context'
def send_request(self, context):
request = VideoUploadRequest(self._api) request.setParams(self.getParamsFromContext(context)) return request.send((context.account_id, 'advideos'))
'send the current request'
def send(self, path):
return self._api.call('POST', path, params=self._params, files=self._files, url_override='https://graph-video.facebook.com')
'Delete accumulated remote objects.'
def delete_remote_objects(self):
for o in reversed(self.remote_objects): if ((o.Field.id in o) and (o.get_id() is not None)): try: o.remote_delete() except Exception: if isinstance(o, objects.AdImage): pass else: raise
'Prepare to delete obj in tearDown.'
def delete_in_teardown(self, obj):
self.remote_objects.append(obj)
'Returns object of same class as subject and with same id.'
@classmethod def get_mirror(cls, subject):
return subject.__class__(subject.get_id())
'Tests if object can be created. It asserts that id is empty before creation, and populated after.'
@classmethod def assert_can_create(cls, subject):
assert (subject[subject.Field.id] is None) subject.remote_create() assert (subject[subject.Field.id] is not None)
'Tests if object can be read. Reads default fields of subject and sees if subject matches with its mirror in all the subject\'s fields.'
@classmethod def assert_can_read(cls, subject):
assert (subject.Field.id in subject) fields_to_read = subject.get_default_read_fields() subject.remote_read(fields=fields_to_read) for field in fields_to_read: assert (field in subject) mirror = cls.get_mirror(subject) mirror.remote_read(fields=fields_to_read) for field in fields_to_...
'Asserts that the id is empty before creation and then updates'
@classmethod def assert_can_save(cls, subject):
assert (subject[subject.Field.id] is None) subject.remote_save() assert (subject[subject.Field.id] is not None) subject.remote_save() mirror = cls.get_mirror(subject) assert (subject[subject.Field.id] == mirror[mirror.Field.id])
'Sometimes the response returns an array inside the data key. This asserts that we successfully build objects using the objects in that array.'
def test_builds_from_array(self):
response = {'data': [{'id': '6019579'}, {'id': '6018402'}]} ei = api.Cursor(adaccount.AdAccount(fbid='123'), ad.Ad) objs = ei.build_objects_from_response(response) assert (len(objs) == 2)
'Sometimes the response returns a single JSON object. This asserts that we\'re not looking for the data key and that we correctly build the object without relying on the data key.'
def test_builds_from_object(self):
response = {'id': '601957/targetingsentencelines', 'targetingsentencelines': [{'content': 'Location - Living In:', 'children': ['United States']}, {'content': 'Age:', 'children': ['18 - 65+']}]} ei = api.Cursor(adaccount.AdAccount(fbid='123'), ad.Ad) obj = ei.build_objects_from_response(re...
'Sometimes the response returns a single JSON object - with a "data". For instance with reachestimate. This asserts that we successfully build the object that is in "data" key.'
def test_builds_from_object_with_data_key(self):
response = {'data': {'estimate_ready': True, 'bid_estimations': [{'cpa_min': 63, 'cpa_median': 116, 'cpm_max': 331, 'cpc_max': 48, 'cpc_median': 35, 'cpc_min': 17, 'cpm_min': 39, 'cpm_median': 212, 'unsupported': False, 'location': 3, 'cpa_max': 163}], 'users': 7600000}} ei = api.Cursor(ad.Ad('123'), reachestim...
'Demonstrates that AbstractCrudObject._assign_fields_to_params() handles various combinations of params and fields properly.'
def test_fields_to_params(self):
class Foo(abstractcrudobject.AbstractCrudObject, ): _default_read_fields = ['id', 'name'] class Bar(abstractcrudobject.AbstractCrudObject, ): _default_read_fields = [] for (adclass, fields, params, expected) in [(Foo, None, {}, {'fields': 'id,name'}), (Foo, None, {'a': 'b'}, {'a': 'b', 'fiel...
'Must be able to print nested objects without serialization issues'
def test_can_print(self):
obj = specs.ObjectStorySpec() obj2 = specs.OfferData() obj2['barcode'] = 'foo' obj['offer_data'] = obj2 try: obj.__repr__() except TypeError as e: self.fail(('Cannot call __repr__ on AbstractObject\n %s' % e))
'Prepare for Ads API calls and return a tuple with act_id and page_id. page_id can be None but act_id is always set.'
@classmethod def auth(cls):
config = cls.load_config() if cls._is_authenticated: return (config['act_id'], config.get('page_id', None)) if (config['app_id'] and config['app_secret'] and config['act_id'] and config['access_token']): FacebookAdsApi.init(config['app_id'], config['app_secret'], config['access_token'], conf...
'Initializes the object\'s internal data. Args: body (optional): The response body as text. http_status (optional): The http status code. headers (optional): The http headers. call (optional): The original call that was made.'
def __init__(self, body=None, http_status=None, headers=None, call=None):
self._body = body self._http_status = http_status self._headers = (headers or {}) self._call = call
'Returns the response body.'
def body(self):
return self._body
'Returns the response body -- in json if possible.'
def json(self):
try: return json.loads(self._body) except (TypeError, ValueError): return self._body
'Return the response headers.'
def headers(self):
return self._headers
'Returns the ETag header value if it exists.'
def etag(self):
return self._headers.get('ETag')
'Returns the http status code of the response.'
def status(self):
return self._http_status
'Returns boolean indicating if the call was successful.'
def is_success(self):
json_body = self.json() if (isinstance(json_body, collections.Mapping) and ('error' in json_body)): return False elif bool(json_body): if ('success' in json_body): return json_body['success'] return ('Service Unavailable' not in json_body) elif (self._http_status =...
'Returns boolean indicating if the call failed.'
def is_failure(self):
return (not self.is_success())
'Returns a FacebookRequestError (located in the exceptions module) with an appropriate debug message.'
def error(self):
if self.is_failure(): return FacebookRequestError('Call was not successful', self._call, self.status(), self.headers(), self.body()) else: return None
'Initializes the api instance. Args: session: FacebookSession object that contains a requests interface and attribute GRAPH (the Facebook GRAPH API URL). api_version: API version'
def __init__(self, session, api_version=None):
self._session = session self._num_requests_succeeded = 0 self._num_requests_attempted = 0 self._api_version = (api_version or self.API_VERSION)
'Returns the number of calls attempted.'
def get_num_requests_attempted(self):
return self._num_requests_attempted