INSTRUCTION stringlengths 1 8.43k | RESPONSE stringlengths 75 104k |
|---|---|
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: | def set_attribute(self, attr, value = True):
""" 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_... |
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 dynamically fetched as if the HTML had been loaded from
the given URL. """
if url:
self.conn.issue_command('SetHtml', html, url)
else:
self.conn.issue_com... |
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, port, user, password) |
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)
if not chunk:
raise E... |
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.encode("utf-8"))
return self._read_response() |
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 != "ok":
raise InvalidResponseError(msg)
r... |
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': self.api_key
}
... |
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
}
return self.get_data(url, params) |
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 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.
"""
path = None
if not isinstance(img, Im... |
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 = traceback.format_stack()
if sys.version_info >= (3, 0):
... |
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
"""
try:
result = function(*args, **kwargs)
self.log_error("{} did not throw ex... |
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
"""
try:
return function(*args, **kwargs)
except Exception as e:
self.log_error("{} d... |
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 incandescent values for a wide range.
# Note: Y = Illuminance or lux
X = ... |
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 Count: 20480 - TCS34725_INTEGRATIONTIME_101MS = ... | def set_integration_time(self, integration_time):
"""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
-... |
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, clear color values (unsigned 16-bit
numbers).
"""
# Read each color register.
r = self._readU16LE(TCS34725_RDATAL)
g = self._readU1... |
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:
enable_reg &= ~TCS34725_ENABLE_AIEN
self._write8(TCS34... |
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.write8(0x06, high & 0xFF)
self._device.write8(0x07, high >> 8) |
Converts JSON to HTML Table format. | def convert(json_input, build_direction="LEFT_TO_RIGHT", table_attributes=None):
"""
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 direc... |
Converts JSON to HTML Table format. | def convert(self, json_input):
"""
Converts JSON to HTML Table format.
Parameters
----------
json_input : dict
JSON object to convert into HTML.
Returns
-------
str
String of converted HTML.
"""
html_output = self.... |
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. | def _dict_to_html_attributes(d):
"""
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 ... |
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. | def _list_of_dicts_to_column_headers(list_of_dicts):
"""
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 ... |
Recursively generates HTML for the current entry. | def _markup(self, entry):
"""
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
... |
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. | def _maybe_club(self, list_of_dicts):
"""
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... |
修改语音通知模版 注意:模板成功修改之后需要重新审核才能使用!同时提醒您如果修改了变量,务必重新测试,以免替换出错! 参数: 参数名 类型 是否必须 描述 示例 apikey String 是 用户唯一标识 9b11127a9701975c734b8aee81ee3526 tpl_id Long 是 模板id,64位长整形。指定id时返回id对应的模板。未指定时返回所有模板 9527 tpl_content String 是 模板id,64位长整形。指定id时返回id对应的模板。未指定时返回所有模板模板内容 您的验证码是#code# Args: param: Results: Result | def update_voice_notify(self, param, must=[APIKEY, TPL_ID, TPL_CONTENT]):
'''修改语音通知模版
注意:模板成功修改之后需要重新审核才能使用!同时提醒您如果修改了变量,务必重新测试,以免替换出错!
参数:
参数名 类型 是否必须 描述 示例
apikey String 是 用户唯一标识 9b11127a9701975c734b8aee81ee3526
tpl_id Long 是 模板... |
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_r: (Optional) force to return Result. Default value is False
returns:
response code(0-success, others-failure) or self
'''
if code or ret_r:
self._code ... |
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 是 用户唯一标识 9b11127a9701975c734b8aee81ee3526
Args:
param: (Optional)
Results:
Result
'''
param = {} if param is None else param
r = s... |
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=CHARSET_UTF8)
self._name... |
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().post(self.uri(), param)
# print(rsp)
return self.result(rsp, h, r)
except Val... |
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
for p in must:
if p not in param:
r.c... |
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:
api = sms.SmsApi()
e... |
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 val |
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=" + charset
rs... |
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 seq with sepr
Returns:
str
'''
try:
from urllib.parse import quote_plus as encode
return sepr.joi... |
发语音验证码 | def send(self, param, must=[APIKEY, MOBILE, CODE]):
'''发语音验证码
参数名 类型 是否必须 描述 示例
apikey String 是 用户唯一标识 9b11127a9701975c734b8aee81ee3526
mobile String 是 接收的手机号、固话(需加区号) 15205201314 01088880000
code String 是 验证码,支持4~6位阿拉伯数字 1234
encrypt String 否 加密方式 使用加密 tea (不再使用)
... |
单条发送 参数名 类型 是否必须 描述 示例 apikey String 是 用户唯一标识 9b11127a9701975c734b8aee81ee3526 mobile String 是 接收的手机号;仅支持单号码发送;国际号码需包含国际地区前缀号码,格式必须是 + 号开头 ( + 号需要urlencode处理,否则会出现格式错误 ) ,国际号码不以 + 开头将被认为是中国地区的号码 (针对国际短信,mobile参数会自动格式化到E. 164格式,可能会造成传入mobile参数跟后续的状态报告中的号码不一致。E. 164格式说明,参见: https:// en. wikipedia. org/ wiki/ E. 164) 国内号码... | def single_send(self, param, must=[APIKEY, MOBILE, TEXT]):
'''单条发送
参数名 类型 是否必须 描述 示例
apikey String 是 用户唯一标识 9b11127a9701975c734b8aee81ee3526
mobile String 是
接收的手机号;仅支持单号码发送;国际号码需包含国际地区前缀号码,格式必须是"+"号开头("+"号需要urlencode处理,否则会出现格式错误),国际号码不以"+"开头将被认为是中国地区的号码
(针对国际短信,m... |
获取回复短信 参数名 类型 是否必须 描述 示例 apikey String 是 用户唯一标识 9b11127a9701975c734b8aee81ee3526 page_size Integer 否 每页个数,最大100个,默认20个 20 Args: param: Results: Result | def pull_reply(self, param=None, must=[APIKEY]):
'''获取回复短信
参数名 类型 是否必须 描述 示例
apikey String 是 用户唯一标识 9b11127a9701975c734b8aee81ee3526
page_size Integer 否 每页个数,最大100个,默认20个 20
Args:
param:
Results:
Result
'''
param =... |
查回复的短信 参数名 类型 是否必须 描述 示例 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 否 填写时只查该手机号的回复,不填时查所有的回复 15205201314 return_fields 否... | def get_reply(self, param, must=[APIKEY, START_TIME, END_TIME, PAGE_NUM, PAGE_SIZE]):
'''查回复的短信
参数名 类型 是否必须 描述 示例
apikey String 是 用户唯一标识 9b11127a9701975c734b8aee81ee3526
start_time String 是 短信回复开始时间 2013-08-11 00:00:00
end_time String 是 短信回复结束时间 2013-08-12 00:00:00
... |
查短信发送记录 参数名 类型 是否必须 描述 示例 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 Integer 否 每页个数,最大100个 20 Args: param: Results: Result | def get_record(self, param, must=[APIKEY, START_TIME, END_TIME]):
'''查短信发送记录
参数名 类型 是否必须 描述 示例
apikey String 是 用户唯一标识 9b11127a9701975c734b8aee81ee3526
mobile String 否 需要查询的手机号 15205201314
start_time String 是 短信发送开始时间 2013-08-11 00:00:00
end_time String 是 短信发送结束时间... |
统计短信条数 参数名 类型 是否必须 描述 示例 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 Integer 否 每页个数,最大100个 20 Args: param: Results: Result | def count(self, param, must=[APIKEY, START_TIME, END_TIME]):
'''统计短信条数
参数名 类型 是否必须 描述 示例
apikey String 是 用户唯一标识 9b11127a9701975c734b8aee81ee3526
start_time String 是 短信发送开始时间 2013-08-11 00:00:00
end_time String 是 短信发送结束时间 2013-08-12 00:00:00
mobile String 否 需要查询的手... |
指定模板发送 only v1 deprecated 参数名 类型 是否必须 描述 示例 apikey String 是 用户唯一标识 9b11127a9701975c734b8aee81ee3526 mobile String 是 接收的手机号 15205201314 tpl_id Long 是 模板id 1 tpl_value String 是 变量名和变量值对。请先对您的变量名和变量值分别进行urlencode再传递。使用参考:代码示例。 注:变量名和变量值都不能为空 模板: 【#company#】您的验证码是#code#。 最终发送结果: 【云片网】您的验证码是1234。 tplvalue = urlencode ( #cod... | def tpl_send(self, param, must=[APIKEY, MOBILE, TPL_ID, TPL_VALUE]):
'''指定模板发送 only v1 deprecated
参数名 类型 是否必须 描述 示例
apikey String 是 用户唯一标识 9b11127a9701975c734b8aee81ee3526
mobile String 是 接收的手机号 15205201314
tpl_id Long 是 模板id 1
tpl_value String 是 变量名和变量值对。请先对您的变量... |
指定模板单发 only v2 deprecated | def tpl_single_send(self, param, must=[APIKEY, MOBILE, TPL_ID, TPL_VALUE]):
'''指定模板单发 only v2 deprecated
参数名 类型 是否必须 描述 示例
apikey String 是 用户唯一标识 9b11127a9701975c734b8aee81ee3526
mobile String 是
接收的手机号(针对国际短信,mobile参数会自动格式化到E.164格式,可能会造成传入mobile参数跟后续的状态报告中的号码不一致。E.164格式说明,参见:
... |
查询流量包 参数名 类型 是否必须 描述 示例 apikey String 是 用户唯一标识 9b11127a9701975c734b8aee81ee3526 carrier String 否 运营商ID 传入该参数则获取指定运营商的流量包, 否则获取所有运营商的流量包 移动:10086 联通:10010 电信:10000 Args: param: Results: Result | def get_package(self, param=None, must=[APIKEY]):
'''查询流量包
参数名 类型 是否必须 描述 示例
apikey String 是 用户唯一标识 9b11127a9701975c734b8aee81ee3526
carrier String 否 运营商ID 传入该参数则获取指定运营商的流量包, 否则获取所有运营商的流量包 移动:10086 联通:10010 电信:10000
Args:
param:
Results:
... |
充值流量 参数名 类型 是否必须 描述 示例 apikey String 是 用户唯一标识 9b11127a9701975c734b8aee81ee3526 mobile String 是 接收的手机号(仅支持大陆号码) 15205201314 sn String 是 流量包的唯一ID 点击查看 1008601 callback_url String 否 本条流量充值的状态报告推送地址 http:// your_receive_url_address encrypt String 否 加密方式 使用加密 tea ( 不再使用 ) _sign String 否 签名字段 参考使用加密 393d079e0a00912335adfe46f... | def recharge(self, param, must=[APIKEY, MOBILE, SN]):
'''充值流量
参数名 类型 是否必须 描述 示例
apikey String 是 用户唯一标识 9b11127a9701975c734b8aee81ee3526
mobile String 是 接收的手机号(仅支持大陆号码) 15205201314
sn String 是 流量包的唯一ID 点击查看 1008601
callback_url String 否 本条流量充值的状态报告推送地址 http://your... |
获取状态报告 参数名 是否必须 描述 示例 apikey 是 用户唯一标识 9b11127a9701975c734b8aee81ee3526 page_size 否 每页个数,最大100个,默认20个 20 Args: param: Results: Result | def pull_status(self, param=None, must=[APIKEY]):
'''获取状态报告
参数名 是否必须 描述 示例
apikey 是 用户唯一标识 9b11127a9701975c734b8aee81ee3526
page_size 否 每页个数,最大100个,默认20个 20
Args:
param:
Results:
Result
'''
param = {} if param is N... |
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: | def run_command(*args, raise_exception=True, cwd=None):
'''
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.std... |
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. | def get_template(self, template, def_name=None):
'''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 aro... |
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. | def get_mako_template(self, template, force=False):
'''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 actua... |
Registers the given app_name with DMP and adds convention - based url patterns for it. | 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.
This function is meant to be called in a project's urls.py.
'''
urlconf = URLConf(app_name, pattern_kwargs)
resolver = re_path(
'... |
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's resolver,
# we don't include the /app/ in the pattern --... |
Creates a DMP - style convention - based pattern that resolves to various view functions based on the dmp_page value. | def dmp_path(regex, kwargs=None, name=None, app_name=None):
'''
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 res... |
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 pattern should create keyword arguments for
dmp_app, dmp_page.
'''
match = super().resolve(path)
if match:
try:
rou... |
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. | def alternate_syntax(local, using, **kwargs):
'''
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 add... |
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, finding it if the first time.
Raises ViewDoesNotExist if not found. This is called by resolver.py.
'''
# first check the cache (without ... |
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 if not found.
'''
dmp = apps.get_app_config('django_mako_plus')
# I'm first calling find_s... |
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 does)
Raises TemplateDoesNotExist if the template doesn't exist.
'''
# ensure the template exists
apps.get_app_config('django_mako_plus').engine.g... |
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:
yield tpl.providers[self.index] |
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['template_cache_key']) |
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:
yield arg |
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. | def crc32(filename):
'''
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... |
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 = subdir_name.format(
app_path=app_config.pa... |
Compiles a template from the given string. This is one of the required methods of Django template engines. | def from_string(self, template_code):
'''
Compiles a template from the given string.
This is one of the required methods of Django template engines.
'''
dmp = apps.get_app_config('django_mako_plus')
mako_template = Template(template_code, imports=dmp.template_imports, inp... |
Retrieves a template object from the pattern app_name/ template. html. This is one of the required methods of Django template engines. | def get_template(self, template_name):
'''
Retrieves a template object from the pattern "app_name/template.html".
This is one of the required methods of Django template engines.
Because DMP templates are always app-specific (Django only searches
a global set of directories), the... |
Returns a template loader object for the given app name in the given subdir. For example get_template_loader ( homepage styles ) will return a loader for the styles/ directory in the homepage app. | def get_template_loader(self, app, subdir='templates', create=False):
'''
Returns a template loader object for the given app name in the given subdir.
For example, get_template_loader('homepage', 'styles') will return
a loader for the styles/ directory in the homepage app.
The a... |
Returns a template loader object for the given directory path. For example get_template_loader (/ var/ mytemplates/ ) will return a loader for that specific directory. | def get_template_loader_for_path(self, path, use_cache=True):
'''
Returns a template loader object for the given directory path.
For example, get_template_loader('/var/mytemplates/') will return
a loader for that specific directory.
Normally, you should not have to call this met... |
Triggered by the | def _register_converter(cls, conv_func, conv_type):
'''Triggered by the @converter_function decorator'''
cls.converters.append(ConverterFunctionInfo(conv_func, conv_type, len(cls.converters)))
cls._sort_converters() |
Sorts the converter functions | def _sort_converters(cls, app_ready=False):
'''Sorts the converter functions'''
# app_ready is True when called from DMP's AppConfig.ready()
# we can't sort before then because models aren't ready
cls._sorting_enabled = cls._sorting_enabled or app_ready
if cls._sorting_enabled:
... |
Iterates the urlparams and converts them according to the type hints in the current view function. This is the primary function of the class. | def convert_parameters(self, request, *args, **kwargs):
'''
Iterates the urlparams and converts them according to the
type hints in the current view function. This is the primary
function of the class.
'''
args = list(args)
urlparam_i = 0
parameters = se... |
Converts a parameter value in the view function call. | def convert_value(self, value, parameter, request):
'''
Converts a parameter value in the view function call.
value: value from request.dmp.urlparams to convert
The value will always be a string, even if empty '' (never None).
parameter: an instanc... |
Creates an entry file for the given script map | def create_entry_file(self, filename, script_map, enapps):
'''Creates an entry file for the given script map'''
if len(script_map) == 0:
return
# create the entry file
template = MakoTemplate('''
<%! import os %>
// dynamic imports are within functions so they don't happen u... |
Maps templates in this app to their scripts. This function deep searches app/ templates/ * for the templates of this app. Returns the following dictionary with absolute paths: | def generate_script_map(self, config):
'''
Maps templates in this app to their scripts. This function deep searches
app/templates/* for the templates of this app. Returns the following
dictionary with absolute paths:
{
( 'appname', 'template1' ): [ '/abs/path/to/sc... |
Returns a list of scripts used by the given template object AND its ancestors. | def template_scripts(self, config, template_name):
'''
Returns a list of scripts used by the given template object AND its ancestors.
This runs a ProviderRun on the given template (as if it were being displayed).
This allows the WEBPACK_PROVIDERS to provide the JS files to us.
'... |
Returns the redirect response for this exception. | def get_response(self, request, *args, **kwargs):
'''Returns the redirect response for this exception.'''
# normal process
response = HttpResponseRedirect(self.redirect_to)
response[REDIRECT_HEADER_KEY] = self.redirect_to
return response |
Returns the redirect response for this exception. | def get_response(self, request):
'''Returns the redirect response for this exception.'''
# the redirect key is already placed in the response by HttpResponseJavascriptRedirect
return HttpResponseJavascriptRedirect(self.redirect_to, *self.args, **self.kwargs) |
Convenience method that calls get_template_loader () on the DMP template engine instance. | def get_template_loader(app, subdir='templates'):
'''
Convenience method that calls get_template_loader() on the DMP
template engine instance.
'''
dmp = apps.get_app_config('django_mako_plus')
return dmp.engine.get_template_loader(app, subdir, create=True) |
Convenience method that directly renders a template given the app and template names. | def render_template(request, app, template_name, context=None, subdir="templates", def_name=None):
'''
Convenience method that directly renders a template, given the app and template names.
'''
return get_template(app, template_name, subdir).render(context, request, def_name) |
Convenience method that calls get_template_loader_for_path () on the DMP template engine instance. | def get_template_loader_for_path(path, use_cache=True):
'''
Convenience method that calls get_template_loader_for_path() on the DMP
template engine instance.
'''
dmp = apps.get_app_config('django_mako_plus')
return dmp.engine.get_template_loader_for_path(path, use_cache) |
Convenience method that retrieves a template given a direct path to it. | def get_template_for_path(path, use_cache=True):
'''
Convenience method that retrieves a template given a direct path to it.
'''
dmp = apps.get_app_config('django_mako_plus')
app_path, template_name = os.path.split(path)
return dmp.engine.get_template_loader_for_path(app_path, use_cache=use_cach... |
Convenience method that directly renders a template given a direct path to it. | def render_template_for_path(request, path, context=None, use_cache=True, def_name=None):
'''
Convenience method that directly renders a template, given a direct path to it.
'''
return get_template_for_path(path, use_cache).render(context, request, def_name) |
Returns the fully - qualified name of the given object | def qualified_name(obj):
'''Returns the fully-qualified name of the given object'''
if not hasattr(obj, '__module__'):
obj = obj.__class__
module = obj.__module__
if module is None or module == str.__class__.__module__:
return obj.__qualname__
return '{}.{}'.format(module, obj.__qual... |
Imports a fully - qualified name from a module: | def import_qualified(name):
'''
Imports a fully-qualified name from a module:
cls = import_qualified('homepage.views.index.MyForm')
Raises an ImportError if it can't be ipmorted.
'''
parts = name.rsplit('.', 1)
if len(parts) != 2:
raise ImportError('Invalid fully-qualified name... |
Returns the HTML for the given provider group ( or all groups if None ) | def links(tself, group=None):
'''Returns the HTML for the given provider group (or all groups if None)'''
pr = ProviderRun(tself, group)
pr.run()
return mark_safe(pr.getvalue()) |
Returns the HTML for the given provider group using an app and template name. This method should not normally be used ( use links () instead ). The use of this method is when provider need to be called from regular python code instead of from within a rendering template environment. | def template_links(request, app, template_name, context=None, group=None, force=True):
'''
Returns the HTML for the given provider group, using an app and template name.
This method should not normally be used (use links() instead). The use of
this method is when provider need to be called from regular... |
Returns the HTML for the given provider group using a template object. This method should not normally be used ( use links () instead ). The use of this method is when provider need to be called from regular python code instead of from within a rendering template environment. | def template_obj_links(request, template_obj, context=None, group=None):
'''
Returns the HTML for the given provider group, using a template object.
This method should not normally be used (use links() instead). The use of
this method is when provider need to be called from regular python code instead
... |
Called when link is not defined in the settings | def build_default_link(self):
'''Called when 'link' is not defined in the settings'''
attrs = {}
attrs["rel"] = "stylesheet"
attrs["href"] ="{}?{:x}".format(
os.path.join(settings.STATIC_URL, self.filepath).replace(os.path.sep, '/'),
self.version_id,
)
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.