INSTRUCTION
stringlengths
1
8.43k
RESPONSE
stringlengths
75
104k
Adds or updates a document to the index
def index(cls, document, id_=None, overwrite_existing=True, es=None, index=None): """Adds or updates a document to the index :arg document: Python dict of key/value pairs representing the document .. Note:: This must be serializable into JSON. ...
Adds or updates a batch of documents.
def bulk_index(cls, documents, id_field='id', es=None, index=None): """Adds or updates a batch of documents. :arg documents: List of Python dicts representing individual documents to be added to the index .. Note:: This must be serializable into JSON. :...
Removes a particular item from the search index.
def unindex(cls, id_, es=None, index=None): """Removes a particular item from the search index. :arg id_: The Elasticsearch id for the document to remove from the index. :arg es: The `Elasticsearch` to use. If you don't specify an `Elasticsearch`, it'll use `cls.get_es(...
Refreshes the index.
def refresh_index(cls, es=None, index=None): """Refreshes the index. Elasticsearch will update the index periodically automatically. If you need to see the documents you just indexed in your search results right now, you should call `refresh_index` as soon as you're done indexin...
Monkey patch for elasticsearch - py 1. 0 + to make it work with ES 0. 90
def monkeypatch_es(): """Monkey patch for elasticsearch-py 1.0+ to make it work with ES 0.90 1. tweaks elasticsearch.client.bulk to normalize return status codes .. Note:: We can nix this whe we drop support for ES 0.90. """ if _monkeypatched_es: return def normalize_bulk_ret...
Returns view context dictionary.
def get_context_data(self, **kwargs): """ Returns view context dictionary. :rtype: dict. """ kwargs.update({ 'entries': Entry.objects.get_for_tag( self.kwargs.get('slug', 0) ) }) return super(EntriesView, self).get_context...
Read the password from the file.
def get_password(self, service, username): """ Read the password from the file. """ assoc = self._generate_assoc(service, username) service = escape_for_ini(service) username = escape_for_ini(username) # load the passwords from the file config = configpar...
Write the password in the file.
def set_password(self, service, username, password): """Write the password in the file. """ if not username: # https://github.com/jaraco/keyrings.alt/issues/21 raise ValueError("Username cannot be blank.") if not isinstance(password, string_types): rai...
Ensure the storage path exists. If it doesn t create it with go - rwx permissions.
def _ensure_file_path(self): """ Ensure the storage path exists. If it doesn't, create it with "go-rwx" permissions. """ storage_root = os.path.dirname(self.file_path) needs_storage_root = storage_root and not os.path.isdir(storage_root) if needs_storage_root: # ...
Delete the password for the username of the service.
def delete_password(self, service, username): """Delete the password for the username of the service. """ service = escape_for_ini(service) username = escape_for_ini(username) config = configparser.RawConfigParser() if os.path.exists(self.file_path): config.re...
Returns a list of model classes that subclass Page and include a tags field.: rtype: list.
def applicable_models(self): """ Returns a list of model classes that subclass Page and include a "tags" field. :rtype: list. """ Page = apps.get_model('wagtailcore', 'Page') applicable = [] for model in apps.get_models(): ...
Add edit handler that includes related panels to applicable model classes that don t explicitly define their own edit handler.
def add_relationship_panels(self): """ Add edit handler that includes "related" panels to applicable model classes that don't explicitly define their own edit handler. """ from wagtailplus.utils.edit_handlers import add_panel_to_edit_handler from wagtailplus.wagtail...
Adds relationship methods to applicable model classes.
def add_relationship_methods(self): """ Adds relationship methods to applicable model classes. """ Entry = apps.get_model('wagtailrelations', 'Entry') @cached_property def related(instance): return instance.get_related() @cached_property ...
Finalizes application configuration.
def ready(self): """ Finalizes application configuration. """ import wagtailplus.wagtailrelations.signals.handlers self.add_relationship_panels() self.add_relationship_methods() super(WagtailRelationsAppConfig, self).ready()
Returns a list of model classes that subclass Page.: rtype: list.
def applicable_models(self): """ Returns a list of model classes that subclass Page. :rtype: list. """ Page = apps.get_model('wagtailcore', 'Page') applicable = [] for model in apps.get_models(): if issubclass(model, Page): ...
Adds rollback panel to applicable model class s edit handlers.
def add_rollback_panels(self): """ Adds rollback panel to applicable model class's edit handlers. """ from wagtailplus.utils.edit_handlers import add_panel_to_edit_handler from wagtailplus.wagtailrollbacks.edit_handlers import HistoryPanel for model in self.applic...
Adds rollback methods to applicable model classes.
def add_rollback_methods(): """ Adds rollback methods to applicable model classes. """ # Modified Page.save_revision method. def page_rollback(instance, revision_id, user=None, submitted_for_moderation=False, approved_go_live_at=None, changed=True): old_revision...
Finalizes application configuration.
def ready(self): """ Finalizes application configuration. """ self.add_rollback_panels() self.add_rollback_methods() super(WagtailRollbacksAppConfig, self).ready()
Returns list of related Entry instances for specified page.
def get_related(page): """ Returns list of related Entry instances for specified page. :param page: the page instance. :rtype: list. """ related = [] entry = Entry.get_for_model(page) if entry: related = entry.related return related
Returns admin URL for specified entry instance.
def get_related_entry_admin_url(entry): """ Returns admin URL for specified entry instance. :param entry: the entry instance. :return: str. """ namespaces = { Document: 'wagtaildocs:edit', Link: 'wagtaillinks:edit', Page: 'wagtailadmin_pages:edit', } ...
Returns list of related tuples ( Entry instance score ) for specified page.
def get_related_with_scores(page): """ Returns list of related tuples (Entry instance, score) for specified page. :param page: the page instance. :rtype: list. """ related = [] entry = Entry.get_for_model(page) if entry: related = entry.related_with_scores return rel...
Get password of the username for the service
def get_password(self, service, username): """Get password of the username for the service """ init_part = self._keyring.get_password(service, username) if init_part: parts = [init_part] i = 1 while True: next_part = self._keyring.get_p...
Set password for the username of the service
def set_password(self, service, username, password): """Set password for the username of the service """ segments = range(0, len(password), self._max_password_size) password_parts = [ password[i:i + self._max_password_size] for i in segments] for i, password_part in e...
Given a dictionary of attributes find the corresponding link instance and return its HTML representation.
def expand_db_attributes(attrs, for_editor): """ Given a dictionary of attributes, find the corresponding link instance and return its HTML representation. :param attrs: dictionary of link attributes. :param for_editor: whether or not HTML is for editor. :rtype: str. ...
The actual keyczar crypter
def crypter(self): """The actual keyczar crypter""" if not hasattr(self, '_crypter'): # initialise the Keyczar keysets if not self.keyset_location: raise ValueError('No encrypted keyset location!') reader = keyczar.readers.CreateReader(self.keyset_loca...
Index documents of a specified mapping type.
def index_objects(mapping_type, ids, chunk_size=100, es=None, index=None): """Index documents of a specified mapping type. This allows for asynchronous indexing. If a mapping_type extends Indexable, you can add a ``post_save`` hook for the model that it's based on like this:: @receiver(dbsign...
Remove documents of a specified mapping_type from the index.
def unindex_objects(mapping_type, ids, es=None, index=None): """Remove documents of a specified mapping_type from the index. This allows for asynchronous deleting. If a mapping_type extends Indexable, you can add a ``pre_delete`` hook for the model that it's based on like this:: @receiver(dbs...
Returns specified link instance as JSON.
def get_json(self, link): """ Returns specified link instance as JSON. :param link: the link instance. :rtype: JSON. """ return json.dumps({ 'id': link.id, 'title': link.title, 'url': link.get_absolute_url(), ...
Create the cipher object to encrypt or decrypt a payload.
def _create_cipher(self, password, salt, IV): """ Create the cipher object to encrypt or decrypt a payload. """ from Crypto.Protocol.KDF import PBKDF2 from Crypto.Cipher import AES pw = PBKDF2(password, salt, dkLen=self.block_size) return AES.new(pw[:self.block_si...
Initialize a new password file and set the reference password.
def _init_file(self): """ Initialize a new password file and set the reference password. """ self.keyring_key = self._get_new_password() # set a reference password, used to check that the password provided # matches for subsequent checks. self.set_password('keyri...
Check if the file exists and has the expected password reference.
def _check_file(self): """ Check if the file exists and has the expected password reference. """ if not os.path.exists(self.file_path): return False self._migrate() config = configparser.RawConfigParser() config.read(self.file_path) try: ...
check for a valid version an existing scheme implies an existing version as well
def _check_version(self, config): """ check for a valid version an existing scheme implies an existing version as well return True, if version is valid, and False otherwise """ try: self.file_version = config.get( escape_for_ini('keyring-setti...
Unlock this keyring by getting the password for the keyring from the user.
def _unlock(self): """ Unlock this keyring by getting the password for the keyring from the user. """ self.keyring_key = getpass.getpass( 'Please enter password for encrypted keyring: ') try: ref_pw = self.get_password('keyring-setting', 'password ...
Single char escape. Return the char escaped if not already legal
def _escape_char(c): "Single char escape. Return the char, escaped if not already legal" if isinstance(c, int): c = _unichr(c) return c if c in LEGAL_CHARS else ESCAPE_FMT % ord(c)
Inverse of escape.
def unescape(value): """ Inverse of escape. """ pattern = ESCAPE_FMT.replace('%02X', '(?P<code>[0-9A-Fa-f]{2})') # the pattern must be bytes to operate on bytes pattern_bytes = pattern.encode('ascii') re_esc = re.compile(pattern_bytes) return re_esc.sub(_unescape_code, value.encode('asci...
Get password of the username for the service
def _find_passwords(self, service, username, deleting=False): """Get password of the username for the service """ passwords = [] service = self._safe_string(service) username = self._safe_string(username) for attrs_tuple in (('username', 'service'), ('user', 'domain')): ...
Get password of the username for the service
def get_password(self, service, username): """Get password of the username for the service """ items = self._find_passwords(service, username) if not items: return None secret = items[0].secret return ( secret if isinstance(secret, six...
Set password for the username of the service
def set_password(self, service, username, password): """Set password for the username of the service """ service = self._safe_string(service) username = self._safe_string(username) password = self._safe_string(password) attrs = GnomeKeyring.Attribute.list_new() Gn...
Delete the password for the username of the service.
def delete_password(self, service, username): """Delete the password for the username of the service. """ items = self._find_passwords(service, username, deleting=True) if not items: raise PasswordDeleteError("Password not found") for current in items: res...
Convert unicode to string as gnomekeyring barfs on unicode
def _safe_string(self, source, encoding='utf-8'): """Convert unicode to string as gnomekeyring barfs on unicode""" if not isinstance(source, str): return source.encode(encoding) return str(source)
Returns context dictionary for view.
def get_context_data(self, **kwargs): """ Returns context dictionary for view. :rtype: dict. """ kwargs.update({ 'view': self, 'email_form': EmailLinkForm(), 'external_form': ExternalLinkForm(), 'type_email': ...
Returns POST response.
def post(self, request, *args, **kwargs): """ Returns POST response. :param request: the request instance. :rtype: django.http.HttpResponse. """ form = None link_type = int(request.POST.get('link_type', 0)) if link_type == Link.LINK_TYPE_EMAIL: ...
Returns form class to use in the view.
def get_form_class(self): """ Returns form class to use in the view. :rtype: django.forms.ModelForm. """ if self.object.link_type == Link.LINK_TYPE_EMAIL: return EmailLinkForm elif self.object.link_type == Link.LINK_TYPE_EXTERNAL: return ExternalL...
Get password of the username for the service
def get_password(self, service, username): """Get password of the username for the service """ try: # fetch the password key = self._key_for_service(service) hkey = winreg.OpenKey(winreg.HKEY_CURRENT_USER, key) password_saved = winreg.QueryValueEx(...
Write the password to the registry
def set_password(self, service, username, password): """Write the password to the registry """ # encrypt the password password_encrypted = _win_crypto.encrypt(password.encode('utf-8')) # encode with base64 password_base64 = base64.encodestring(password_encrypted) ...
Delete the password for the username of the service.
def delete_password(self, service, username): """Delete the password for the username of the service. """ try: key_name = self._key_for_service(service) hkey = winreg.OpenKey( winreg.HKEY_CURRENT_USER, key_name, 0, winreg.KEY_ALL_ACCESS) ...
Encrypt the password.
def encrypt(self, password): """Encrypt the password. """ if not password or not self._crypter: return password or b'' return self._crypter.encrypt(password)
Decrypt the password.
def decrypt(self, password_encrypted): """Decrypt the password. """ if not password_encrypted or not self._crypter: return password_encrypted or b'' return self._crypter.decrypt(password_encrypted)
Open the password file in the specified mode
def _open(self, mode='r'): """Open the password file in the specified mode """ open_file = None writeable = 'w' in mode or 'a' in mode or '+' in mode try: # NOTE: currently the MemOpener does not split off any filename # which causes errors on close(...
load the passwords from the config file
def config(self): """load the passwords from the config file """ if not hasattr(self, '_config'): raw_config = configparser.RawConfigParser() f = self._open() if f: raw_config.readfp(f) f.close() self._config = raw_c...
Read the password from the file.
def get_password(self, service, username): """Read the password from the file. """ service = escape_for_ini(service) username = escape_for_ini(username) # fetch the password try: password_base64 = self.config.get(service, username).encode() # deco...
Write the password in the file.
def set_password(self, service, username, password): """Write the password in the file. """ service = escape_for_ini(service) username = escape_for_ini(username) # encrypt the password password = password or '' password_encrypted = self.encrypt(password.encode('u...
Returns queryset limited to categories with live Entry instances.
def get_queryset(self): """ Returns queryset limited to categories with live Entry instances. :rtype: django.db.models.query.QuerySet. """ queryset = super(LiveEntryCategoryManager, self).get_queryset() return queryset.filter(tag__in=[ entry_tag.tag ...
Returns tuple ( Entry instance created ) for specified model instance.
def get_for_model(self, model): """ Returns tuple (Entry instance, created) for specified model instance. :rtype: wagtailplus.wagtailrelations.models.Entry. """ return self.get_or_create( content_type = ContentType.objects.get_for_model(model), ...
Returns queryset of Entry instances assigned to specified tag which can be a PK value a slug value or a Tag instance.
def get_for_tag(self, tag): """ Returns queryset of Entry instances assigned to specified tag, which can be a PK value, a slug value, or a Tag instance. :param tag: tag PK, slug, or instance. :rtype: django.db.models.query.QuerySet. """ tag_filter = {'tag': tag} ...
Returns queryset of EntryTag instances for specified category.
def for_category(self, category, live_only=False): """ Returns queryset of EntryTag instances for specified category. :param category: the Category instance. :param live_only: flag to include only "live" entries. :rtype: django.db.models.query.QuerySet. """ filte...
Returns queryset of Entry instances related to specified Entry instance.
def related_to(self, entry, live_only=False): """ Returns queryset of Entry instances related to specified Entry instance. :param entry: the Entry instance. :param live_only: flag to include only "live" entries. :rtype: django.db.models.query.QuerySet. """ ...
Returns a ChosenView class that extends specified chooser class.
def chosen_view_factory(chooser_cls): """ Returns a ChosenView class that extends specified chooser class. :param chooser_cls: the class to extend. :rtype: class. """ class ChosenView(chooser_cls): #noinspection PyUnusedLocal def get(self, request, *args, **kwargs): ...
Processes an invalid form submittal.
def form_invalid(self, form): """ Processes an invalid form submittal. :param form: the form instance. :rtype: django.http.HttpResponse. """ context = self.get_context_data(form=form) #noinspection PyUnresolvedReferences return render_modal_workflow( ...
Processes a valid form submittal.
def form_valid(self, form): """ Processes a valid form submittal. :param form: the form instance. :rtype: django.http.HttpResponse. """ #noinspection PyAttributeOutsideInit self.object = form.save() # Index the link. for backend in get_search_bac...
Returns GET response.
def get(self, request, *args, **kwargs): """ Returns GET response. :param request: the request instance. :rtype: django.http.HttpResponse. """ #noinspection PyAttributeOutsideInit self.object_list = self.get_queryset() context = self.get_co...
Returns the keyword arguments for instantiating the form.
def get_form_kwargs(self): """ Returns the keyword arguments for instantiating the form. :rtype: dict. """ kwargs = { 'initial': self.get_initial(), 'prefix': self.get_prefix(), } #noinspection PyUnresolvedReferences if self.re...
Creates EntryTag for Entry corresponding to specified ItemBase instance.
def create_entry_tag(sender, instance, created, **kwargs): """ Creates EntryTag for Entry corresponding to specified ItemBase instance. :param sender: the sending ItemBase class. :param instance: the ItemBase instance. """ from ..models import ( Entry, EntryTag ) en...
Deletes EntryTag for Entry corresponding to specified TaggedItemBase instance.
def delete_entry_tag(sender, instance, **kwargs): """ Deletes EntryTag for Entry corresponding to specified TaggedItemBase instance. :param sender: the sending TaggedItemBase class. :param instance: the TaggedItemBase instance. """ from ..models import ( Entry, EntryTag ...
Deletes Entry instance corresponding to specified instance.
def delete_entry(sender, instance, **kwargs): """ Deletes Entry instance corresponding to specified instance. :param sender: the sending class. :param instance: the instance being deleted. """ from ..models import Entry Entry.objects.get_for_model(instance)[0].delete()
Updates attributes for Entry instance corresponding to specified instance.
def update_entry_attributes(sender, instance, **kwargs): """ Updates attributes for Entry instance corresponding to specified instance. :param sender: the sending class. :param instance: the instance being saved. """ from ..models import Entry entry = Entry.objects.get_for_model(instan...
Returns paginated queryset of PageRevision instances for specified Page instance.
def get_revisions(page, page_num=1): """ Returns paginated queryset of PageRevision instances for specified Page instance. :param page: the page instance. :param page_num: the pagination page number. :rtype: django.db.models.query.QuerySet. """ revisions = page.revisions.order_by('-cr...
Returns GET response for specified page revisions.
def page_revisions(request, page_id, template_name='wagtailrollbacks/edit_handlers/revisions.html'): """ Returns GET response for specified page revisions. :param request: the request instance. :param page_id: the page ID. :param template_name: the template name. :rtype: django.http.HttpRespons...
Returns GET response for specified page preview.
def preview_page_version(request, revision_id): """ Returns GET response for specified page preview. :param request: the request instance. :param reversion_pk: the page revision ID. :rtype: django.http.HttpResponse. """ revision = get_object_or_404(PageRevision, pk=revision_id) if not ...
Handles page reversion process ( GET and POST ).
def confirm_page_reversion(request, revision_id, template_name='wagtailrollbacks/pages/confirm_reversion.html'): """ Handles page reversion process (GET and POST). :param request: the request instance. :param revision_id: the page revision ID. :param template_name: the template name. :rtype: dj...
Get password of the username for the service
def get_password(self, service, username): """Get password of the username for the service """ result = self._get_entry(self._keyring, service, username) if result: result = self._decrypt(result) return result
Set password for the username of the service
def set_password(self, service, username, password): """Set password for the username of the service """ password = self._encrypt(password or '') keyring_working_copy = copy.deepcopy(self._keyring) service_entries = keyring_working_copy.get(service) if not service_entries...
Helper to actually write the keyring to Google
def _save_keyring(self, keyring_dict): """Helper to actually write the keyring to Google""" import gdata result = self.OK file_contents = base64.urlsafe_b64encode(pickle.dumps(keyring_dict)) try: if self.docs_entry: extra_headers = {'Content-Type': 'te...
Calculate the request token ( tk ) of a string: param text: str The text to calculate a token for: param seed: str The seed to use. By default this is the number of hours since epoch
def calculate_token(self, text, seed=None): """ Calculate the request token (`tk`) of a string :param text: str The text to calculate a token for :param seed: str The seed to use. By default this is the number of hours since epoch """ if seed is None: seed = self._ge...
Make HTTP request raising an exception if it fails.
def _request(method, url, session=None, **kwargs): """Make HTTP request, raising an exception if it fails. """ url = BASE_URL + url if session: request_func = getattr(session, method) else: request_func = getattr(requests, method) response = request_func(url, **kwargs) # rai...
Send a dweet to dweet. io
def _send_dweet(payload, url, params=None, session=None): """Send a dweet to dweet.io """ data = json.dumps(payload) headers = {'Content-type': 'application/json'} return _request('post', url, data=data, headers=headers, params=params, session=session)
Send a dweet to dweet. io for a thing with a known name
def dweet_for(thing_name, payload, key=None, session=None): """Send a dweet to dweet.io for a thing with a known name """ if key is not None: params = {'key': key} else: params = None return _send_dweet(payload, '/dweet/for/{0}'.format(thing_name), params=params, session=session)
Read all the dweets for a dweeter
def get_dweets_for(thing_name, key=None, session=None): """Read all the dweets for a dweeter """ if key is not None: params = {'key': key} else: params = None return _request('get', '/get/dweets/for/{0}'.format(thing_name), params=params, session=None)
Remove a lock ( no matter what it s connected to ).
def remove_lock(lock, key, session=None): """Remove a lock (no matter what it's connected to). """ return _request('get', '/remove/lock/{0}'.format(lock), params={'key': key}, session=session)
Lock a thing ( prevents unauthed dweets for the locked thing )
def lock(thing_name, lock, key, session=None): """Lock a thing (prevents unauthed dweets for the locked thing) """ return _request('get', '/lock/{0}'.format(thing_name), params={'key': key, 'lock': lock}, session=session)
Unlock a thing
def unlock(thing_name, key, session=None): """Unlock a thing """ return _request('get', '/unlock/{0}'.format(thing_name), params={'key': key}, session=session)
Set an alert on a thing with the given condition
def set_alert(thing_name, who, condition, key, session=None): """Set an alert on a thing with the given condition """ return _request('get', '/alert/{0}/when/{1}/{2}'.format( ','.join(who), thing_name, quote(condition), ), params={'key': key}, session=session)
Set an alert on a thing with the given condition
def get_alert(thing_name, key, session=None): """Set an alert on a thing with the given condition """ return _request('get', '/get/alert/for/{0}'.format(thing_name), params={'key': key}, session=session)
Remove an alert for the given thing
def remove_alert(thing_name, key, session=None): """Remove an alert for the given thing """ return _request('get', '/remove/alert/for/{0}'.format(thing_name), params={'key': key}, session=session)
list all product sets for current user
def get_product_sets(self): """ list all product sets for current user """ # ensure we are using api url without a specific product set id api_url = super(ProductSetAPI, self).base_url return self.client.get(api_url)
BE NOTICED: this will delete all product sets for current user
def delete_all_product_sets(self): """ BE NOTICED: this will delete all product sets for current user """ # ensure we are using api url without a specific product set id api_url = super(ProductSetAPI, self).base_url return self.client.delete(api_url)
This function ( and backend API ) is being obsoleted. Don t use it anymore.
def get_products(self, product_ids): """ This function (and backend API) is being obsoleted. Don't use it anymore. """ if self.product_set_id is None: raise ValueError('product_set_id must be specified') data = {'ids': product_ids} return self.client.get(self....
Check if the timeout has been reached and raise a StopIteration if so.
def _check_stream_timeout(started, timeout): """Check if the timeout has been reached and raise a `StopIteration` if so. """ if timeout: elapsed = datetime.datetime.utcnow() - started if elapsed.seconds > timeout: raise StopIteration
Yields dweets as received from dweet. io s streaming API
def _listen_for_dweets_from_response(response): """Yields dweets as received from dweet.io's streaming API """ streambuffer = '' for byte in response.iter_content(): if byte: streambuffer += byte.decode('ascii') try: dweet = json.loads(streambuffer.splitli...
Create a real - time subscription to dweets
def listen_for_dweets_from(thing_name, timeout=900, key=None, session=None): """Create a real-time subscription to dweets """ url = BASE_URL + '/listen/for/dweets/from/{0}'.format(thing_name) session = session or requests.Session() if key is not None: params = {'key': key} else: ...
curl - X POST \ - H x - ca - version: 1. 0 \ - H x - ca - accesskeyid: YourAccessId \ - d service_id = p4dkh2sg&request_id = c13ed5aa - d6d2 - 11e8 - ba11 - 02420a582a05&description = blahlblah \ https:// api. productai. cn/ bad_cases/ _0000204
def add(self, service_id, request_id, description=None, details=None): if not service_id: raise ValueError('service_id is required') if not request_id: raise ValueError('request_id is required') """ curl -X POST \ -H 'x-ca-version: 1.0' \ ...
Executes a packer build
def build(self, parallel=True, debug=False, force=False, machine_readable=False): """Executes a `packer build` :param bool parallel: Run builders in parallel :param bool debug: Run in debug mode :param bool force: Force artifact output even if exists :param bool ma...
Implements the packer fix function
def fix(self, to_file=None): """Implements the `packer fix` function :param string to_file: File to output fixed template to """ self.packer_cmd = self.packer.fix self._add_opt(self.packerfile) result = self.packer_cmd() if to_file: with open(to_fil...
Inspects a Packer Templates file ( packer inspect - machine - readable )
def inspect(self, mrf=True): """Inspects a Packer Templates file (`packer inspect -machine-readable`) To return the output in a readable form, the `-machine-readable` flag is appended automatically, afterwhich the output is parsed and returned as a dict of the following format: ...
Implmenets the packer push function
def push(self, create=True, token=False): """Implmenets the `packer push` function UNTESTED! Must be used alongside an Atlas account """ self.packer_cmd = self.packer.push self._add_opt('-create=true' if create else None) self._add_opt('-tokn={0}'.format(token) if token...
Validates a Packer Template file ( packer validate )
def validate(self, syntax_only=False): """Validates a Packer Template file (`packer validate`) If the validation failed, an `sh` exception will be raised. :param bool syntax_only: Whether to validate the syntax only without validating the configuration itself. """ self.p...
Appends base arguments to packer commands.
def _append_base_arguments(self): """Appends base arguments to packer commands. -except, -only, -var and -var-file are appeneded to almost all subcommands in packer. As such this can be called to add these flags to the subcommand. """ if self.exc and self.only: ...
Parses the machine - readable output packer inspect provides.
def _parse_inspection_output(self, output): """Parses the machine-readable output `packer inspect` provides. See the inspect method for more info. This has been tested vs. Packer v0.7.5 """ parts = {'variables': [], 'builders': [], 'provisioners': []} for line in output....
Perform an HTTP POST request for a given url. Returns the response object.
def post(self, url, data, headers=None): """ Perform an HTTP POST request for a given url. Returns the response object. """ return self._request('POST', url, data, headers=headers)
Perform an HTTP PUT request for a given url. Returns the response object.
def put(self, url, data, headers=None): """ Perform an HTTP PUT request for a given url. Returns the response object. """ return self._request('PUT', url, data, headers=headers)