INSTRUCTION
stringlengths
1
8.43k
RESPONSE
stringlengths
75
104k
function to scrape file links from html response
def scrape_links(html, engine): """ function to scrape file links from html response """ soup = BeautifulSoup(html, 'lxml') links = [] if engine == 'd': results = soup.findAll('a', {'class': 'result__a'}) for result in results: link = result.get('href')[15:] link = link.replace('/blob/', '/raw/') li...
function to get return code of a url
def get_url_nofollow(url): """ function to get return code of a url Credits: http://blog.jasonantman.com/2013/06/python-script-to-check-a-list-of-urls-for-return-code-and-final-return-code-if-redirected/ """ try: response = urlopen(url) code = response.getcode() return code except HTTPError as e: return...
function to validate urls based on http ( s ) prefix and return code
def validate_links(links): """ function to validate urls based on http(s) prefix and return code """ valid_links = [] for link in links: if link[:7] in "http://" or link[:8] in "https://": valid_links.append(link) if not valid_links: print("No files found.") sys.exit(0) # checking valid urls for retu...
main function to search for links and return valid ones
def search(query, engine='g', site="", file_type = 'pdf', limit = 10): """ main function to search for links and return valid ones """ if site == "": search_query = "filetype:{0} {1}".format(file_type, query) else: search_query = "site:{0} filetype:{1} {2}".format(site,file_type, query) headers = { 'User A...
function to check input filetype against threat extensions list
def check_threats(**args): """ function to check input filetype against threat extensions list """ is_high_threat = False for val in THREAT_EXTENSIONS.values(): if type(val) == list: for el in val: if args['file_type'] == el: is_high_threat = True break else: if args['file_type'] == val: ...
function to check if input query is not None and set missing arguments to default value
def validate_args(**args): """ function to check if input query is not None and set missing arguments to default value """ if not args['query']: print("\nMissing required query argument.") sys.exit() for key in DEFAULTS: if key not in args: args[key] = DEFAULTS[key] return args
main function to fetch links and download them
def download_content(**args): """ main function to fetch links and download them """ args = validate_args(**args) if not args['directory']: args['directory'] = args['query'].replace(' ', '-') print("Downloading {0} {1} files on topic {2} from {3} and saving to directory: {4}" .format(args['limit'], args['fi...
function to show valid file extensions
def show_filetypes(extensions): """ function to show valid file extensions """ for item in extensions.items(): val = item[1] if type(item[1]) == list: val = ", ".join(str(x) for x in item[1]) print("{0:4}: {1}".format(val, item[0]))
Determine if a python datum is an instance of a schema.
def validate_ex(expected_schema, # type: Schema datum, # type: Any identifiers=None, # type: List[Text] strict=False, # type: bool foreign_properties=None, # type: Set...
Force use of unicode.
def json_dump(obj, # type: Any fp, # type: IO[str] **kwargs # type: Any ): # type: (...) -> None """ Force use of unicode. """ if six.PY2: kwargs['encoding'] = 'utf-8' json.dump(convert_to_dict(obj), fp, **kwargs)
Force use of unicode.
def json_dumps(obj, # type: Any **kwargs # type: Any ): # type: (...) -> str """ Force use of unicode. """ if six.PY2: kwargs['encoding'] = 'utf-8' return json.dumps(convert_to_dict(obj), **kwargs)
Generate classes with loaders for the given Schema Salad description.
def codegen(lang, # type: str i, # type: List[Dict[Text, Any]] schema_metadata, # type: Dict[Text, Any] loader # type: Loader ): # type: (...) -> None """Generate classes with loaders for the given Schema Salad description.""" ...
Return a list of subset of VM that match the pattern name
def find(self, name): """ Return a list of subset of VM that match the pattern name @param name (str): the vm name of the virtual machine @param name (Obj): the vm object that represent the virtual machine (can be Pro or Smart) @return (list): the subse...
Reinitialize a VM.: param admin_password: Administrator password.: param debug: Flag to enable debug output.: param ConfigureIPv6: Flag to enable IPv6 on the VM.: param OSTemplateID: TemplateID to reinitialize the VM with.: return: True in case of success otherwise False: type admin_password: str: type debug: bool: typ...
def reinitialize(self, admin_password=None, debug=False, ConfigureIPv6=False, OSTemplateID=None): """ Reinitialize a VM. :param admin_password: Administrator password. :param debug: Flag to enable debug output. :param ConfigureIPv6: Flag to enable IPv6 on the VM. :param O...
Set the authentication data in the object and if load is True ( default is True ) it also retrieve the ip list and the vm list in order to build the internal objects list.
def login(self, username, password, load=True): """ Set the authentication data in the object, and if load is True (default is True) it also retrieve the ip list and the vm list in order to build the internal objects list. @param (str) username: username of the cloud @par...
Poweroff a VM. If possible to pass the VM object or simply the ID of the VM that we want to turn on. Args: server: VM Object that represent the VM to power off server_id: Int or Str representing the ID of the VM to power off. Returns: return True if json_obj [ Success ] is True else False
def poweroff_server(self, server=None, server_id=None): """ Poweroff a VM. If possible to pass the VM object or simply the ID of the VM that we want to turn on. Args: server: VM Object that represent the VM to power off, server_id: Int or Str representing the ID o...
Initialize the internal list containing each template available for each hypervisor.
def get_hypervisors(self): """ Initialize the internal list containing each template available for each hypervisor. :return: [bool] True in case of success, otherwise False """ json_scheme = self.gen_def_json_scheme('GetHypervisors') json_obj = self.call_method_p...
Create the list of Server object inside the Datacenter objects. Build an internal list of VM Objects ( pro or smart ) as iterator.: return: bool
def get_servers(self): """ Create the list of Server object inside the Datacenter objects. Build an internal list of VM Objects (pro or smart) as iterator. :return: bool """ json_scheme = self.gen_def_json_scheme('GetServers') json_obj = self.call_method_post(meth...
Return a list of templates that could have one or more elements. Args: name: name of the template to find. hv: the ID of the hypervisor to search the template in Returns: A list of templates object. If hv is None will return all the templates matching the name if every hypervisor type. Otherwise if name is None will re...
def find_template(self, name=None, hv=None): """ Return a list of templates that could have one or more elements. Args: name: name of the template to find. hv: the ID of the hypervisor to search the template in Returns: A list of templates object. If h...
Return an ip object representing a new bought IP
def purchase_ip(self, debug=False): """ Return an ip object representing a new bought IP @param debug [Boolean] if true, request and response will be printed @return (Ip): Ip object """ json_scheme = self.gen_def_json_scheme('SetPurchaseIpAddress') json_obj = self...
Purchase a new VLAN.: param debug: Log the json response if True: param vlan_name: String representing the name of the vlan ( virtual switch ): return: a Vlan Object representing the vlan created
def purchase_vlan(self, vlan_name, debug=False): """ Purchase a new VLAN. :param debug: Log the json response if True :param vlan_name: String representing the name of the vlan (virtual switch) :return: a Vlan Object representing the vlan created """ vlan_name = {...
Remove a VLAN: param vlan_resource_id:: return:
def remove_vlan(self, vlan_resource_id): """ Remove a VLAN :param vlan_resource_id: :return: """ vlan_id = {'VLanResourceId': vlan_resource_id} json_scheme = self.gen_def_json_scheme('SetRemoveVLan', vlan_id) json_obj = self.call_method_post(method='SetRem...
Delete an Ip from the boughs ip list
def remove_ip(self, ip_id): """ Delete an Ip from the boughs ip list @param (str) ip_id: a string representing the resource id of the IP @return: True if json method had success else False """ ip_id = ' "IpAddressResourceId": %s' % ip_id json_scheme = self.gen_...
Retrieve the smart package id given is English name
def get_package_id(self, name): """ Retrieve the smart package id given is English name @param (str) name: the Aruba Smart package size name, ie: "small", "medium", "large", "extra large". @return: The package id that depends on the Data center and the size choosen. """ j...
Retrieve a complete list of bought ip address related only to PRO Servers. It create an internal object ( Iplist ) representing all of the ips object iterated form the WS.
def get_ip(self): """ Retrieve a complete list of bought ip address related only to PRO Servers. It create an internal object (Iplist) representing all of the ips object iterated form the WS. @param: None @return: None """ json_scheme = self.gen_def_json_s...
Generate the scheme for the json request.: param req: String representing the name of the method to call: param method_fields: A dictionary containing the method - specified fields: rtype: json object representing the method call
def gen_def_json_scheme(self, req, method_fields=None): """ Generate the scheme for the json request. :param req: String representing the name of the method to call :param method_fields: A dictionary containing the method-specified fields :rtype : json object representing the met...
: return: ( dict ) Response object content
def _commit(self): """ :return: (dict) Response object content """ assert self.uri is not None, Exception("BadArgument: uri property cannot be None") url = '{}/{}'.format(self.uri, self.__class__.__name__) serialized_json = jsonpickle.encode(self, unpicklable=False, ) ...
Retrieve the current configured SharedStorages entries: return: [ list ] List containing the current SharedStorages entries
def get(self): """ Retrieve the current configured SharedStorages entries :return: [list] List containing the current SharedStorages entries """ request = self._call(GetSharedStorages) response = request.commit() return response['Value']
: type quantity: int: type iqn: list [ str ]: type name: str: type protocol: SharedStorageProtocols: param quantity: Amount of GB: param iqn: List of IQN represented in string format: param name: Name of the resource: param protocol: Protocol to use: return:
def purchase_iscsi(self, quantity, iqn, name, protocol=SharedStorageProtocolType.ISCSI): """ :type quantity: int :type iqn: list[str] :type name: str :type protocol: SharedStorageProtocols :param quantity: Amount of GB :param iqn: List of IQN represented in string...
Wrapper around Requests for GET requests
def _get(self, *args, **kwargs): """Wrapper around Requests for GET requests Returns: Response: A Requests Response object """ if 'timeout' not in kwargs: kwargs['timeout'] = self.timeout req = self.session.get(*args, **kwargs) r...
Wrapper around Requests for GET XML requests
def _get_xml(self, *args, **kwargs): """Wrapper around Requests for GET XML requests Returns: Response: A Requests Response object """ req = self.session_xml.get(*args, **kwargs) return req
Wrapper around Requests for POST requests
def _post(self, *args, **kwargs): """Wrapper around Requests for POST requests Returns: Response: A Requests Response object """ if 'timeout' not in kwargs: kwargs['timeout'] = self.timeout req = self.session.post(*args, **kwargs) ...
Wrapper around Requests for POST requests
def _post_xml(self, *args, **kwargs): """Wrapper around Requests for POST requests Returns: Response: A Requests Response object """ if 'timeout' not in kwargs: kwargs['timeout'] = self.timeout req = self.session_xml.post(*args, **kwargs...
Wrapper around Requests for PUT requests
def _put(self, *args, **kwargs): """Wrapper around Requests for PUT requests Returns: Response: A Requests Response object """ if 'timeout' not in kwargs: kwargs['timeout'] = self.timeout req = self.session.put(*args, **kwargs) r...
Wrapper around Requests for DELETE requests
def _delete(self, *args, **kwargs): """Wrapper around Requests for DELETE requests Returns: Response: A Requests Response object """ if 'timeout' not in kwargs: kwargs['timeout'] = self.timeout req = self.session.delete(*args, **kwargs) ...
Test that application can authenticate to Crowd.
def auth_ping(self): """Test that application can authenticate to Crowd. Attempts to authenticate the application user against the Crowd server. In order for user authentication to work, an application must be able to authenticate. Returns: bool: Tru...
Authenticate a user account against the Crowd server.
def auth_user(self, username, password): """Authenticate a user account against the Crowd server. Attempts to authenticate the user against the Crowd server. Args: username: The account username. password: The account password. Returns: dict: ...
Create a session for a user.
def get_session(self, username, password, remote="127.0.0.1", proxy=None): """Create a session for a user. Attempts to create a user session on the Crowd server. Args: username: The account username. password: The account password. remote: ...
Validate a session token.
def validate_session(self, token, remote="127.0.0.1", proxy=None): """Validate a session token. Validate a previously acquired session token against the Crowd server. This may be a token provided by a user from a http cookie or by some other means. Args: token: The ...
Terminates the session token effectively logging out the user from all crowd - enabled services.
def terminate_session(self, token): """Terminates the session token, effectively logging out the user from all crowd-enabled services. Args: token: The session token. Returns: True: If session terminated None: If session termination failed "...
Add a user to the directory
def add_user(self, username, raise_on_error=False, **kwargs): """Add a user to the directory Args: username: The account username raise_on_error: optional (default: False) **kwargs: key-value pairs: password: mandatory ...
Retrieve information about a user
def get_user(self, username): """Retrieve information about a user Returns: dict: User information None: If no user or failure occurred """ response = self._get(self.rest_url + "/user", params={"username": username, ...
Set the active state of a user
def set_active(self, username, active_state): """Set the active state of a user Args: username: The account username active_state: True or False Returns: True: If successful None: If no user or failure occurred """ if active_stat...
Set an attribute on a user: param username: The username on which to set the attribute: param attribute: The name of the attribute to set: param value: The value of the attribute to set: return: True on success False on failure.
def set_user_attribute(self, username, attribute, value, raise_on_error=False): """Set an attribute on a user :param username: The username on which to set the attribute :param attribute: The name of the attribute to set :param value: The value of the attribute to set :return: T...
Add a user to a group: param username: The username to assign to the group: param groupname: The group name into which to assign the user: return: True on success False on failure.
def add_user_to_group(self, username, groupname, raise_on_error=False): """Add a user to a group :param username: The username to assign to the group :param groupname: The group name into which to assign the user :return: True on success, False on failure. """ data = { ...
Remove a user from a group
def remove_user_from_group(self, username, groupname, raise_on_error=False): """Remove a user from a group Attempts to remove a user from a group Args username: The username to remove from the group. groupname: The group name to be removed from the user. Returns: ...
Change new password for a user
def change_password(self, username, newpassword, raise_on_error=False): """Change new password for a user Args: username: The account username. newpassword: The account new password. raise_on_error: optional (default: False) Returns: True: Succ...
Sends the user a password reset link ( by email )
def send_password_reset_link(self, username): """Sends the user a password reset link (by email) Args: username: The account username. Returns: True: Succeeded False: If unsuccessful """ response = self._post(self.rest_url + "/user/mail/pass...
Retrieve a list of all group names that have <username > as a direct or indirect member.
def get_nested_groups(self, username): """Retrieve a list of all group names that have <username> as a direct or indirect member. Args: username: The account username. Returns: list: A list of strings of group names. """ response = self...
Retrieves a list of all users that directly or indirectly belong to the given groupname.
def get_nested_group_users(self, groupname): """Retrieves a list of all users that directly or indirectly belong to the given groupname. Args: groupname: The group name. Returns: list: A list of strings of user names. """ response = sel...
Determines if the user exists.
def user_exists(self, username): """Determines if the user exists. Args: username: The user name. Returns: bool: True if the user exists in the Crowd application. """ response = self._get(self.rest_url + "/user", ...
Fetches all group memberships.
def get_memberships(self): """Fetches all group memberships. Returns: dict: key: group name value: (array of users, array of groups) """ response = self._get_xml(self.rest_url + "/group/membership") if not response.ok: return None ...
Performs a user search using the Crowd search API.
def search(self, entity_type, property_name, search_string, start_index=0, max_results=99999): """Performs a user search using the Crowd search API. https://developer.atlassian.com/display/CROWDDEV/Crowd+REST+Resources#CrowdRESTResources-SearchResource Args: entity_type: 'user' or ...
The versions associated with Blender
def versions(self) -> List(BlenderVersion): """ The versions associated with Blender """ return [BlenderVersion(tag) for tag in self.git_repo.tags] + [BlenderVersion(BLENDER_VERSION_MASTER)]
Copy libraries from the bin directory and place them as appropriate
def run(self): """ Copy libraries from the bin directory and place them as appropriate """ self.announce("Moving library files", level=3) # We have already built the libraries in the previous build_ext step self.skip_build = True bin_dir = self.distribution.bi...
Copy the required directory to the build directory and super (). run ()
def run(self): """ Copy the required directory to the build directory and super().run() """ self.announce("Moving scripts files", level=3) self.skip_build = True bin_dir = self.distribution.bin_dir scripts_dirs = [os.path.join(bin_dir, _dir) for _dir in ...
Perform build_cmake before doing the normal stuff
def run(self): """ Perform build_cmake before doing the 'normal' stuff """ for extension in self.extensions: if extension.name == "bpy": self.build_cmake(extension) super().run()
The steps required to build the extension
def build_cmake(self, extension: Extension): """ The steps required to build the extension """ # We import the setup_requires modules here because if we import them # at the top this script will always fail as they won't be present from git import Repo as GitRepo ...
: type addresses: list [ str ]: param addresses: ( list [ str ] ) List of addresses to retrieve their reverse dns Retrieve the current configured ReverseDns entries: return: ( list ) List containing the current ReverseDns Addresses
def get(self, addresses): """ :type addresses: list[str] :param addresses: (list[str]) List of addresses to retrieve their reverse dns Retrieve the current configured ReverseDns entries :return: (list) List containing the current ReverseDns Addresses """ request =...
Assign one or more PTR record to a single IP Address: type address: str: type host_name: list [ str ]: param address: ( str ) The IP address to configure: param host_name: ( list [ str ] ) The list of strings representing PTR records: return: ( bool ) True in case of success False in case of failure
def set(self, address, host_name): """ Assign one or more PTR record to a single IP Address :type address: str :type host_name: list[str] :param address: (str) The IP address to configure :param host_name: (list[str]) The list of strings representing PTR records :...
Remove all PTR records from the given address: type addresses: List [ str ]: param addresses: ( List [ str ] ) The IP Address to reset: return: ( bool ) True in case of success False in case of failure
def reset(self, addresses): """ Remove all PTR records from the given address :type addresses: List[str] :param addresses: (List[str]) The IP Address to reset :return: (bool) True in case of success, False in case of failure """ request = self._call(SetEnqueueRese...
: type healthCheckNotification: bool: type instance: list [ Instance ]: type ipAddressResourceId: list [ int ]: type loadBalancerClassOfServiceID: int: type name: str: type notificationContacts: NotificationContacts or list [ NotificationContact ]: type rules: Rules: param healthCheckNotification: Enable or disable not...
def create(self, healthCheckNotification, instance, ipAddressResourceId, name, notificationContacts, rules, loadBalancerClassOfServiceID=1, *args, **kwargs): """ :type healthCheckNotification: bool :type instance: list[Instance] :type ipAddressResourceId: list[int] ...
Get the load balancer notifications for a specific rule within a specifying window time frame: type startDate: datetime: type endDate: datetime: type loadBalancerID: int: type loadBalancerRuleID: int: param startDate: From Date: param endDate: To Date: param loadBalancerID: ID of the Laod Balancer: param loadBalancerRu...
def get_notifications(self, startDate, endDate, loadBalancerID, loadBalancerRuleID): """ Get the load balancer notifications for a specific rule within a specifying window time frame :type startDate: datetime :type endDate: datetime :type loadBalancerID: int :type loadBal...
Check if the given authcfg_id ( or the default ) exists and if it s valid OAuth2 return the configuration or None
def get_oauth_authcfg(authcfg_id=AUTHCFG_ID): """Check if the given authcfg_id (or the default) exists, and if it's valid OAuth2, return the configuration or None""" # Handle empty strings if not authcfg_id: authcfg_id = AUTHCFG_ID configs = auth_manager().availableAuthMethodConfigs() if...
Setup oauth configuration to access the BCS API return authcfg_id on success None on failure
def setup_oauth(username, password, basemaps_token_uri, authcfg_id=AUTHCFG_ID, authcfg_name=AUTHCFG_NAME): """Setup oauth configuration to access the BCS API, return authcfg_id on success, None on failure """ cfgjson = { "accessMethod" : 0, "apiKey" : "", "clientId" : "", "clientSecr...
Create a new SearchQuery instance and execute a search against ES.
def execute_search( search, search_terms="", user=None, reference="", save=True, query_type=SearchQuery.QUERY_TYPE_SEARCH, ): """ Create a new SearchQuery instance and execute a search against ES. Args: search: elasticsearch.search.Search object, that internally contains ...
Return True if an object is part of the search index queryset.
def in_search_queryset(self, instance_id, index="_all"): """ Return True if an object is part of the search index queryset. Sometimes it's useful to know if an object _should_ be indexed. If an object is saved, how do you know if you should push that change to the search index? ...
Return queryset of objects from SearchQuery. results ** in order **.
def from_search_query(self, search_query): """ Return queryset of objects from SearchQuery.results, **in order**. EXPERIMENTAL: this will only work with results from a single index, with a single doc_type - as we are returning a single QuerySet. This method takes the hits JSON ...
Prepare SQL statement consisting of a sequence of WHEN.. THEN statements.
def _raw_sql(self, values): """Prepare SQL statement consisting of a sequence of WHEN .. THEN statements.""" if isinstance(self.model._meta.pk, CharField): when_clauses = " ".join( [self._when("'{}'".format(x), y) for (x, y) in values] ) else: ...
Key used for storing search docs in local cache.
def search_document_cache_key(self): """Key used for storing search docs in local cache.""" return "elasticsearch_django:{}.{}.{}".format( self._meta.app_label, self._meta.model_name, self.pk )
Return True if the field can be serialized into a JSON doc.
def _is_field_serializable(self, field_name): """Return True if the field can be serialized into a JSON doc.""" return ( self._meta.get_field(field_name).get_internal_type() in self.SIMPLE_UPDATE_FIELD_TYPES )
Clean the list of update_fields based on the index being updated. \
def clean_update_fields(self, index, update_fields): """ Clean the list of update_fields based on the index being updated.\ If any field in the update_fields list is not in the set of properties defined by the index mapping for this model, then we ignore it. If a field _is_ in t...
Return a partial update document based on which fields have been updated.
def as_search_document_update(self, *, index, update_fields): """ Return a partial update document based on which fields have been updated. If an object is saved with the `update_fields` argument passed through, then it is assumed that this is a 'partial update'. In this scenari...
Return an object as represented in a bulk api operation.
def as_search_action(self, *, index, action): """ Return an object as represented in a bulk api operation. Bulk API operations have a very specific format. This function will call the standard `as_search_document` method on the object and then wrap that up in the correct format ...
Fetch the object s document from a search index by id.
def fetch_search_document(self, *, index): """Fetch the object's document from a search index by id.""" assert self.pk, "Object must have a primary key before being indexed." client = get_client() return client.get(index=index, doc_type=self.search_doc_type, id=self.pk)
Create or replace search document in named index.
def index_search_document(self, *, index): """ Create or replace search document in named index. Checks the local cache to see if the document has changed, and if not aborts the update, else pushes to ES, and then resets the local cache. Cache timeout is set as "cache_expiry" ...
Partial update of a document in named index.
def update_search_document(self, *, index, update_fields): """ Partial update of a document in named index. Partial updates are invoked via a call to save the document with 'update_fields'. These fields are passed to the as_search_document method so that it can build a partial ...
Delete document from named index.
def delete_search_document(self, *, index): """Delete document from named index.""" cache.delete(self.search_document_cache_key) get_client().delete(index=index, doc_type=self.search_doc_type, id=self.pk)
Create a new SearchQuery instance and execute a search against ES.
def execute(cls, search, search_terms="", user=None, reference=None, save=True): """Create a new SearchQuery instance and execute a search against ES.""" warnings.warn( "Pending deprecation - please use `execute_search` function instead.", PendingDeprecationWarning, ) ...
Save and return the object ( for chaining ).
def save(self, **kwargs): """Save and return the object (for chaining).""" if self.search_terms is None: self.search_terms = "" super().save(**kwargs) return self
Return the query from: size tuple ( 0 - based ).
def page_slice(self): """Return the query from:size tuple (0-based).""" return ( None if self.query is None else (self.query.get("from", 0), self.query.get("size", 10)) )
Sets the value of a plugin setting.
def setPluginSetting(name, value, namespace = None): ''' Sets the value of a plugin setting. :param name: the name of the setting. It is not the full path, but just the last name of it :param value: the value to set for the plugin setting :param namespace: The namespace. If not passed or None, the ...
Returns the value of a plugin setting.
def pluginSetting(name, namespace=None, typ=None): ''' Returns the value of a plugin setting. :param name: the name of the setting. It is not the full path, but just the last name of it :param namespace: The namespace. If not passed or None, the namespace will be inferred from the caller method. No...
Reads the settings corresponding to the plugin from where the method is called. This function has to be called in the __init__ method of the plugin class. Settings are stored in a settings. json file in the plugin folder. Here is an eample of such a file:
def readSettings(settings_path=None): global _settings ''' Reads the settings corresponding to the plugin from where the method is called. This function has to be called in the __init__ method of the plugin class. Settings are stored in a settings.json file in the plugin folder. Here is an eampl...
Delete search index.
def do_index_command(self, index, **options): """Delete search index.""" if options["interactive"]: logger.warning("This will permanently delete the index '%s'.", index) if not self._confirm_action(): logger.warning( "Aborting deletion of index...
Create an index and apply mapping if appropriate.
def create_index(index): """Create an index and apply mapping if appropriate.""" logger.info("Creating search index: '%s'", index) client = get_client() return client.indices.create(index=index, body=get_index_mapping(index))
Re - index every document in a named index.
def update_index(index): """Re-index every document in a named index.""" logger.info("Updating search index: '%s'", index) client = get_client() responses = [] for model in get_index_models(index): logger.info("Updating search index model: '%s'", model.search_doc_type) objects = mode...
Delete index entirely ( removes all documents and mapping ).
def delete_index(index): """Delete index entirely (removes all documents and mapping).""" logger.info("Deleting search index: '%s'", index) client = get_client() return client.indices.delete(index=index)
Remove all orphaned documents from an index.
def prune_index(index): """Remove all orphaned documents from an index. This function works by scanning the remote index, and in each returned batch of documents looking up whether they appear in the default index queryset. If they don't (they've been deleted, or no longer fit the qs filters) then ...
Check whether a document should be pruned.
def _prune_hit(hit, model): """ Check whether a document should be pruned. This method uses the SearchDocumentManagerMixin.in_search_queryset method to determine whether a 'hit' (search document) should be pruned from an index, and if so it returns the hit as a Django object(id=hit_id). Args: ...
Yield all documents of model type in an index.
def scan_index(index, model): """ Yield all documents of model type in an index. This function calls the elasticsearch.helpers.scan function, and yields all the documents in the index that match the doc_type produced by a specific Django model. Args: index: string, the name of the inde...
Yield bulk api actions from a collection of objects.
def bulk_actions(objects, index, action): """ Yield bulk api 'actions' from a collection of objects. The output from this method can be fed in to the bulk api helpers - each document returned by get_documents is decorated with the appropriate bulk api op_type. Args: objects: iterable (...
Validate settings. SEARCH_SETTINGS.
def _validate_config(strict=False): """Validate settings.SEARCH_SETTINGS.""" for index in settings.get_index_names(): _validate_mapping(index, strict=strict) for model in settings.get_index_models(index): _validate_model(model) if settings.get_setting("update_strategy", "full") n...
Check that an index mapping JSON file exists.
def _validate_mapping(index, strict=False): """Check that an index mapping JSON file exists.""" try: settings.get_index_mapping(index) except IOError: if strict: raise ImproperlyConfigured("Index '%s' has no mapping file." % index) else: logger.warning("Index ...
Check that a model configured for an index subclasses the required classes.
def _validate_model(model): """Check that a model configured for an index subclasses the required classes.""" if not hasattr(model, "as_search_document"): raise ImproperlyConfigured("'%s' must implement `as_search_document`." % model) if not hasattr(model.objects, "get_search_queryset"): rai...
Connect up post_save post_delete signals for models.
def _connect_signals(): """Connect up post_save, post_delete signals for models.""" for index in settings.get_index_names(): for model in settings.get_index_models(index): _connect_model_signals(model)
Connect signals for a single model.
def _connect_model_signals(model): """Connect signals for a single model.""" dispatch_uid = "%s.post_save" % model._meta.model_name logger.debug("Connecting search index model post_save signal: %s", dispatch_uid) signals.post_save.connect(_on_model_save, sender=model, dispatch_uid=dispatch_uid) disp...
Update document in search index post_save.
def _on_model_save(sender, **kwargs): """Update document in search index post_save.""" instance = kwargs.pop("instance") update_fields = kwargs.pop("update_fields") for index in instance.search_indexes: try: _update_search_index( instance=instance, index=index, update...
Remove documents from search indexes post_delete.
def _on_model_delete(sender, **kwargs): """Remove documents from search indexes post_delete.""" instance = kwargs.pop("instance") for index in instance.search_indexes: try: _delete_from_search_index(instance=instance, index=index) except Exception: logger.exception("E...
Wrapper around the instance manager method.
def _in_search_queryset(*, instance, index) -> bool: """Wrapper around the instance manager method.""" try: return instance.__class__.objects.in_search_queryset(instance.id, index=index) except Exception: logger.exception("Error checking object in_search_queryset.") return False