InstaloaderContext (Low-level functions)

InstaloaderContext

class InstaloaderContext(sleep=True, quiet=False, user_agent=None, max_connection_attempts=3, request_timeout=300.0, rate_controller=None, fatal_status_codes=None, iphone_support=True)

Class providing methods for (error) logging and low-level communication with Instagram.

It is not thought to be instantiated directly, rather Instaloader instances maintain a context object.

For logging, it provides log(), error(), error_catcher().

It provides low-level communication routines get_json(), graphql_query(), graphql_node_list(), get_and_write_raw() and implements mechanisms for rate controlling and error handling.

Further, it provides methods for logging in and general session handles, which are used by that routines in class Instaloader.

anonymous_copy()
property is_logged_in

True, if this Instaloader instance is logged in.

Return type

bool

log(*msg, sep='', end='\n', flush=False)

Log a message to stdout that can be suppressed with –quiet.

error(msg, repeat_at_end=True)

Log a non-fatal error message to stderr, which is repeated at program termination.

Parameters
  • msg – Message to be printed.

  • repeat_at_end – Set to false if the message should be printed, but not repeated at program termination.

close()

Print error log and close session

error_catcher(extra_info=None)

Context manager to catch, print and record InstaloaderExceptions.

Parameters

extra_info (Optional[str]) – String to prefix error message with.

get_anonymous_session()

Returns our default anonymous requests.Session object.

Return type

Session

save_session_to_file(sessionfile)

Not meant to be used directly, use Instaloader.save_session_to_file().

load_session_from_file(username, sessionfile)

Not meant to be used directly, use Instaloader.load_session_from_file().

test_login()

Not meant to be used directly, use Instaloader.test_login().

Return type

Optional[str]

login(user, passwd)

Not meant to be used directly, use Instaloader.login().

Raises
two_factor_login(two_factor_code)

Second step of login if 2FA is enabled. Not meant to be used directly, use Instaloader.two_factor_login().

Raises

New in version 4.2.

do_sleep()

Sleep a short time if self.sleep is set. Called before each request to instagram.com.

get_json(path, params, host='www.instagram.com', session=None, _attempt=1)

JSON request to Instagram.

Parameters
  • path (str) – URL, relative to the given domain which defaults to www.instagram.com/

  • params (Dict[str, Any]) – GET parameters

  • host (str) – Domain part of the URL from where to download the requested JSON; defaults to www.instagram.com

  • session (Optional[Session]) – Session to use, or None to use self.session

Return type

Dict[str, Any]

Returns

Decoded response dictionary

Raises
graphql_query(query_hash, variables, referer=None, rhx_gis=None)

Do a GraphQL Query.

Parameters
  • query_hash (str) – Query identifying hash.

  • variables (Dict[str, Any]) – Variables for the Query.

  • referer (Optional[str]) – HTTP Referer, or None.

  • rhx_gis (Optional[str]) – ‘rhx_gis’ variable as somewhere returned by Instagram, needed to ‘sign’ request

Return type

Dict[str, Any]

Returns

The server’s response dictionary.

graphql_node_list(query_hash, query_variables, query_referer, edge_extractor, rhx_gis=None, first_data=None)

Retrieve a list of GraphQL nodes.

Deprecated since version 4.5: Use NodeIterator instead, which provides more functionality.

Return type

Iterator[Dict[str, Any]]

get_iphone_json(path, params)

JSON request to i.instagram.com.

Parameters
  • path (str) – URL, relative to i.instagram.com/

  • params (Dict[str, Any]) – GET parameters

Return type

Dict[str, Any]

Returns

Decoded response dictionary

Raises

New in version 4.2.1.

write_raw(resp, filename)

Write raw response data into a file.

New in version 4.2.1.

Return type

None

get_raw(url, _attempt=1)

Downloads a file anonymously.

Raises

New in version 4.2.1.

Return type

Response

get_and_write_raw(url, filename)

Downloads and writes anonymously-requested raw data into a file.

Raises
Return type

None

head(url, allow_redirects=False)

HEAD a URL anonymously.

Raises

New in version 4.7.6.

Return type

Response

property root_rhx_gis

rhx_gis string returned in the / query.

Return type

Optional[str]

RateController

class RateController(context)

Class providing request tracking and rate controlling to stay within rate limits.

It can be overridden to change Instaloader’s behavior regarding rate limits, for example to raise a custom exception when the rate limit is hit:

import instaloader

class MyRateController(instaloader.RateController):
    def sleep(self, secs):
        raise MyCustomException()

L = instaloader.Instaloader(rate_controller=lambda ctx: MyRateController(ctx))

New in version 4.5.

sleep(secs)

Wait given number of seconds.

count_per_sliding_window(query_type)

Return how many requests of the given type can be done within a sliding window of 11 minutes.

This is called by RateController.query_waittime() and allows to simply customize wait times before queries at query_type granularity. Consider overriding RateController.query_waittime() directly if you need more control.

Return type

int

query_waittime(query_type, current_time, untracked_queries=False)

Calculate time needed to wait before query can be executed.

Return type

float

wait_before_query(query_type)

This method is called before a query to Instagram.

It calls RateController.query_waittime() to determine the time needed to wait and then calls RateController.sleep() to wait until the request can be made.

Return type

None

handle_429(query_type)

This method is called to handle a 429 Too Many Requests response.

It calls RateController.query_waittime() to determine the time needed to wait and then calls RateController.sleep() to wait until we can repeat the same request.

Return type

None

Next Section

Exceptions