text stringlengths 81 112k |
|---|
Parse a single entry from show interfaces output.
Different cases:
mgmt0 is up
admin state is up
Ethernet2/1 is up
admin state is up, Dedicated Interface
Vlan1 is down (Administratively down), line protocol is down, autostate enabled
Ethernet154/1/48 is up (with no 'admin state')
def pa... |
Get a diff between running config and a proposed file.
def _get_diff(self):
"""Get a diff between running config and a proposed file."""
diff = []
self._create_sot_file()
command = ('show diff rollback-patch file {0} file {1}'.format(
'sot_file', self.replace_file.spl... |
Save the current running config to the given file.
def _save_to_checkpoint(self, filename):
"""Save the current running config to the given file."""
command = 'checkpoint file {}'.format(filename)
self.device.send_command(command) |
Return a set of facts from the devices.
def get_facts(self):
"""Return a set of facts from the devices."""
# default values.
vendor = u'Cisco'
uptime = -1
serial_number, fqdn, os_version, hostname, domain_name = ('',) * 5
# obtain output from device
show_ver = s... |
Get arp table information.
Return a list of dictionaries having the following set of keys:
* interface (string)
* mac (string)
* ip (string)
* age (float)
For example::
[
{
'interface' : 'MgmtEth0/RSP0/CPU0... |
Returns a lists of dictionaries. Each dictionary represents an entry in the MAC Address
Table, having the following keys
* mac (string)
* interface (string)
* vlan (int)
* active (boolean)
* static (boolean)
* moves (int)
* last... |
Remove all auth tokens owned by request.user.
def get(self, request, format=None):
"""
Remove all auth tokens owned by request.user.
"""
tokens = Token.objects.filter(user=request.user)
for token in tokens:
token.delete()
content = {'success': _('User logged ... |
Set attributes to dictionary values so can access via dot notation.
def _set_attrs_to_values(self, response={}):
"""
Set attributes to dictionary values so can access via dot notation.
"""
for key in response.keys():
setattr(self, key, response[key]) |
Add a custom filter nl2br to jinja2
Replaces all newline to <BR>
def add_custom_nl2br_filters(self, app):
"""Add a custom filter nl2br to jinja2
Replaces all newline to <BR>
"""
_paragraph_re = re.compile(r'(?:\r\n|\r|\n){3,}')
@app.template_filter()
@evalcont... |
Add flask route to autodoc for automatic documentation
Any route decorated with this method will be added to the list of
routes to be documented by the generate() or html() methods.
By default, the route is added to the 'all' group.
By specifying group or groups argument, the route can... |
Return a list of dict describing the routes specified by the
doc() method
Each dict contains:
- methods: the set of allowed methods (ie ['GET', 'POST'])
- rule: relative url (ie '/user/<int:id>')
- endpoint: function name (ie 'show_user')
- doc: docstring of the func... |
Return an html string of the routes specified by the doc() method
A template can be specified. A list of routes is available under the
'autodoc' value (refer to the documentation for the generate() for a
description of available values). If no template is specified, a
default template i... |
Return true if OK to continue with close or quit or whatever
def unsaved_files_dialog(
self, all_files=False, with_cancel=True, with_discard=True):
"""Return true if OK to continue with close or quit or whatever"""
for image in self.images:
if image.metadata.changed() and (all_f... |
Sufficiently general ISO 8601 parser.
Inputs must be in "basic" format, i.e. no '-' or ':' separators.
See https://en.wikipedia.org/wiki/ISO_8601
def from_ISO_8601(cls, date_string, time_string, tz_string):
"""Sufficiently general ISO 8601 parser.
Inputs must be in "basic" format, i.e... |
Create a new post.
Form Data: title, content, authorid.
def post_post():
"""Create a new post.
Form Data: title, content, authorid.
"""
authorid = request.form.get('authorid', None)
Post(request.form['title'],
request.form['content'],
users[authorid])
return redirect("/pos... |
Finds another node by XPath originating at the current node.
def xpath(self, xpath):
""" Finds another node by XPath originating at the current node. """
return [self.get_node_factory().create(node_id)
for node_id in self._get_xpath_ids(xpath).split(",")
if node_id] |
Finds another node by a CSS selector relative to the current node.
def css(self, css):
""" Finds another node by a CSS selector relative to the current node. """
return [self.get_node_factory().create(node_id)
for node_id in self._get_css_ids(css).split(",")
if node_id] |
Returns the value of a boolean HTML attribute like `checked` or `disabled`
def get_bool_attr(self, name):
""" Returns the value of a boolean HTML attribute like `checked` or `disabled`
"""
val = self.get_attr(name)
return val is not None and val.lower() in ("true", name) |
Sets the value of an attribute.
def set_attr(self, name, value):
""" Sets the value of an attribute. """
self.exec_script("node.setAttribute(%s, %s)" % (repr(name), repr(value))) |
Returns the node's value.
def value(self):
""" Returns the node's value. """
if self.is_multi_select():
return [opt.value()
for opt in self.xpath(".//option")
if opt["selected"]]
else:
return self._invoke("value") |
Sets a HTTP header for future requests.
def set_header(self, key, value):
""" Sets a HTTP header for future requests. """
self.conn.issue_command("Header", _normalize_header(key), value) |
Returns a list of the last HTTP response headers.
Header keys are normalized to capitalized form, as in `User-Agent`.
def headers(self):
""" Returns a list of the last HTTP response headers.
Header keys are normalized to capitalized form, as in `User-Agent`.
"""
headers = self.conn.issue_command("H... |
Evaluates a piece of Javascript in the context of the current page and
returns its value.
def eval_script(self, expr):
""" Evaluates a piece of Javascript in the context of the current page and
returns its value. """
ret = self.conn.issue_command("Evaluate", expr)
return json.loads("[%s]" % ret)[0] |
Renders the current page to a PNG file (viewport size in pixels).
def render(self, path, width = 1024, height = 1024):
""" Renders the current page to a PNG file (viewport size in pixels). """
self.conn.issue_command("Render", path, width, height) |
Returns a list of all cookies in cookie string format.
def cookies(self):
""" Returns a list of all cookies in cookie string format. """
return [line.strip()
for line in self.conn.issue_command("GetCookies").split("\n")
if line.strip()] |
Sets a custom attribute for our Webkit instance. Possible attributes are:
* ``auto_load_images``
* ``dns_prefetch_enabled``
* ``plugins_enabled``
* ``private_browsing_enabled``
* ``javascript_can_open_windows``
* ``javascript_can_access_clipboard``
* ``offline_storage_database... |
Sets custom HTML in our Webkit session and allows to specify a fake URL.
Scripts and CSS is dynamically fetched as if the HTML had been loaded from
the given URL.
def set_html(self, html, url = None):
""" Sets custom HTML in our Webkit session and allows to specify a fake URL.
Scripts and CSS is dynami... |
Sets a custom HTTP proxy to use for future requests.
def set_proxy(self, host = "localhost",
port = 0,
user = "",
password = ""):
""" Sets a custom HTTP proxy to use for future requests. """
self.conn.issue_command("SetProxy", host, ... |
Returns a new socket connection to this server.
def connect(self):
""" Returns a new socket connection to this server. """
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect(("127.0.0.1", self._port))
return sock |
Consume one line from the stream.
def read_line(self):
""" Consume one line from the stream. """
while True:
newline_idx = self.buf.find(b"\n")
if newline_idx >= 0:
res = self.buf[:newline_idx]
self.buf = self.buf[newline_idx + 1:]
return res
chunk = self.f.recv(4096)
... |
Consume `n` characters from the stream.
def read(self, n):
""" Consume `n` characters from the stream. """
while len(self.buf) < n:
chunk = self.f.recv(4096)
if not chunk:
raise EndOfStreamError()
self.buf += chunk
res, self.buf = self.buf[:n], self.buf[n:]
return res |
Sends and receives a message to/from the server
def issue_command(self, cmd, *args):
""" Sends and receives a message to/from the server """
self._writeline(cmd)
self._writeline(str(len(args)))
for arg in args:
arg = str(arg)
self._writeline(str(len(arg)))
self._sock.sendall(arg.encod... |
Reads a complete response packet from the server
def _read_response(self):
""" Reads a complete response packet from the server """
result = self.buf.read_line().decode("utf-8")
if not result:
raise NoResponseError("No response received from server.")
msg = self._read_message()
if result != ... |
Reads a single size-annotated message from the server
def _read_message(self):
""" Reads a single size-annotated message from the server """
size = int(self.buf.read_line().decode("utf-8"))
return self.buf.read(size).decode("utf-8") |
GetDeepSearchResults API
def get_deep_search_results(self, address, zipcode):
"""
GetDeepSearchResults API
"""
url = 'http://www.zillow.com/webservice/GetDeepSearchResults.htm'
params = {
'address': address,
'citystatezip': zipcode,
'zws-id':... |
GetUpdatedPropertyDetails API
def get_updated_property_details(self, zpid):
"""
GetUpdatedPropertyDetails API
"""
url = 'http://www.zillow.com/webservice/GetUpdatedPropertyDetails.htm'
params = {
'zpid': zpid,
'zws-id': self.api_key
}
ret... |
`img` can be an Image instance or a path to an image file.
`save_over` indicates if the original image file should be replaced by the new image.
* Note: `save_over` is only valid if `img` is a file path.
def fix_orientation(img, save_over=False):
"""
`img` can be an Image instance or a path to an image... |
Add an error message and optional user message to the error list
def log_error(self, error, message, detail=None, strip=4):
"Add an error message and optional user message to the error list"
if message:
msg = message + ": " + error
else:
msg = error
tb = traceba... |
Check if two values are equal
def equal(self, a, b, message=None):
"Check if two values are equal"
if a != b:
self.log_error("{} != {}".format(str(a), str(b)), message)
return False
return True |
Check if a value is not None
def is_not_none(self, a, message=None):
"Check if a value is not None"
if a is None:
self.log_error("{} is None".format(str(a)), message)
return False
return True |
Check if a function raises a specified exception type,
*args and **kwargs are forwarded to the function
def raises(self, exception_type, function, *args, **kwargs):
"""
Check if a function raises a specified exception type,
*args and **kwargs are forwarded to the function
... |
Check if a function does not raise an exception,
*args and **kwargs are forwarded to the function
def does_not_raise(self, function, *args, **kwargs):
"""
Check if a function does not raise an exception,
*args and **kwargs are forwarded to the function
"""
tr... |
Converts the raw R/G/B values to color temperature in degrees Kelvin.
def calculate_color_temperature(r, g, b):
"""Converts the raw R/G/B values to color temperature in degrees Kelvin."""
# 1. Map RGB values to their XYZ counterparts.
# Based on 6500K fluorescent, 3000K fluorescent
# and 60W incandesce... |
Converts the raw R/G/B values to luminosity in lux.
def calculate_lux(r, g, b):
"""Converts the raw R/G/B values to luminosity in lux."""
illuminance = (-0.32466 * r) + (1.57837 * g) + (-0.73191 * b)
return int(illuminance) |
Write a 8-bit value to a register.
def _write8(self, reg, value):
"""Write a 8-bit value to a register."""
self._device.write8(TCS34725_COMMAND_BIT | reg, value) |
Enable the chip.
def enable(self):
"""Enable the chip."""
# Flip on the power and enable bits.
self._write8(TCS34725_ENABLE, TCS34725_ENABLE_PON)
time.sleep(0.01)
self._write8(TCS34725_ENABLE, (TCS34725_ENABLE_PON | TCS34725_ENABLE_AEN)) |
Disable the chip (power down).
def disable(self):
"""Disable the chip (power down)."""
# Flip off the power on and enable bits.
reg = self._readU8(TCS34725_ENABLE)
reg &= ~(TCS34725_ENABLE_PON | TCS34725_ENABLE_AEN)
self._write8(TCS34725_ENABLE, reg) |
Sets the integration time for the TC34725. Provide one of these
constants:
- TCS34725_INTEGRATIONTIME_2_4MS = 2.4ms - 1 cycle - Max Count: 1024
- TCS34725_INTEGRATIONTIME_24MS = 24ms - 10 cycles - Max Count: 10240
- TCS34725_INTEGRATIONTIME_50MS = 50ms - 20 cycles - Max C... |
Reads the raw red, green, blue and clear channel values. Will return
a 4-tuple with the red, green, blue, clear color values (unsigned 16-bit
numbers).
def get_raw_data(self):
"""Reads the raw red, green, blue and clear channel values. Will return
a 4-tuple with the red, green, blue, cl... |
Enable or disable interrupts by setting enabled to True or False.
def set_interrupt(self, enabled):
"""Enable or disable interrupts by setting enabled to True or False."""
enable_reg = self._readU8(TCS34725_ENABLE)
if enabled:
enable_reg |= TCS34725_ENABLE_AIEN
else:
... |
Set the interrupt limits to provied unsigned 16-bit threshold values.
def set_interrupt_limits(self, low, high):
"""Set the interrupt limits to provied unsigned 16-bit threshold values.
"""
self._device.write8(0x04, low & 0xFF)
self._device.write8(0x05, low >> 8)
self._device.wr... |
Converts JSON to HTML Table format.
Parameters
----------
json_input : dict
JSON object to convert into HTML.
build_direction : {"TOP_TO_BOTTOM", "LEFT_TO_RIGHT"}
String denoting the build direction of the table. If ``"TOP_TO_BOTTOM"`` child
objects will be appended below parent... |
Converts JSON to HTML Table format.
Parameters
----------
json_input : dict
JSON object to convert into HTML.
Returns
-------
str
String of converted HTML.
def convert(self, json_input):
"""
Converts JSON to HTML Table format.
... |
Converts a dictionary to a string of ``key=\"value\"`` pairs.
If ``None`` is provided as the dictionary an empty string is returned,
i.e. no html attributes are generated.
Parameters
----------
d : dict
Dictionary to convert to html attributes.
Returns
... |
Detects if all entries in an list of ``dict``'s have identical keys.
Returns the keys if all keys are the same and ``None`` otherwise.
Parameters
----------
list_of_dicts : list
List of dictionaries to test for identical keys.
Returns
-------
list or... |
Recursively generates HTML for the current entry.
Parameters
----------
entry : object
Object to convert to HTML. Maybe be a single entity or contain multiple and/or nested objects.
Returns
-------
str
String of HTML formatted json.
def _markup(... |
If all keys in a list of dicts are identical, values from each ``dict``
are clubbed, i.e. inserted under a common column heading. If the keys
are not identical ``None`` is returned, and the list should be converted
to HTML per the normal ``convert`` function.
Parameters
-------... |
修改语音通知模版
注意:模板成功修改之后需要重新审核才能使用!同时提醒您如果修改了变量,务必重新测试,以免替换出错!
参数:
参数名 类型 是否必须 描述 示例
apikey String 是 用户唯一标识 9b11127a9701975c734b8aee81ee3526
tpl_id Long 是 模板id,64位长整形。指定id时返回id对应的模板。未指定时返回所有模板 9527
tpl_content String 是 模板i... |
Args:
code: (Optional) set code
ret_r: (Optional) force to return Result. Default value is False
returns:
response code(0-success, others-failure) or self
def code(self, code=None, ret_r=False):
'''
Args:
code: (Optional) set code
ret_... |
code's message
def msg(self, msg=None, ret_r=False):
'''code's message'''
if msg or ret_r:
self._msg = msg
return self
return self._msg |
code's detail
def detail(self, detail=None, ret_r=False):
'''code's detail'''
if detail or ret_r:
self._detail = detail
return self
return self._detail |
response data
def data(self, data=None, ret_r=False):
'''response data'''
if data or ret_r:
self._data = data
return self
return self._data |
查账户信息
参数名 类型 是否必须 描述 示例
apikey String 是 用户唯一标识 9b11127a9701975c734b8aee81ee3526
Args:
param: (Optional)
Results:
Result
def get(self, param=None, must=[APIKEY]):
'''查账户信息
参数名 类型 是否必须 描述 示例
apikey String 是 用户唯一标识... |
initialize api by YunpianClient
def _init(self, clnt):
'''initialize api by YunpianClient'''
assert clnt, "clnt is None"
self._clnt = clnt
self._apikey = clnt.apikey()
self._version = clnt.conf(YP_VERSION, defval=VERSION_V2)
self._charset = clnt.conf(HTTP_CHARSET, defval... |
api name, default is module.__name__
def name(self, name=None):
'''api name, default is module.__name__'''
if name:
self._name = name
return self
return self._name |
Args:
param: request parameters
h: ResultHandler
r: YunpianApiResult
def post(self, param, h, r):
'''
Args:
param: request parameters
h: ResultHandler
r: YunpianApiResult
'''
try:
rsp = self.client().pos... |
return Code.ARGUMENT_MISSING if every key in must not found in param
def verify_param(self, param, must=[], r=None):
'''return Code.ARGUMENT_MISSING if every key in must not found in param'''
if APIKEY not in param:
param[APIKEY] = self.apikey()
r = Result() if r is None else r
... |
custom apikey and http parameters
def custom_conf(self, conf):
'''custom apikey and http parameters'''
if conf:
for (key, val) in conf.items():
self.__conf[key] = val
return self |
get config
def conf(self, key):
'''get config'''
return self.__conf[key] if key in self.__conf else _YunpianConf.YP_CONF.get(key) |
return special API by package's name
def api(self, name):
'''return special API by package's name'''
assert name, 'name is none'
if flow.__name__ == name:
api = flow.FlowApi()
elif sign.__name__ == name:
api = sign.SignApi()
elif sms.__name__ == name:
... |
return YunpianConf if key=None, else return value in YunpianConf
def conf(self, key=None, defval=None):
'''return YunpianConf if key=None, else return value in YunpianConf'''
if key is None:
return self._ypconf
val = self._ypconf.conf(key)
return defval if val is None else v... |
response json text
def post(self, url, data, charset=CHARSET_UTF8, headers={}):
'''response json text'''
if 'Api-Lang' not in headers:
headers['Api-Lang'] = 'python'
if 'Content-Type' not in headers:
headers['Content-Type'] = "application/x-www-form-urlencoded;charset=" ... |
sepr.join(urlencode(seq))
Args:
seq: string list to be urlencoded
sepr: join seq with sepr
Returns:
str
def urlEncodeAndJoin(self, seq, sepr=','):
'''sepr.join(urlencode(seq))
Args:
seq: string list to be urlencoded
sepr: join ... |
发语音验证码
参数名 类型 是否必须 描述 示例
apikey String 是 用户唯一标识 9b11127a9701975c734b8aee81ee3526
mobile String 是 接收的手机号、固话(需加区号) 15205201314 01088880000
code String 是 验证码,支持4~6位阿拉伯数字 1234
encrypt String 否 加密方式 使用加密 tea (不再使用)
_sign String 否 签名字段 参考使用加密 393d079e0a00912335adfe46f4a2e10f (... |
单条发送
参数名 类型 是否必须 描述 示例
apikey String 是 用户唯一标识 9b11127a9701975c734b8aee81ee3526
mobile String 是
接收的手机号;仅支持单号码发送;国际号码需包含国际地区前缀号码,格式必须是"+"号开头("+"号需要urlencode处理,否则会出现格式错误),国际号码不以"+"开头将被认为是中国地区的号码
(针对国际短信,mobile参数会自动格式化到E.164格式,可能会造成传入mobile参数跟后续的状态报告中的号码不一致。E.164格式说明,参见:
... |
获取回复短信
参数名 类型 是否必须 描述 示例
apikey String 是 用户唯一标识 9b11127a9701975c734b8aee81ee3526
page_size Integer 否 每页个数,最大100个,默认20个 20
Args:
param:
Results:
Result
def pull_reply(self, param=None, must=[APIKEY]):
'''获取回复短信
参数... |
查回复的短信
参数名 类型 是否必须 描述 示例
apikey String 是 用户唯一标识 9b11127a9701975c734b8aee81ee3526
start_time String 是 短信回复开始时间 2013-08-11 00:00:00
end_time String 是 短信回复结束时间 2013-08-12 00:00:00
page_num Integer 是 页码,默认值为1 1
page_size Integer 是 每页个数,最大100个 20
mobile String... |
查短信发送记录
参数名 类型 是否必须 描述 示例
apikey String 是 用户唯一标识 9b11127a9701975c734b8aee81ee3526
mobile String 否 需要查询的手机号 15205201314
start_time String 是 短信发送开始时间 2013-08-11 00:00:00
end_time String 是 短信发送结束时间 2013-08-12 00:00:00
page_num Integer 否 页码,默认值为1 1
page_size ... |
统计短信条数
参数名 类型 是否必须 描述 示例
apikey String 是 用户唯一标识 9b11127a9701975c734b8aee81ee3526
start_time String 是 短信发送开始时间 2013-08-11 00:00:00
end_time String 是 短信发送结束时间 2013-08-12 00:00:00
mobile String 否 需要查询的手机号 15205201314
page_num Integer 否 页码,默认值为1 1
page_size I... |
指定模板发送 only v1 deprecated
参数名 类型 是否必须 描述 示例
apikey String 是 用户唯一标识 9b11127a9701975c734b8aee81ee3526
mobile String 是 接收的手机号 15205201314
tpl_id Long 是 模板id 1
tpl_value String 是 变量名和变量值对。请先对您的变量名和变量值分别进行urlencode再传递。使用参考:代码示例。
注:变量名和变量值都不能为空 模板: 【#company#】您的验证码是#co... |
指定模板单发 only v2 deprecated
参数名 类型 是否必须 描述 示例
apikey String 是 用户唯一标识 9b11127a9701975c734b8aee81ee3526
mobile String 是
接收的手机号(针对国际短信,mobile参数会自动格式化到E.164格式,可能会造成传入mobile参数跟后续的状态报告中的号码不一致。E.164格式说明,参见:
https://en.wikipedia.org/wiki/E.164) 15205201314
tpl_id Long 是 模板id 1
... |
查询流量包
参数名 类型 是否必须 描述 示例
apikey String 是 用户唯一标识 9b11127a9701975c734b8aee81ee3526
carrier String 否 运营商ID 传入该参数则获取指定运营商的流量包, 否则获取所有运营商的流量包 移动:10086 联通:10010 电信:10000
Args:
param:
Results:
Result
def get_package(self, param=None, must=[APIKE... |
充值流量
参数名 类型 是否必须 描述 示例
apikey String 是 用户唯一标识 9b11127a9701975c734b8aee81ee3526
mobile String 是 接收的手机号(仅支持大陆号码) 15205201314
sn String 是 流量包的唯一ID 点击查看 1008601
callback_url String 否 本条流量充值的状态报告推送地址 http://your_receive_url_address
encrypt String 否 加密方式 使用加密 tea (不再使用... |
获取状态报告
参数名 是否必须 描述 示例
apikey 是 用户唯一标识 9b11127a9701975c734b8aee81ee3526
page_size 否 每页个数,最大100个,默认20个 20
Args:
param:
Results:
Result
def pull_status(self, param=None, must=[APIKEY]):
'''获取状态报告
参数名 是否必须 描述 示例
... |
Runs a command, piping all output to the DMP log.
The args should be separate arguments so paths and subcommands can have spaces in them:
ret = run_command('ls', '-l', '/Users/me/My Documents')
print(ret.code)
print(ret.stdout)
print(ret.stderr)
On Windows, the PATH is not foll... |
Retrieve a *Django* API template object for the given template name, using the app_path and template_subdir
settings in this object. This method still uses the corresponding Mako template and engine, but it
gives a Django API wrapper around it so you can use it the same as any Django template.
... |
Retrieve the real *Mako* template object for the given template name without any wrapper,
using the app_path and template_subdir settings in this object.
This method is an alternative to get_template(). Use it when you need the actual Mako template object.
This method raises a Mako ex... |
Registers the given app_name with DMP and adds convention-based
url patterns for it.
This function is meant to be called in a project's urls.py.
def app_resolver(app_name=None, pattern_kwargs=None, name=None):
'''
Registers the given app_name with DMP and adds convention-based
url patterns for it.... |
Utility function that creates the default patterns for an app
def dmp_paths_for_app(app_name, pattern_kwargs=None, pretty_app_name=None):
'''Utility function that creates the default patterns for an app'''
dmp = apps.get_app_config('django_mako_plus')
# Because these patterns are subpatterns within the app... |
Creates a DMP-style, convention-based pattern that resolves
to various view functions based on the 'dmp_page' value.
The following should exist as 1) regex named groups or
2) items in the kwargs dict:
dmp_app Should resolve to a name in INSTALLED_APPS.
If missing, de... |
Different from Django, this method matches by /app/page/ convention
using its pattern. The pattern should create keyword arguments for
dmp_app, dmp_page.
def resolve(self, path):
'''
Different from Django, this method matches by /app/page/ convention
using its pattern. The pat... |
A Mako filter that renders a block of text using a different template engine
than Mako. The named template engine must be listed in settings.TEMPLATES.
The template context variables are available in the embedded template.
Specify kwargs to add additional variables created within the template.
This i... |
Retrieves a view function from the cache, finding it if the first time.
Raises ViewDoesNotExist if not found. This is called by resolver.py.
def get_view_function(module_name, function_name, fallback_app=None, fallback_template=None, verify_decorator=True):
'''
Retrieves a view function from the cache, fi... |
Finds a view function, class-based view, or template view.
Raises ViewDoesNotExist if not found.
def find_view_function(module_name, function_name, fallback_app=None, fallback_template=None, verify_decorator=True):
'''
Finds a view function, class-based view, or template view.
Raises ViewDoesNotExist i... |
Creates a view function for templates (used whe a view.py file doesn't exist but the .html does)
Raises TemplateDoesNotExist if the template doesn't exist.
def create_view_for_template(app_name, template_name):
'''
Creates a view function for templates (used whe a view.py file doesn't exist but the .html d... |
Generator function that iterates this object's related providers,
which includes this provider.
def iter_related(self):
'''
Generator function that iterates this object's related providers,
which includes this provider.
'''
for tpl in self.provider_run.templates:
... |
Gets the cached item. Raises AttributeError if it hasn't been set.
def get_cache_item(self):
'''Gets the cached item. Raises AttributeError if it hasn't been set.'''
if settings.DEBUG:
raise AttributeError('Caching disabled in DEBUG mode')
return getattr(self.template, self.options[... |
Generator that recursively flattens embedded lists, tuples, etc.
def flatten(*args):
'''Generator that recursively flattens embedded lists, tuples, etc.'''
for arg in args:
if isinstance(arg, collections.Iterable) and not isinstance(arg, (str, bytes)):
yield from flatten(*arg)
else:... |
Calculates the CRC checksum for a file.
Using CRC32 because security isn't the issue and don't need perfect noncollisions.
We just need to know if a file has changed.
On my machine, crc32 was 20 times faster than any hashlib algorithm,
including blake and md5 algorithms.
def crc32(filename):
'''
... |
Compiles the Mako templates within the apps of this system
def compile_mako_files(self, app_config):
'''Compiles the Mako templates within the apps of this system'''
# go through the files in the templates, scripts, and styles directories
for subdir_name in self.SEARCH_DIRS:
subdir ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.