INSTRUCTION stringlengths 1 8.43k | RESPONSE stringlengths 75 104k |
|---|---|
Fetch messages for given user. Returns None if no such message exists. | def get_messages(user):
"""
Fetch messages for given user. Returns None if no such message exists.
:param user: User instance
"""
key = _user_key(user)
result = cache.get(key)
if result:
cache.delete(key)
return result
return None |
Check for messages for this user and if it exists call the messages API with it | def process_response(self, request, response):
"""
Check for messages for this user and, if it exists,
call the messages API with it
"""
if hasattr(request, "session") and hasattr(request, "user") and request.user.is_authenticated():
msgs = get_messages(request.user)
... |
Checks the config. json file for default settings and auth values. | def check_config_file(msg):
"""
Checks the config.json file for default settings and auth values.
Args:
:msg: (Message class) an instance of a message class.
"""
with jsonconfig.Config("messages", indent=4) as cfg:
verify_profile_name(msg, cfg)
retrieve_data_from_config(msg... |
Verifies the profile name exists in the config. json file. | def verify_profile_name(msg, cfg):
"""
Verifies the profile name exists in the config.json file.
Args:
:msg: (Message class) an instance of a message class.
:cfg: (jsonconfig.Config) config instance.
"""
if msg.profile not in cfg.data:
raise UnknownProfileError(msg.profile) |
Update msg attrs with values from the profile configuration if the msg. attr = None else leave it alone. | def retrieve_data_from_config(msg, cfg):
"""
Update msg attrs with values from the profile configuration if the
msg.attr=None, else leave it alone.
Args:
:msg: (Message class) an instance of a message class.
:cfg: (jsonconfig.Config) config instance.
"""
msg_type = msg.__class__... |
Retrieve auth from profile configuration and set in msg. auth attr. | def retrieve_pwd_from_config(msg, cfg):
"""
Retrieve auth from profile configuration and set in msg.auth attr.
Args:
:msg: (Message class) an instance of a message class.
:cfg: (jsonconfig.Config) config instance.
"""
msg_type = msg.__class__.__name__.lower()
key_fmt = msg.profi... |
Updates the profile s config entry with values set in each attr by the user. This will overwrite existing values. | def update_config_data(msg, cfg):
"""
Updates the profile's config entry with values set in each attr by the
user. This will overwrite existing values.
Args:
:msg: (Message class) an instance of a message class.
:cfg: (jsonconfig.Config) config instance.
"""
for attr in msg:
... |
Updates the profile s auth entry with values set by the user. This will overwrite existing values. | def update_config_pwd(msg, cfg):
"""
Updates the profile's auth entry with values set by the user.
This will overwrite existing values.
Args:
:msg: (Message class) an instance of a message class.
:cfg: (jsonconfig.Config) config instance.
"""
msg_type = msg.__class__.__name__.lo... |
Create a profile for the given message type. | def create_config_profile(msg_type):
"""
Create a profile for the given message type.
Args:
:msg_type: (str) message type to create config entry.
"""
msg_type = msg_type.lower()
if msg_type not in CONFIG.keys():
raise UnsupportedMessageTypeError(msg_type)
display_required_... |
Display the required items needed to configure a profile for the given message type. | def display_required_items(msg_type):
"""
Display the required items needed to configure a profile for the given
message type.
Args:
:msg_type: (str) message type to create config entry.
"""
print("Configure a profile for: " + msg_type)
print("You will need the following information... |
Get the required settings from the user and return as a dict. | def get_data_from_user(msg_type):
"""Get the required 'settings' from the user and return as a dict."""
data = {}
for k, v in CONFIG[msg_type]["settings"].items():
data[k] = input(v + ": ")
return data |
Get the required auth from the user and return as a dict. | def get_auth_from_user(msg_type):
"""Get the required 'auth' from the user and return as a dict."""
auth = []
for k, v in CONFIG[msg_type]["auth"].items():
auth.append((k, getpass(v + ": ")))
return OrderedDict(auth) |
Create the profile entry. | def configure_profile(msg_type, profile_name, data, auth):
"""
Create the profile entry.
Args:
:msg_type: (str) message type to create config entry.
:profile_name: (str) name of the profile entry
:data: (dict) dict values for the 'settings'
:auth: (dict) auth parameters
... |
Write the settings into the data portion of the cfg. | def write_data(msg_type, profile_name, data, cfg):
"""
Write the settings into the data portion of the cfg.
Args:
:msg_type: (str) message type to create config entry.
:profile_name: (str) name of the profile entry
:data: (dict) dict values for the 'settings'
:cfg: (jsonconf... |
Write the settings into the auth portion of the cfg. | def write_auth(msg_type, profile_name, auth, cfg):
"""
Write the settings into the auth portion of the cfg.
Args:
:msg_type: (str) message type to create config entry.
:profile_name: (str) name of the profile entry
:auth: (dict) auth parameters
:cfg: (jsonconfig.Config) conf... |
Build the message params. | def _construct_message(self):
"""Build the message params."""
self.message["text"] = ""
if self.from_:
self.message["text"] += "From: " + self.from_ + "\n"
if self.subject:
self.message["text"] += "Subject: " + self.subject + "\n"
self.message["text"] += ... |
Add attachments. | def _add_attachments(self):
"""Add attachments."""
if self.attachments:
if not isinstance(self.attachments, list):
self.attachments = [self.attachments]
self.message["attachments"] = [
{"image_url": url, "author_name": ""} for url in self.attachme... |
Send the message via HTTP POST default is json - encoded. | def send(self, encoding="json"):
"""Send the message via HTTP POST, default is json-encoded."""
self._construct_message()
if self.verbose:
print(
"Debugging info"
"\n--------------"
"\n{} Message created.".format(timestamp())
... |
Set the message token/ channel then call the bas class constructor. | def _construct_message(self):
"""Set the message token/channel, then call the bas class constructor."""
self.message = {"token": self._auth, "channel": self.channel}
super()._construct_message() |
Constructs a message class and sends the message. Defaults to sending synchronously. Set send_async = True to send asynchronously. | def send(msg_type, send_async=False, *args, **kwargs):
"""
Constructs a message class and sends the message.
Defaults to sending synchronously. Set send_async=True to send
asynchronously.
Args:
:msg_type: (str) the type of message to send, i.e. 'Email'
:send_async: (bool) default i... |
Factory function to return the specified message instance. | def message_factory(msg_type, msg_types=MESSAGE_TYPES, *args, **kwargs):
"""
Factory function to return the specified message instance.
Args:
:msg_type: (str) the type of message to send, i.e. 'Email'
:msg_types: (str, list, or set) the supported message types
:kwargs: (dict) keywor... |
A credential property factory for each message class that will set private attributes and return obfuscated credentials when requested. | def credential_property(cred):
"""
A credential property factory for each message class that will set
private attributes and return obfuscated credentials when requested.
"""
def getter(instance):
return "***obfuscated***"
def setter(instance, value):
private = "_" + cred
... |
A property factory that will dispatch the to a specific validator function that will validate the user s input to ensure critical parameters are of a specific type. | def validate_property(attr):
"""
A property factory that will dispatch the to a specific validator function
that will validate the user's input to ensure critical parameters are of a
specific type.
"""
def getter(instance):
return instance.__dict__[attr]
def setter(instance, value)... |
Base function to validate input dispatched via message type. | def validate_input(msg_type, attr, value):
"""Base function to validate input, dispatched via message type."""
try:
valid = {
"Email": validate_email,
"Twilio": validate_twilio,
"SlackWebhook": validate_slackwebhook,
"SlackPost": validate_slackpost,
... |
Checker function all validate_ * functions below will call. Raises InvalidMessageInputError if input is not valid as per given func. | def check_valid(msg_type, attr, value, func, exec_info):
"""
Checker function all validate_* functions below will call.
Raises InvalidMessageInputError if input is not valid as per
given func.
"""
if value is not None:
if isinstance(value, MutableSequence):
for v in value:
... |
Twilio input validator function. | def validate_twilio(attr, value):
"""Twilio input validator function."""
if attr in ("from_", "to"):
check_valid("Twilio", attr, value, validus.isphone, "phone number")
elif attr in ("attachments"):
check_valid("Twilio", attr, value, validus.isurl, "url") |
SlackPost input validator function. | def validate_slackpost(attr, value):
"""SlackPost input validator function."""
if attr in ("channel", "credentials"):
if not isinstance(value, str):
raise InvalidMessageInputError("SlackPost", attr, value, "string")
elif attr in ("attachments"):
check_valid("SlackPost", attr, val... |
WhatsApp input validator function. | def validate_whatsapp(attr, value):
"""WhatsApp input validator function."""
if attr in ("from_", "to"):
if value is not None and "whatsapp:" in value:
value = value.split("whatsapp:+")[-1]
check_valid(
"WhatsApp",
attr,
value,
validus.... |
Creates a running coroutine to receive message instances and send them in a futures executor. | def _send_coroutine():
"""
Creates a running coroutine to receive message instances and send
them in a futures executor.
"""
with PoolExecutor() as executor:
while True:
msg = yield
future = executor.submit(msg.send)
future.add_done_callback(_exception_han... |
Add a message to the futures executor. | def add_message(self, msg):
"""Add a message to the futures executor."""
try:
self._coro.send(msg)
except AttributeError:
raise UnsupportedMessageTypeError(msg.__class__.__name__) |
Reads message body if specified via filepath. | def get_body_from_file(kwds):
"""Reads message body if specified via filepath."""
if kwds["file"] and os.path.isfile(kwds["file"]):
kwds["body"] = open(kwds["file"], "r").read()
kwds["file"] = None |
Gets rid of args with value of None as well as select keys. | def trim_args(kwds):
"""Gets rid of args with value of None, as well as select keys."""
reject_key = ("type", "types", "configure")
reject_val = (None, ())
kwargs = {
k: v for k, v in kwds.items() if k not in reject_key and v not in reject_val
}
for k, v in kwargs.items():
if k i... |
Do some final preprocessing and send the message. | def send_message(msg_type, kwds):
"""Do some final preprocessing and send the message."""
if kwds["file"]:
get_body_from_file(kwds)
kwargs = trim_args(kwds)
send(msg_type, send_async=False, **kwargs) |
Lookup chat_id of username if chat_id is unknown via API call. | def get_chat_id(self, username):
"""Lookup chat_id of username if chat_id is unknown via API call."""
if username is not None:
chats = requests.get(self.base_url + "/getUpdates").json()
user = username.split("@")[-1]
for chat in chats["result"]:
if cha... |
Build the message params. | def _construct_message(self):
"""Build the message params."""
self.message["chat_id"] = self.chat_id
self.message["text"] = ""
if self.from_:
self.message["text"] += "From: " + self.from_ + "\n"
if self.subject:
self.message["text"] += "Subject: " + self.s... |
send via HTTP Post. | def _send_content(self, method="/sendMessage"):
"""send via HTTP Post."""
url = self.base_url + method
try:
resp = requests.post(url, json=self.message)
resp.raise_for_status()
except requests.exceptions.HTTPError as e:
raise MessageSendError(e)
... |
Start sending the message and attachments. | def send(self):
"""Start sending the message and attachments."""
self._construct_message()
if self.verbose:
print(
"Debugging info"
"\n--------------"
"\n{} Message created.".format(timestamp())
)
self._send_conten... |
Send the SMS/ MMS message. Set self. sid to return code of message. | def send(self):
"""
Send the SMS/MMS message.
Set self.sid to return code of message.
"""
url = (
"https://api.twilio.com/2010-04-01/Accounts/"
+ self._auth[0]
+ "/Messages.json"
)
data = {
"From": self.from_,
... |
Return an SMTP servername guess from outgoing email address. | def get_server(address=None):
"""Return an SMTP servername guess from outgoing email address."""
if address:
domain = address.split("@")[1]
try:
return SMTP_SERVERS[domain]
except KeyError:
return ("smtp." + domain, 465)
return ... |
Put the parts of the email together. | def _generate_email(self):
"""Put the parts of the email together."""
self.message = MIMEMultipart()
self._add_header()
self._add_body()
self._add_attachments() |
Add email header info. | def _add_header(self):
"""Add email header info."""
self.message["From"] = self.from_
self.message["Subject"] = self.subject
if self.to:
self.message["To"] = self.list_to_string(self.to)
if self.cc:
self.message["Cc"] = self.list_to_string(self.cc)
... |
Add body content of email. | def _add_body(self):
"""Add body content of email."""
if self.body:
b = MIMEText("text", "plain")
b.set_payload(self.body)
self.message.attach(b) |
Add required attachments. | def _add_attachments(self):
"""Add required attachments."""
num_attached = 0
if self.attachments:
if isinstance(self.attachments, str):
self.attachments = [self.attachments]
for item in self.attachments:
doc = MIMEApplication(open(item, "r... |
Start session with email server. | def _get_session(self):
"""Start session with email server."""
if self.port in (465, "465"):
session = self._get_ssl()
elif self.port in (587, "587"):
session = self._get_tls()
try:
session.login(self.from_, self._auth)
except SMTPResponseExce... |
Get an SMTP session with SSL. | def _get_ssl(self):
"""Get an SMTP session with SSL."""
return smtplib.SMTP_SSL(
self.server, self.port, context=ssl.create_default_context()
) |
Get an SMTP session with TLS. | def _get_tls(self):
"""Get an SMTP session with TLS."""
session = smtplib.SMTP(self.server, self.port)
session.ehlo()
session.starttls(context=ssl.create_default_context())
session.ehlo()
return session |
Send the message. First a message is constructed then a session with the email servers is created finally the message is sent and the session is stopped. | def send(self):
"""
Send the message.
First, a message is constructed, then a session with the email
servers is created, finally the message is sent and the session
is stopped.
"""
self._generate_email()
if self.verbose:
print(
... |
Remove tags from a file. | def delete(self, filename=None):
"""Remove tags from a file."""
if self.tags is not None:
if filename is None:
filename = self.filename
else:
warnings.warn(
"delete(filename=...) is deprecated, reload the file",
... |
Save metadata tags. | def save(self, filename=None, **kwargs):
"""Save metadata tags."""
if filename is None:
filename = self.filename
else:
warnings.warn(
"save(filename=...) is deprecated, reload the file",
DeprecationWarning)
if self.tags is not None... |
Releases renderer resources associated with this image. | def unload(self):
'''Releases renderer resources associated with this image.'''
if self._handle != -1:
lib.UnloadImage(self._handle)
self._handle = -1 |
Get an image that refers to the given rectangle within this image. The image data is not actually copied ; if the image region is rendered into it will affect this image. | def get_region(self, x1, y1, x2, y2):
'''Get an image that refers to the given rectangle within this image. The image data is not actually
copied; if the image region is rendered into, it will affect this image.
:param int x1: left edge of the image region to return
:param int y1: top ... |
main program loop | def main( argv ):
"""main program loop"""
global output_dir
try:
opts, args = getopt.getopt( sys.argv[1:], \
"hb", \
["help", "backup"] )
except getopt.GetoptError:
usage()
sys.exit( 2 )
if ar... |
Instantiates and returns a: py: class: route53. connection. Route53Connection instance which is how you ll start your interactions with the Route 53 API. | def connect(aws_access_key_id=None, aws_secret_access_key=None, **kwargs):
"""
Instantiates and returns a :py:class:`route53.connection.Route53Connection`
instance, which is how you'll start your interactions with the Route 53
API.
:keyword str aws_access_key_id: Your AWS Access Key ID
:keyword... |
Validate keys and values. | def validate(self):
"""Validate keys and values.
Check to make sure every key used is a valid Vorbis key, and
that every value used is a valid Unicode or UTF-8 string. If
any invalid keys or values are found, a ValueError is raised.
In Python 3 all keys and values have to be a ... |
Clear all keys from the comment. | def clear(self):
"""Clear all keys from the comment."""
for i in list(self._internal):
self._internal.remove(i) |
Return a string representation of the data. | def write(self, framing=True):
"""Return a string representation of the data.
Validation is always performed, so calling this function on
invalid data may raise a ValueError.
Keyword arguments:
* framing -- if true, append a framing bit (see load)
"""
self.val... |
Read the chunks data | def read(self):
"""Read the chunks data"""
self.__fileobj.seek(self.data_offset)
self.data = self.__fileobj.read(self.data_size) |
Removes the chunk from the file | def delete(self):
"""Removes the chunk from the file"""
delete_bytes(self.__fileobj, self.size, self.offset)
if self.parent_chunk is not None:
self.parent_chunk.resize(self.parent_chunk.data_size - self.size) |
Update the size of the chunk | def resize(self, data_size):
"""Update the size of the chunk"""
self.__fileobj.seek(self.offset + 4)
self.__fileobj.write(pack('>I', data_size))
if self.parent_chunk is not None:
size_diff = self.data_size - data_size
self.parent_chunk.resize(self.parent_chunk.dat... |
Insert a new chunk at the end of the IFF file | def insert_chunk(self, id_):
"""Insert a new chunk at the end of the IFF file"""
if not isinstance(id_, text_type):
id_ = id_.decode('ascii')
if not is_valid_chunk_id(id_):
raise KeyError("AIFF key must be four ASCII characters.")
self.__fileobj.seek(self.__nex... |
Save ID3v2 data to the AIFF file | def save(self, filename=None, v2_version=4, v23_sep='/'):
"""Save ID3v2 data to the AIFF file"""
framedata = self._prepare_framedata(v2_version, v23_sep)
framesize = len(framedata)
if filename is None:
filename = self.filename
# Unlike the parent ID3.save method, w... |
Completely removes the ID3 chunk from the AIFF file | def delete(self, filename=None):
"""Completely removes the ID3 chunk from the AIFF file"""
if filename is None:
filename = self.filename
delete(filename)
self.clear() |
Load stream and tag information from a file. | def load(self, filename, **kwargs):
"""Load stream and tag information from a file."""
self.filename = filename
try:
self.tags = _IFFID3(filename, **kwargs)
except ID3Error:
self.tags = None
try:
fileobj = open(filename, "rb")
sel... |
parse a C source file and add its blocks to the processor s list | def parse_file( self, filename ):
"""parse a C source file, and add its blocks to the processor's list"""
self.reset()
self.filename = filename
fileinput.close()
self.format = None
self.lineno = 0
self.lines = []
for line in fileinput.input( filename ... |
process a normal line and check whether it is the start of a new block | def process_normal_line( self, line ):
"""process a normal line and check whether it is the start of a new block"""
for f in re_source_block_formats:
if f.start.match( line ):
self.add_block_lines()
self.format = f
self.lineno = fileinput.file... |
add the current accumulated lines and create a new block | def add_block_lines( self ):
"""add the current accumulated lines and create a new block"""
if self.lines != []:
block = SourceBlock( self, self.filename, self.lineno, self.lines )
self.blocks.append( block )
self.format = None
self.lines = [] |
Draw a string with the given font. | def draw_string(font, text, x, y, width=None, height=None, align=Alignment.left, vertical_align=VerticalAlignment.baseline):
'''Draw a string with the given font.
:note: Text alignment and word-wrapping is not yet implemented. The text is rendered with the left edge and
baseline at ``(x, y)``.
:p... |
Draw a prepared: class: GlyphLayout | def draw_glyph_layout(glyph_layout):
'''Draw a prepared :class:`GlyphLayout`
'''
pushed_color = False
# Draw lines
for line in glyph_layout.lines:
x = line.x
y = line.y
for run in line.runs:
style = run.style
if style.color is not None:
... |
Parses a standard ISO 8601 time string. The Route53 API uses these here and there. | def parse_iso_8601_time_str(time_str):
"""
Parses a standard ISO 8601 time string. The Route53 API uses these here
and there.
:param str time_str: An ISO 8601 time string.
:rtype: datetime.datetime
:returns: A timezone aware (UTC) datetime.datetime instance.
"""
if re.search('\.\d{3}Z$'... |
convert a series of simple words into some HTML text | def make_html_words( self, words ):
""" convert a series of simple words into some HTML text """
line = ""
if words:
line = html_quote( words[0] )
for w in words[1:]:
line = line + " " + html_quote( w )
return line |
analyze a simple word to detect cross - references and styling | def make_html_word( self, word ):
"""analyze a simple word to detect cross-references and styling"""
# look for cross-references
m = re_crossref.match( word )
if m:
try:
name = m.group( 1 )
rest = m.group( 2 )
block = self.iden... |
convert words of a paragraph into tagged HTML text handle xrefs | def make_html_para( self, words ):
""" convert words of a paragraph into tagged HTML text, handle xrefs """
line = ""
if words:
line = self.make_html_word( words[0] )
for word in words[1:]:
line = line + " " + self.make_html_word( word )
# con... |
convert a code sequence to HTML | def make_html_code( self, lines ):
""" convert a code sequence to HTML """
line = code_header + '\n'
for l in lines:
line = line + html_quote( l ) + '\n'
return line + code_footer |
convert a field s content into some valid HTML | def make_html_items( self, items ):
""" convert a field's content into some valid HTML """
lines = []
for item in items:
if item.lines:
lines.append( self.make_html_code( item.lines ) )
else:
lines.append( self.make_html_para( item.words )... |
main program loop | def main( argv ):
"""main program loop"""
global output_dir
try:
opts, args = getopt.getopt( sys.argv[1:], \
"ht:o:p:", \
["help", "title=", "output=", "prefix="] )
except getopt.GetoptError:
usage()
sy... |
Parses the API responses for the: py: meth: route53. connection. Route53Connection. get_hosted_zone_by_id method. | def get_hosted_zone_by_id_parser(root, connection):
"""
Parses the API responses for the
:py:meth:`route53.connection.Route53Connection.get_hosted_zone_by_id` method.
:param lxml.etree._Element root: The root node of the etree parsed
response from the API.
:param Route53Connection connectio... |
Save the metadata to the given filename. | def save(self, filename):
"""Save the metadata to the given filename."""
values = []
items = sorted(self.items(), key=MP4Tags.__get_sort_stats )
for key, value in items:
info = self.__atoms.get(key[:4], (None, type(self).__render_text))
try:
value... |
Update all parent atoms with the new size. | def __update_parents(self, fileobj, path, delta):
"""Update all parent atoms with the new size."""
for atom in path:
fileobj.seek(atom.offset)
size = cdata.uint_be(fileobj.read(4))
if size == 1: # 64bit
# skip name (4B) and read size (8B)
... |
Start running the game. The window is created and shown at this point and then the main event loop is entered. game. on_tick and other event handlers are called repeatedly until the game exits. | def run(game):
'''Start running the game. The window is created and shown at this point, and then
the main event loop is entered. 'game.on_tick' and other event handlers are called
repeatedly until the game exits.
If a game is already running, this function replaces the :class:`Game` instance that
... |
Register a mapping for controllers with the given vendor and product IDs. The mapping will replace any existing mapping for these IDs for controllers not yet connected. | def register(cls, vendor_id, product_id, mapping):
'''Register a mapping for controllers with the given vendor and product IDs. The mapping will
replace any existing mapping for these IDs for controllers not yet connected.
:param vendor_id: the vendor ID of the controller, as reported by :attr... |
Find a mapping that can apply to the given controller. Returns None if unsuccessful. | def get(cls, controller):
'''Find a mapping that can apply to the given controller. Returns None if unsuccessful.
:param controller: :class:`Controller` to look up
:return: :class:`ControllerMapping`
'''
try:
return cls._registry[(controller.vendor_id, controller.pr... |
Register a text key. | def RegisterFreeformKey(cls, key, name, mean=b"com.apple.iTunes"):
"""Register a text key.
If the key you need to register is a simple one-to-one mapping
of MP4 freeform atom (----) and name to EasyMP4Tags key, then
you can use this function::
EasyMP4Tags.RegisterFreeformKe... |
Route53 uses AWS an HMAC - based authentication scheme involving the signing of a date string with the user s secret access key. More details on the specifics can be found in their documentation_. | def _hmac_sign_string(self, string_to_sign):
"""
Route53 uses AWS an HMAC-based authentication scheme, involving the
signing of a date string with the user's secret access key. More details
on the specifics can be found in their documentation_.
.. documentation:: http://docs.ama... |
Determine the headers to send along with the request. These are pretty much the same for every request with Route53. | def get_request_headers(self):
"""
Determine the headers to send along with the request. These are
pretty much the same for every request, with Route53.
"""
date_header = time.asctime(time.gmtime())
# We sign the time string above with the user's AWS secret access key
... |
All outbound requests go through this method. It defers to the transport s various HTTP method - specific methods. | def send_request(self, path, data, method):
"""
All outbound requests go through this method. It defers to the
transport's various HTTP method-specific methods.
:param str path: The path to tack on to the endpoint URL for
the query.
:param data: The params to send al... |
Sends the GET request to the Route53 endpoint. | def _send_get_request(self, path, params, headers):
"""
Sends the GET request to the Route53 endpoint.
:param str path: The path to tack on to the endpoint URL for
the query.
:param dict params: Key/value pairs to send.
:param dict headers: A dict of headers to send ... |
Sends the POST request to the Route53 endpoint. | def _send_post_request(self, path, data, headers):
"""
Sends the POST request to the Route53 endpoint.
:param str path: The path to tack on to the endpoint URL for
the query.
:param data: Either a dict, or bytes.
:type data: dict or bytes
:param dict headers:... |
Sends the DELETE request to the Route53 endpoint. | def _send_delete_request(self, path, headers):
"""
Sends the DELETE request to the Route53 endpoint.
:param str path: The path to tack on to the endpoint URL for
the query.
:param dict headers: A dict of headers to send with the request.
:rtype: str
:returns:... |
APEv2 tag value factory. | def APEValue(value, kind):
"""APEv2 tag value factory.
Use this if you need to specify the value's type manually. Binary
and text data are automatically detected by APEv2.__setitem__.
"""
if kind in (TEXT, EXTERNAL):
if not isinstance(value, text_type):
# stricter with py3
... |
Load tags from a filename. | def load(self, filename):
"""Load tags from a filename."""
self.filename = filename
fileobj = open(filename, "rb")
try:
data = _APEv2Data(fileobj)
finally:
fileobj.close()
if data.tag:
self.clear()
self.__casemap.clear()
... |
Save changes to a file. | def save(self, filename=None):
"""Save changes to a file.
If no filename is given, the one most recently loaded is used.
Tags are always written at the end of the file, and include
a header and a footer.
"""
filename = filename or self.filename
try:
... |
Remove tags from a file. | def delete(self, filename=None):
"""Remove tags from a file."""
filename = filename or self.filename
fileobj = open(filename, "r+b")
try:
data = _APEv2Data(fileobj)
if data.start is not None and data.size is not None:
delete_bytes(fileobj, data.en... |
Uses the HTTP transport to query the Route53 API. Runs the response through lxml s parser before we hand it off for further picking apart by our call - specific parsers. | def _send_request(self, path, data, method):
"""
Uses the HTTP transport to query the Route53 API. Runs the response
through lxml's parser, before we hand it off for further picking
apart by our call-specific parsers.
:param str path: The RESTful path to tack on to the :py:attr:... |
Given an API method the arguments passed to it and a function to hand parsing off to loop through the record sets in the API call until all records have been yielded. | def _do_autopaginating_api_call(self, path, params, method, parser_func,
next_marker_xpath, next_marker_param_name,
next_type_xpath=None, parser_kwargs=None):
"""
Given an API method, the arguments passed to it, and a function to
hand parsing off to, loop through the record sets ... |
List all hosted zones associated with this connection s account. Since this method returns a generator you can pull as many or as few entries as you d like without having to query and receive every hosted zone you may have. | def list_hosted_zones(self, page_chunks=100):
"""
List all hosted zones associated with this connection's account. Since
this method returns a generator, you can pull as many or as few
entries as you'd like, without having to query and receive every
hosted zone you may have.
... |
Creates and returns a new hosted zone. Once a hosted zone is created its details can t be changed. | def create_hosted_zone(self, name, caller_reference=None, comment=None):
"""
Creates and returns a new hosted zone. Once a hosted zone is created,
its details can't be changed.
:param str name: The name of the hosted zone to create.
:keyword str caller_reference: A unique string... |
Retrieves a hosted zone by hosted zone ID ( not name ). | def get_hosted_zone_by_id(self, id):
"""
Retrieves a hosted zone, by hosted zone ID (not name).
:param str id: The hosted zone's ID (a short hash string).
:rtype: :py:class:`HostedZone <route53.hosted_zone.HostedZone>`
:returns: An :py:class:`HostedZone <route53.hosted_zone.Host... |
Deletes a hosted zone by hosted zone ID ( not name ). | def delete_hosted_zone_by_id(self, id):
"""
Deletes a hosted zone, by hosted zone ID (not name).
.. tip:: For most cases, we recommend deleting hosted zones via a
:py:class:`HostedZone <route53.hosted_zone.HostedZone>`
instance's
:py:meth:`HostedZone.delete <... |
Lists a hosted zone s resource record sets by Zone ID if you already know it. | def _list_resource_record_sets_by_zone_id(self, id, rrset_type=None,
identifier=None, name=None,
page_chunks=100):
"""
Lists a hosted zone's resource record sets by Zone ID, if you
already know it.
... |
Given a ChangeSet POST it to the Route53 API. | def _change_resource_record_sets(self, change_set, comment=None):
"""
Given a ChangeSet, POST it to the Route53 API.
.. note:: You probably shouldn't be using this method directly,
as there are convenience methods on the ResourceRecordSet
sub-classes.
:param cha... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.