repository_name
stringlengths
7
55
func_path_in_repository
stringlengths
4
223
func_name
stringlengths
1
134
whole_func_string
stringlengths
75
104k
language
stringclasses
1 value
func_code_string
stringlengths
75
104k
func_code_tokens
listlengths
19
28.4k
func_documentation_string
stringlengths
1
46.9k
func_documentation_tokens
listlengths
1
1.97k
split_name
stringclasses
1 value
func_code_url
stringlengths
87
315
yunpian/yunpian-python-sdk
yunpian_python_sdk/api/sms.py
SmsApi.count
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 否 需要查询的手机号 15205201314 page_num Integer 否 页码,默认值为1 1 page_size Integer 否 每页个数,最大100个 20 Args: param: Results: Result ''' r = self.verify_param(param, must) if not r.is_succ(): return r h = CommonResultHandler(lambda rsp: int(rsp[TOTAL]) if TOTAL in rsp else 0) return self.path('count.json').post(param, h, r)
python
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 否 需要查询的手机号 15205201314 page_num Integer 否 页码,默认值为1 1 page_size Integer 否 每页个数,最大100个 20 Args: param: Results: Result ''' r = self.verify_param(param, must) if not r.is_succ(): return r h = CommonResultHandler(lambda rsp: int(rsp[TOTAL]) if TOTAL in rsp else 0) return self.path('count.json').post(param, h, r)
[ "def", "count", "(", "self", ",", "param", ",", "must", "=", "[", "APIKEY", ",", "START_TIME", ",", "END_TIME", "]", ")", ":", "r", "=", "self", ".", "verify_param", "(", "param", ",", "must", ")", "if", "not", "r", ".", "is_succ", "(", ")", ":", "return", "r", "h", "=", "CommonResultHandler", "(", "lambda", "rsp", ":", "int", "(", "rsp", "[", "TOTAL", "]", ")", "if", "TOTAL", "in", "rsp", "else", "0", ")", "return", "self", ".", "path", "(", "'count.json'", ")", ".", "post", "(", "param", ",", "h", ",", "r", ")" ]
统计短信条数 参数名 类型 是否必须 描述 示例 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
[ "统计短信条数", "参数名", "类型", "是否必须", "描述", "示例", "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" ]
train
https://github.com/yunpian/yunpian-python-sdk/blob/405a1196ec83fdf29ff454f74ef036974be11970/yunpian_python_sdk/api/sms.py#L242-L262
yunpian/yunpian-python-sdk
yunpian_python_sdk/api/sms.py
SmsApi.tpl_send
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 是 变量名和变量值对。请先对您的变量名和变量值分别进行urlencode再传递。使用参考:代码示例。 注:变量名和变量值都不能为空 模板: 【#company#】您的验证码是#code#。 最终发送结果: 【云片网】您的验证码是1234。 tplvalue=urlencode("#code#") + "=" + urlencode("1234") + "&" + urlencode("#company#") + "=" + urlencode("云片网"); 若您直接发送报文请求则使用下面这种形式 tplvalue=urlencode(urlencode("#code#") + "=" + urlencode("1234") + "&" + urlencode("#company#") + "=" + urlencode("云片网")); extend String 否 扩展号。默认不开放,如有需要请联系客服申请 001 uid String 否 用户自定义唯一id。最大长度不超过256的字符串。 默认不开放,如有需要请联系客服申请 10001 Args: param: Results: Result ''' r = self.verify_param(param, must) if not r.is_succ(): return r h = CommonResultHandler(lambda rsp: {VERSION_V1:rsp.get(RESULT)}[self.version()]) return self.path('tpl_send.json').post(param, h, r)
python
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 是 变量名和变量值对。请先对您的变量名和变量值分别进行urlencode再传递。使用参考:代码示例。 注:变量名和变量值都不能为空 模板: 【#company#】您的验证码是#code#。 最终发送结果: 【云片网】您的验证码是1234。 tplvalue=urlencode("#code#") + "=" + urlencode("1234") + "&" + urlencode("#company#") + "=" + urlencode("云片网"); 若您直接发送报文请求则使用下面这种形式 tplvalue=urlencode(urlencode("#code#") + "=" + urlencode("1234") + "&" + urlencode("#company#") + "=" + urlencode("云片网")); extend String 否 扩展号。默认不开放,如有需要请联系客服申请 001 uid String 否 用户自定义唯一id。最大长度不超过256的字符串。 默认不开放,如有需要请联系客服申请 10001 Args: param: Results: Result ''' r = self.verify_param(param, must) if not r.is_succ(): return r h = CommonResultHandler(lambda rsp: {VERSION_V1:rsp.get(RESULT)}[self.version()]) return self.path('tpl_send.json').post(param, h, r)
[ "def", "tpl_send", "(", "self", ",", "param", ",", "must", "=", "[", "APIKEY", ",", "MOBILE", ",", "TPL_ID", ",", "TPL_VALUE", "]", ")", ":", "r", "=", "self", ".", "verify_param", "(", "param", ",", "must", ")", "if", "not", "r", ".", "is_succ", "(", ")", ":", "return", "r", "h", "=", "CommonResultHandler", "(", "lambda", "rsp", ":", "{", "VERSION_V1", ":", "rsp", ".", "get", "(", "RESULT", ")", "}", "[", "self", ".", "version", "(", ")", "]", ")", "return", "self", ".", "path", "(", "'tpl_send.json'", ")", ".", "post", "(", "param", ",", "h", ",", "r", ")" ]
指定模板发送 only v1 deprecated 参数名 类型 是否必须 描述 示例 apikey String 是 用户唯一标识 9b11127a9701975c734b8aee81ee3526 mobile String 是 接收的手机号 15205201314 tpl_id Long 是 模板id 1 tpl_value String 是 变量名和变量值对。请先对您的变量名和变量值分别进行urlencode再传递。使用参考:代码示例。 注:变量名和变量值都不能为空 模板: 【#company#】您的验证码是#code#。 最终发送结果: 【云片网】您的验证码是1234。 tplvalue=urlencode("#code#") + "=" + urlencode("1234") + "&" + urlencode("#company#") + "=" + urlencode("云片网"); 若您直接发送报文请求则使用下面这种形式 tplvalue=urlencode(urlencode("#code#") + "=" + urlencode("1234") + "&" + urlencode("#company#") + "=" + urlencode("云片网")); extend String 否 扩展号。默认不开放,如有需要请联系客服申请 001 uid String 否 用户自定义唯一id。最大长度不超过256的字符串。 默认不开放,如有需要请联系客服申请 10001 Args: param: Results: Result
[ "指定模板发送", "only", "v1", "deprecated", "参数名", "类型", "是否必须", "描述", "示例", "apikey", "String", "是", "用户唯一标识", "9b11127a9701975c734b8aee81ee3526", "mobile", "String", "是", "接收的手机号", "15205201314", "tpl_id", "Long", "是", "模板id", "1", "tpl_value", "String", "是", "变量名和变量值对。请先对您的变量名和变量值分别进行urlencode再传递。使用参考:代码示例。", "注:变量名和变量值都不能为空", "模板:", "【#company#】您的验证码是#code#。", "最终发送结果:", "【云片网】您的验证码是1234。", "tplvalue", "=", "urlencode", "(", "#code#", ")", "+", "=", "+", "urlencode", "(", "1234", ")", "+", "&amp", ";", "+", "urlencode", "(", "#company#", ")", "+", "=", "+", "urlencode", "(", "云片网", ")", ";", "若您直接发送报文请求则使用下面这种形式", "tplvalue", "=", "urlencode", "(", "urlencode", "(", "#code#", ")", "+", "=", "+", "urlencode", "(", "1234", ")", "+", "&amp", ";", "+", "urlencode", "(", "#company#", ")", "+", "=", "+", "urlencode", "(", "云片网", "))", ";", "extend", "String", "否", "扩展号。默认不开放,如有需要请联系客服申请", "001", "uid", "String", "否", "用户自定义唯一id。最大长度不超过256的字符串。", "默认不开放,如有需要请联系客服申请", "10001", "Args", ":", "param", ":", "Results", ":", "Result" ]
train
https://github.com/yunpian/yunpian-python-sdk/blob/405a1196ec83fdf29ff454f74ef036974be11970/yunpian_python_sdk/api/sms.py#L264-L289
yunpian/yunpian-python-sdk
yunpian_python_sdk/api/sms.py
SmsApi.tpl_single_send
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格式说明,参见: https://en.wikipedia.org/wiki/E.164) 15205201314 tpl_id Long 是 模板id 1 tpl_value String 是 变量名和变量值对。请先对您的变量名和变量值分别进行urlencode再传递。使用参考:代码示例。 注:变量名和变量值都不能为空 模板: 【#company#】您的验证码是#code#。 最终发送结果: 【云片网】您的验证码是1234。 tplvalue=urlencode("#code#") + "=" + urlencode("1234") + "&" + urlencode("#company#") + "=" + urlencode("云片网"); 若您直接发送报文请求则使用下面这种形式 tplvalue=urlencode(urlencode("#code#") + "=" + urlencode("1234") + "&" + urlencode("#company#") + "=" + urlencode("云片网")); extend String 否 扩展号。默认不开放,如有需要请联系客服申请 001 uid String 否 用户自定义唯一id。最大长度不超过256的字符串。 默认不开放,如有需要请联系客服申请 10001 Args: param: Results: Result ''' r = self.verify_param(param, must) if not r.is_succ(): return r h = CommonResultHandler(lambda rsp: {VERSION_V2:rsp}[self.version()]) return self.path('tpl_single_send.json').post(param, h, r)
python
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格式说明,参见: https://en.wikipedia.org/wiki/E.164) 15205201314 tpl_id Long 是 模板id 1 tpl_value String 是 变量名和变量值对。请先对您的变量名和变量值分别进行urlencode再传递。使用参考:代码示例。 注:变量名和变量值都不能为空 模板: 【#company#】您的验证码是#code#。 最终发送结果: 【云片网】您的验证码是1234。 tplvalue=urlencode("#code#") + "=" + urlencode("1234") + "&" + urlencode("#company#") + "=" + urlencode("云片网"); 若您直接发送报文请求则使用下面这种形式 tplvalue=urlencode(urlencode("#code#") + "=" + urlencode("1234") + "&" + urlencode("#company#") + "=" + urlencode("云片网")); extend String 否 扩展号。默认不开放,如有需要请联系客服申请 001 uid String 否 用户自定义唯一id。最大长度不超过256的字符串。 默认不开放,如有需要请联系客服申请 10001 Args: param: Results: Result ''' r = self.verify_param(param, must) if not r.is_succ(): return r h = CommonResultHandler(lambda rsp: {VERSION_V2:rsp}[self.version()]) return self.path('tpl_single_send.json').post(param, h, r)
[ "def", "tpl_single_send", "(", "self", ",", "param", ",", "must", "=", "[", "APIKEY", ",", "MOBILE", ",", "TPL_ID", ",", "TPL_VALUE", "]", ")", ":", "r", "=", "self", ".", "verify_param", "(", "param", ",", "must", ")", "if", "not", "r", ".", "is_succ", "(", ")", ":", "return", "r", "h", "=", "CommonResultHandler", "(", "lambda", "rsp", ":", "{", "VERSION_V2", ":", "rsp", "}", "[", "self", ".", "version", "(", ")", "]", ")", "return", "self", ".", "path", "(", "'tpl_single_send.json'", ")", ".", "post", "(", "param", ",", "h", ",", "r", ")" ]
指定模板单发 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 tpl_value String 是 变量名和变量值对。请先对您的变量名和变量值分别进行urlencode再传递。使用参考:代码示例。 注:变量名和变量值都不能为空 模板: 【#company#】您的验证码是#code#。 最终发送结果: 【云片网】您的验证码是1234。 tplvalue=urlencode("#code#") + "=" + urlencode("1234") + "&" + urlencode("#company#") + "=" + urlencode("云片网"); 若您直接发送报文请求则使用下面这种形式 tplvalue=urlencode(urlencode("#code#") + "=" + urlencode("1234") + "&" + urlencode("#company#") + "=" + urlencode("云片网")); extend String 否 扩展号。默认不开放,如有需要请联系客服申请 001 uid String 否 用户自定义唯一id。最大长度不超过256的字符串。 默认不开放,如有需要请联系客服申请 10001 Args: param: Results: Result
[ "指定模板单发", "only", "v2", "deprecated" ]
train
https://github.com/yunpian/yunpian-python-sdk/blob/405a1196ec83fdf29ff454f74ef036974be11970/yunpian_python_sdk/api/sms.py#L291-L318
yunpian/yunpian-python-sdk
yunpian_python_sdk/api/flow.py
FlowApi.get_package
def get_package(self, param=None, must=[APIKEY]): '''查询流量包 参数名 类型 是否必须 描述 示例 apikey String 是 用户唯一标识 9b11127a9701975c734b8aee81ee3526 carrier String 否 运营商ID 传入该参数则获取指定运营商的流量包, 否则获取所有运营商的流量包 移动:10086 联通:10010 电信:10000 Args: param: Results: Result ''' param = {} if param is None else param r = self.verify_param(param, must) if not r.is_succ(): return r h = CommonResultHandler(lambda rsp: {VERSION_V1:rsp[FLOW_PACKAGE] if FLOW_PACKAGE in rsp else None, VERSION_V2:rsp}[self.version()]) return self.path('get_package.json').post(param, h, r)
python
def get_package(self, param=None, must=[APIKEY]): '''查询流量包 参数名 类型 是否必须 描述 示例 apikey String 是 用户唯一标识 9b11127a9701975c734b8aee81ee3526 carrier String 否 运营商ID 传入该参数则获取指定运营商的流量包, 否则获取所有运营商的流量包 移动:10086 联通:10010 电信:10000 Args: param: Results: Result ''' param = {} if param is None else param r = self.verify_param(param, must) if not r.is_succ(): return r h = CommonResultHandler(lambda rsp: {VERSION_V1:rsp[FLOW_PACKAGE] if FLOW_PACKAGE in rsp else None, VERSION_V2:rsp}[self.version()]) return self.path('get_package.json').post(param, h, r)
[ "def", "get_package", "(", "self", ",", "param", "=", "None", ",", "must", "=", "[", "APIKEY", "]", ")", ":", "param", "=", "{", "}", "if", "param", "is", "None", "else", "param", "r", "=", "self", ".", "verify_param", "(", "param", ",", "must", ")", "if", "not", "r", ".", "is_succ", "(", ")", ":", "return", "r", "h", "=", "CommonResultHandler", "(", "lambda", "rsp", ":", "{", "VERSION_V1", ":", "rsp", "[", "FLOW_PACKAGE", "]", "if", "FLOW_PACKAGE", "in", "rsp", "else", "None", ",", "VERSION_V2", ":", "rsp", "}", "[", "self", ".", "version", "(", ")", "]", ")", "return", "self", ".", "path", "(", "'get_package.json'", ")", ".", "post", "(", "param", ",", "h", ",", "r", ")" ]
查询流量包 参数名 类型 是否必须 描述 示例 apikey String 是 用户唯一标识 9b11127a9701975c734b8aee81ee3526 carrier String 否 运营商ID 传入该参数则获取指定运营商的流量包, 否则获取所有运营商的流量包 移动:10086 联通:10010 电信:10000 Args: param: Results: Result
[ "查询流量包", "参数名", "类型", "是否必须", "描述", "示例", "apikey", "String", "是", "用户唯一标识", "9b11127a9701975c734b8aee81ee3526", "carrier", "String", "否", "运营商ID", "传入该参数则获取指定运营商的流量包,", "否则获取所有运营商的流量包", "移动:10086", "联通:10010", "电信:10000", "Args", ":", "param", ":", "Results", ":", "Result" ]
train
https://github.com/yunpian/yunpian-python-sdk/blob/405a1196ec83fdf29ff454f74ef036974be11970/yunpian_python_sdk/api/flow.py#L19-L36
yunpian/yunpian-python-sdk
yunpian_python_sdk/api/flow.py
FlowApi.recharge
def recharge(self, param, must=[APIKEY, MOBILE, SN]): '''充值流量 参数名 类型 是否必须 描述 示例 apikey String 是 用户唯一标识 9b11127a9701975c734b8aee81ee3526 mobile String 是 接收的手机号(仅支持大陆号码) 15205201314 sn String 是 流量包的唯一ID 点击查看 1008601 callback_url String 否 本条流量充值的状态报告推送地址 http://your_receive_url_address encrypt String 否 加密方式 使用加密 tea (不再使用) _sign String 否 签名字段 参考使用加密 393d079e0a00912335adfe46f4a2e10f (不再使用) Args: param: Results: Result ''' r = self.verify_param(param, must) if not r.is_succ(): return r h = CommonResultHandler(lambda rsp: {VERSION_V1:rsp[RESULT] if RESULT in rsp else None, VERSION_V2:rsp}[self.version()]) return self.path('recharge.json').post(param, h, r)
python
def recharge(self, param, must=[APIKEY, MOBILE, SN]): '''充值流量 参数名 类型 是否必须 描述 示例 apikey String 是 用户唯一标识 9b11127a9701975c734b8aee81ee3526 mobile String 是 接收的手机号(仅支持大陆号码) 15205201314 sn String 是 流量包的唯一ID 点击查看 1008601 callback_url String 否 本条流量充值的状态报告推送地址 http://your_receive_url_address encrypt String 否 加密方式 使用加密 tea (不再使用) _sign String 否 签名字段 参考使用加密 393d079e0a00912335adfe46f4a2e10f (不再使用) Args: param: Results: Result ''' r = self.verify_param(param, must) if not r.is_succ(): return r h = CommonResultHandler(lambda rsp: {VERSION_V1:rsp[RESULT] if RESULT in rsp else None, VERSION_V2:rsp}[self.version()]) return self.path('recharge.json').post(param, h, r)
[ "def", "recharge", "(", "self", ",", "param", ",", "must", "=", "[", "APIKEY", ",", "MOBILE", ",", "SN", "]", ")", ":", "r", "=", "self", ".", "verify_param", "(", "param", ",", "must", ")", "if", "not", "r", ".", "is_succ", "(", ")", ":", "return", "r", "h", "=", "CommonResultHandler", "(", "lambda", "rsp", ":", "{", "VERSION_V1", ":", "rsp", "[", "RESULT", "]", "if", "RESULT", "in", "rsp", "else", "None", ",", "VERSION_V2", ":", "rsp", "}", "[", "self", ".", "version", "(", ")", "]", ")", "return", "self", ".", "path", "(", "'recharge.json'", ")", ".", "post", "(", "param", ",", "h", ",", "r", ")" ]
充值流量 参数名 类型 是否必须 描述 示例 apikey String 是 用户唯一标识 9b11127a9701975c734b8aee81ee3526 mobile String 是 接收的手机号(仅支持大陆号码) 15205201314 sn String 是 流量包的唯一ID 点击查看 1008601 callback_url String 否 本条流量充值的状态报告推送地址 http://your_receive_url_address encrypt String 否 加密方式 使用加密 tea (不再使用) _sign String 否 签名字段 参考使用加密 393d079e0a00912335adfe46f4a2e10f (不再使用) Args: param: Results: Result
[ "充值流量", "参数名", "类型", "是否必须", "描述", "示例", "apikey", "String", "是", "用户唯一标识", "9b11127a9701975c734b8aee81ee3526", "mobile", "String", "是", "接收的手机号(仅支持大陆号码)", "15205201314", "sn", "String", "是", "流量包的唯一ID", "点击查看", "1008601", "callback_url", "String", "否", "本条流量充值的状态报告推送地址", "http", ":", "//", "your_receive_url_address", "encrypt", "String", "否", "加密方式", "使用加密", "tea", "(", "不再使用", ")", "_sign", "String", "否", "签名字段", "参考使用加密", "393d079e0a00912335adfe46f4a2e10f", "(", "不再使用", ")", "Args", ":", "param", ":", "Results", ":", "Result" ]
train
https://github.com/yunpian/yunpian-python-sdk/blob/405a1196ec83fdf29ff454f74ef036974be11970/yunpian_python_sdk/api/flow.py#L38-L58
yunpian/yunpian-python-sdk
yunpian_python_sdk/api/flow.py
FlowApi.pull_status
def pull_status(self, param=None, must=[APIKEY]): '''获取状态报告 参数名 是否必须 描述 示例 apikey 是 用户唯一标识 9b11127a9701975c734b8aee81ee3526 page_size 否 每页个数,最大100个,默认20个 20 Args: param: Results: Result ''' param = {} if param is None else param r = self.verify_param(param, must) if not r.is_succ(): return r h = CommonResultHandler(lambda rsp: {VERSION_V1:rsp[FLOW_STATUS] if FLOW_STATUS in rsp else None, VERSION_V2:rsp}[self.version()]) return self.path('pull_status.json').post(param, h, r)
python
def pull_status(self, param=None, must=[APIKEY]): '''获取状态报告 参数名 是否必须 描述 示例 apikey 是 用户唯一标识 9b11127a9701975c734b8aee81ee3526 page_size 否 每页个数,最大100个,默认20个 20 Args: param: Results: Result ''' param = {} if param is None else param r = self.verify_param(param, must) if not r.is_succ(): return r h = CommonResultHandler(lambda rsp: {VERSION_V1:rsp[FLOW_STATUS] if FLOW_STATUS in rsp else None, VERSION_V2:rsp}[self.version()]) return self.path('pull_status.json').post(param, h, r)
[ "def", "pull_status", "(", "self", ",", "param", "=", "None", ",", "must", "=", "[", "APIKEY", "]", ")", ":", "param", "=", "{", "}", "if", "param", "is", "None", "else", "param", "r", "=", "self", ".", "verify_param", "(", "param", ",", "must", ")", "if", "not", "r", ".", "is_succ", "(", ")", ":", "return", "r", "h", "=", "CommonResultHandler", "(", "lambda", "rsp", ":", "{", "VERSION_V1", ":", "rsp", "[", "FLOW_STATUS", "]", "if", "FLOW_STATUS", "in", "rsp", "else", "None", ",", "VERSION_V2", ":", "rsp", "}", "[", "self", ".", "version", "(", ")", "]", ")", "return", "self", ".", "path", "(", "'pull_status.json'", ")", ".", "post", "(", "param", ",", "h", ",", "r", ")" ]
获取状态报告 参数名 是否必须 描述 示例 apikey 是 用户唯一标识 9b11127a9701975c734b8aee81ee3526 page_size 否 每页个数,最大100个,默认20个 20 Args: param: Results: Result
[ "获取状态报告", "参数名", "是否必须", "描述", "示例", "apikey", "是", "用户唯一标识", "9b11127a9701975c734b8aee81ee3526", "page_size", "否", "每页个数,最大100个,默认20个", "20", "Args", ":", "param", ":", "Results", ":", "Result" ]
train
https://github.com/yunpian/yunpian-python-sdk/blob/405a1196ec83fdf29ff454f74ef036974be11970/yunpian_python_sdk/api/flow.py#L60-L77
doconix/django-mako-plus
django_mako_plus/command.py
run_command
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.stdout) print(ret.stderr) On Windows, the PATH is not followed. This can be overcome with: import shutil run_command(shutil.which('program'), '-l', '/Users/me/My Documents') ''' args = [ str(a) for a in args ] log.info('running %s', ' '.join(args)) p = subprocess.Popen(args, stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE, cwd=cwd) stdout, stderr = p.communicate() returninfo = ReturnInfo(p.returncode, stdout.decode('utf8'), stderr.decode('utf8')) if stdout: log.info('%s', returninfo.stdout) if raise_exception and returninfo.code != 0: raise CommandError(' '.join(args), returninfo) return returninfo
python
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.stdout) print(ret.stderr) On Windows, the PATH is not followed. This can be overcome with: import shutil run_command(shutil.which('program'), '-l', '/Users/me/My Documents') ''' args = [ str(a) for a in args ] log.info('running %s', ' '.join(args)) p = subprocess.Popen(args, stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE, cwd=cwd) stdout, stderr = p.communicate() returninfo = ReturnInfo(p.returncode, stdout.decode('utf8'), stderr.decode('utf8')) if stdout: log.info('%s', returninfo.stdout) if raise_exception and returninfo.code != 0: raise CommandError(' '.join(args), returninfo) return returninfo
[ "def", "run_command", "(", "*", "args", ",", "raise_exception", "=", "True", ",", "cwd", "=", "None", ")", ":", "args", "=", "[", "str", "(", "a", ")", "for", "a", "in", "args", "]", "log", ".", "info", "(", "'running %s'", ",", "' '", ".", "join", "(", "args", ")", ")", "p", "=", "subprocess", ".", "Popen", "(", "args", ",", "stdout", "=", "subprocess", ".", "PIPE", ",", "stderr", "=", "subprocess", ".", "PIPE", ",", "stdin", "=", "subprocess", ".", "PIPE", ",", "cwd", "=", "cwd", ")", "stdout", ",", "stderr", "=", "p", ".", "communicate", "(", ")", "returninfo", "=", "ReturnInfo", "(", "p", ".", "returncode", ",", "stdout", ".", "decode", "(", "'utf8'", ")", ",", "stderr", ".", "decode", "(", "'utf8'", ")", ")", "if", "stdout", ":", "log", ".", "info", "(", "'%s'", ",", "returninfo", ".", "stdout", ")", "if", "raise_exception", "and", "returninfo", ".", "code", "!=", "0", ":", "raise", "CommandError", "(", "' '", ".", "join", "(", "args", ")", ",", "returninfo", ")", "return", "returninfo" ]
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 followed. This can be overcome with: import shutil run_command(shutil.which('program'), '-l', '/Users/me/My Documents')
[ "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", ":" ]
train
https://github.com/doconix/django-mako-plus/blob/a90f9b4af19e5fa9f83452989cdcaed21569a181/django_mako_plus/command.py#L13-L37
doconix/django-mako-plus
django_mako_plus/template/loader.py
MakoTemplateLoader.get_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 around it so you can use it the same as any Django template. If def_name is provided, template rendering will be limited to the named def/block (see Mako docs). This method corresponds to the Django templating system API. A Django exception is raised if the template is not found or cannot compile. ''' try: # wrap the mako template in an adapter that gives the Django template API return MakoTemplateAdapter(self.get_mako_template(template), def_name) except (TopLevelLookupException, TemplateLookupException) as e: # Mako exception raised tdne = TemplateDoesNotExist('Template "%s" not found in search path: %s.' % (template, self.template_search_dirs)) if settings.DEBUG: tdne.template_debug = get_template_debug(template, e) raise tdne from e except (CompileException, SyntaxException) as e: # Mako exception raised tse = TemplateSyntaxError('Template "%s" raised an error: %s' % (template, e)) if settings.DEBUG: tse.template_debug = get_template_debug(template, e) raise tse from e
python
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 around it so you can use it the same as any Django template. If def_name is provided, template rendering will be limited to the named def/block (see Mako docs). This method corresponds to the Django templating system API. A Django exception is raised if the template is not found or cannot compile. ''' try: # wrap the mako template in an adapter that gives the Django template API return MakoTemplateAdapter(self.get_mako_template(template), def_name) except (TopLevelLookupException, TemplateLookupException) as e: # Mako exception raised tdne = TemplateDoesNotExist('Template "%s" not found in search path: %s.' % (template, self.template_search_dirs)) if settings.DEBUG: tdne.template_debug = get_template_debug(template, e) raise tdne from e except (CompileException, SyntaxException) as e: # Mako exception raised tse = TemplateSyntaxError('Template "%s" raised an error: %s' % (template, e)) if settings.DEBUG: tse.template_debug = get_template_debug(template, e) raise tse from e
[ "def", "get_template", "(", "self", ",", "template", ",", "def_name", "=", "None", ")", ":", "try", ":", "# wrap the mako template in an adapter that gives the Django template API", "return", "MakoTemplateAdapter", "(", "self", ".", "get_mako_template", "(", "template", ")", ",", "def_name", ")", "except", "(", "TopLevelLookupException", ",", "TemplateLookupException", ")", "as", "e", ":", "# Mako exception raised", "tdne", "=", "TemplateDoesNotExist", "(", "'Template \"%s\" not found in search path: %s.'", "%", "(", "template", ",", "self", ".", "template_search_dirs", ")", ")", "if", "settings", ".", "DEBUG", ":", "tdne", ".", "template_debug", "=", "get_template_debug", "(", "template", ",", "e", ")", "raise", "tdne", "from", "e", "except", "(", "CompileException", ",", "SyntaxException", ")", "as", "e", ":", "# Mako exception raised", "tse", "=", "TemplateSyntaxError", "(", "'Template \"%s\" raised an error: %s'", "%", "(", "template", ",", "e", ")", ")", "if", "settings", ".", "DEBUG", ":", "tse", ".", "template_debug", "=", "get_template_debug", "(", "template", ",", "e", ")", "raise", "tse", "from", "e" ]
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. If def_name is provided, template rendering will be limited to the named def/block (see Mako docs). This method corresponds to the Django templating system API. A Django exception is raised if the template is not found or cannot compile.
[ "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", "." ]
train
https://github.com/doconix/django-mako-plus/blob/a90f9b4af19e5fa9f83452989cdcaed21569a181/django_mako_plus/template/loader.py#L71-L95
doconix/django-mako-plus
django_mako_plus/template/loader.py
MakoTemplateLoader.get_mako_template
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 actual Mako template object. This method raises a Mako exception if the template is not found or cannot compile. If force is True, an empty Mako template will be created when the file does not exist. This option is used by the providers part of DMP and normally be left False. ''' if template is None: raise TemplateLookupException('Template "%s" not found in search path: %s.' % (template, self.template_search_dirs)) # get the template try: template_obj = self.tlookup.get_template(template) except TemplateLookupException: if not force: raise template_obj = Template('', filename=os.path.join(self.template_dir, template)) # get the template return template_obj
python
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 actual Mako template object. This method raises a Mako exception if the template is not found or cannot compile. If force is True, an empty Mako template will be created when the file does not exist. This option is used by the providers part of DMP and normally be left False. ''' if template is None: raise TemplateLookupException('Template "%s" not found in search path: %s.' % (template, self.template_search_dirs)) # get the template try: template_obj = self.tlookup.get_template(template) except TemplateLookupException: if not force: raise template_obj = Template('', filename=os.path.join(self.template_dir, template)) # get the template return template_obj
[ "def", "get_mako_template", "(", "self", ",", "template", ",", "force", "=", "False", ")", ":", "if", "template", "is", "None", ":", "raise", "TemplateLookupException", "(", "'Template \"%s\" not found in search path: %s.'", "%", "(", "template", ",", "self", ".", "template_search_dirs", ")", ")", "# get the template", "try", ":", "template_obj", "=", "self", ".", "tlookup", ".", "get_template", "(", "template", ")", "except", "TemplateLookupException", ":", "if", "not", "force", ":", "raise", "template_obj", "=", "Template", "(", "''", ",", "filename", "=", "os", ".", "path", ".", "join", "(", "self", ".", "template_dir", ",", "template", ")", ")", "# get the template", "return", "template_obj" ]
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 exception if the template is not found or cannot compile. If force is True, an empty Mako template will be created when the file does not exist. This option is used by the providers part of DMP and normally be left 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", "." ]
train
https://github.com/doconix/django-mako-plus/blob/a90f9b4af19e5fa9f83452989cdcaed21569a181/django_mako_plus/template/loader.py#L98-L119
doconix/django-mako-plus
django_mako_plus/router/resolver.py
app_resolver
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( '^{}/?'.format(app_name) if app_name is not None else '', include(urlconf), name=urlconf.app_name, ) # this next line is a workaround for Django's URLResolver class not having # a `name` attribute, which is expected in Django's technical_404.html. resolver.name = getattr(resolver, 'name', name or app_name) return resolver
python
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( '^{}/?'.format(app_name) if app_name is not None else '', include(urlconf), name=urlconf.app_name, ) # this next line is a workaround for Django's URLResolver class not having # a `name` attribute, which is expected in Django's technical_404.html. resolver.name = getattr(resolver, 'name', name or app_name) return resolver
[ "def", "app_resolver", "(", "app_name", "=", "None", ",", "pattern_kwargs", "=", "None", ",", "name", "=", "None", ")", ":", "urlconf", "=", "URLConf", "(", "app_name", ",", "pattern_kwargs", ")", "resolver", "=", "re_path", "(", "'^{}/?'", ".", "format", "(", "app_name", ")", "if", "app_name", "is", "not", "None", "else", "''", ",", "include", "(", "urlconf", ")", ",", "name", "=", "urlconf", ".", "app_name", ",", ")", "# this next line is a workaround for Django's URLResolver class not having", "# a `name` attribute, which is expected in Django's technical_404.html.", "resolver", ".", "name", "=", "getattr", "(", "resolver", ",", "'name'", ",", "name", "or", "app_name", ")", "return", "resolver" ]
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.
[ "Registers", "the", "given", "app_name", "with", "DMP", "and", "adds", "convention", "-", "based", "url", "patterns", "for", "it", "." ]
train
https://github.com/doconix/django-mako-plus/blob/a90f9b4af19e5fa9f83452989cdcaed21569a181/django_mako_plus/router/resolver.py#L30-L46
doconix/django-mako-plus
django_mako_plus/router/resolver.py
dmp_paths_for_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 -- it's already been # handled by the app's resolver. # # Also note how the each pattern below defines the four kwargs-- # either as 1) a regex named group or 2) in kwargs. return [ # page.function/urlparams dmp_path( r'^(?P<dmp_page>[_a-zA-Z0-9\-]+)\.(?P<dmp_function>[_a-zA-Z0-9\.\-]+)/(?P<dmp_urlparams>.+?)/?$', merge_dicts({ 'dmp_app': app_name or dmp.options['DEFAULT_APP'], }, pattern_kwargs), 'DMP /{}/page.function/urlparams'.format(pretty_app_name), app_name, ), # page.function dmp_path( r'^(?P<dmp_page>[_a-zA-Z0-9\-]+)\.(?P<dmp_function>[_a-zA-Z0-9\.\-]+)/?$', merge_dicts({ 'dmp_app': app_name or dmp.options['DEFAULT_APP'], 'dmp_urlparams': '', }, pattern_kwargs), 'DMP /{}/page.function'.format(pretty_app_name), app_name, ), # page/urlparams dmp_path( r'^(?P<dmp_page>[_a-zA-Z0-9\-]+)/(?P<dmp_urlparams>.+?)/?$', merge_dicts({ 'dmp_app': app_name or dmp.options['DEFAULT_APP'], 'dmp_function': 'process_request', }, pattern_kwargs), 'DMP /{}/page/urlparams'.format(pretty_app_name), app_name, ), # page dmp_path( r'^(?P<dmp_page>[_a-zA-Z0-9\-]+)/?$', merge_dicts({ 'dmp_app': app_name or dmp.options['DEFAULT_APP'], 'dmp_function': 'process_request', 'dmp_urlparams': '', }, pattern_kwargs), 'DMP /{}/page'.format(pretty_app_name), app_name, ), # empty dmp_path( r'^$', merge_dicts({ 'dmp_app': app_name or dmp.options['DEFAULT_APP'], 'dmp_function': 'process_request', 'dmp_urlparams': '', 'dmp_page': dmp.options['DEFAULT_PAGE'], }, pattern_kwargs), 'DMP /{}'.format(pretty_app_name), app_name, ), ]
python
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 -- it's already been # handled by the app's resolver. # # Also note how the each pattern below defines the four kwargs-- # either as 1) a regex named group or 2) in kwargs. return [ # page.function/urlparams dmp_path( r'^(?P<dmp_page>[_a-zA-Z0-9\-]+)\.(?P<dmp_function>[_a-zA-Z0-9\.\-]+)/(?P<dmp_urlparams>.+?)/?$', merge_dicts({ 'dmp_app': app_name or dmp.options['DEFAULT_APP'], }, pattern_kwargs), 'DMP /{}/page.function/urlparams'.format(pretty_app_name), app_name, ), # page.function dmp_path( r'^(?P<dmp_page>[_a-zA-Z0-9\-]+)\.(?P<dmp_function>[_a-zA-Z0-9\.\-]+)/?$', merge_dicts({ 'dmp_app': app_name or dmp.options['DEFAULT_APP'], 'dmp_urlparams': '', }, pattern_kwargs), 'DMP /{}/page.function'.format(pretty_app_name), app_name, ), # page/urlparams dmp_path( r'^(?P<dmp_page>[_a-zA-Z0-9\-]+)/(?P<dmp_urlparams>.+?)/?$', merge_dicts({ 'dmp_app': app_name or dmp.options['DEFAULT_APP'], 'dmp_function': 'process_request', }, pattern_kwargs), 'DMP /{}/page/urlparams'.format(pretty_app_name), app_name, ), # page dmp_path( r'^(?P<dmp_page>[_a-zA-Z0-9\-]+)/?$', merge_dicts({ 'dmp_app': app_name or dmp.options['DEFAULT_APP'], 'dmp_function': 'process_request', 'dmp_urlparams': '', }, pattern_kwargs), 'DMP /{}/page'.format(pretty_app_name), app_name, ), # empty dmp_path( r'^$', merge_dicts({ 'dmp_app': app_name or dmp.options['DEFAULT_APP'], 'dmp_function': 'process_request', 'dmp_urlparams': '', 'dmp_page': dmp.options['DEFAULT_PAGE'], }, pattern_kwargs), 'DMP /{}'.format(pretty_app_name), app_name, ), ]
[ "def", "dmp_paths_for_app", "(", "app_name", ",", "pattern_kwargs", "=", "None", ",", "pretty_app_name", "=", "None", ")", ":", "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 -- it's already been", "# handled by the app's resolver.", "#", "# Also note how the each pattern below defines the four kwargs--", "# either as 1) a regex named group or 2) in kwargs.", "return", "[", "# page.function/urlparams", "dmp_path", "(", "r'^(?P<dmp_page>[_a-zA-Z0-9\\-]+)\\.(?P<dmp_function>[_a-zA-Z0-9\\.\\-]+)/(?P<dmp_urlparams>.+?)/?$'", ",", "merge_dicts", "(", "{", "'dmp_app'", ":", "app_name", "or", "dmp", ".", "options", "[", "'DEFAULT_APP'", "]", ",", "}", ",", "pattern_kwargs", ")", ",", "'DMP /{}/page.function/urlparams'", ".", "format", "(", "pretty_app_name", ")", ",", "app_name", ",", ")", ",", "# page.function", "dmp_path", "(", "r'^(?P<dmp_page>[_a-zA-Z0-9\\-]+)\\.(?P<dmp_function>[_a-zA-Z0-9\\.\\-]+)/?$'", ",", "merge_dicts", "(", "{", "'dmp_app'", ":", "app_name", "or", "dmp", ".", "options", "[", "'DEFAULT_APP'", "]", ",", "'dmp_urlparams'", ":", "''", ",", "}", ",", "pattern_kwargs", ")", ",", "'DMP /{}/page.function'", ".", "format", "(", "pretty_app_name", ")", ",", "app_name", ",", ")", ",", "# page/urlparams", "dmp_path", "(", "r'^(?P<dmp_page>[_a-zA-Z0-9\\-]+)/(?P<dmp_urlparams>.+?)/?$'", ",", "merge_dicts", "(", "{", "'dmp_app'", ":", "app_name", "or", "dmp", ".", "options", "[", "'DEFAULT_APP'", "]", ",", "'dmp_function'", ":", "'process_request'", ",", "}", ",", "pattern_kwargs", ")", ",", "'DMP /{}/page/urlparams'", ".", "format", "(", "pretty_app_name", ")", ",", "app_name", ",", ")", ",", "# page", "dmp_path", "(", "r'^(?P<dmp_page>[_a-zA-Z0-9\\-]+)/?$'", ",", "merge_dicts", "(", "{", "'dmp_app'", ":", "app_name", "or", "dmp", ".", "options", "[", "'DEFAULT_APP'", "]", ",", "'dmp_function'", ":", "'process_request'", ",", "'dmp_urlparams'", ":", "''", ",", "}", ",", "pattern_kwargs", ")", ",", "'DMP /{}/page'", ".", "format", "(", "pretty_app_name", ")", ",", "app_name", ",", ")", ",", "# empty", "dmp_path", "(", "r'^$'", ",", "merge_dicts", "(", "{", "'dmp_app'", ":", "app_name", "or", "dmp", ".", "options", "[", "'DEFAULT_APP'", "]", ",", "'dmp_function'", ":", "'process_request'", ",", "'dmp_urlparams'", ":", "''", ",", "'dmp_page'", ":", "dmp", ".", "options", "[", "'DEFAULT_PAGE'", "]", ",", "}", ",", "pattern_kwargs", ")", ",", "'DMP /{}'", ".", "format", "(", "pretty_app_name", ")", ",", "app_name", ",", ")", ",", "]" ]
Utility function that creates the default patterns for an app
[ "Utility", "function", "that", "creates", "the", "default", "patterns", "for", "an", "app" ]
train
https://github.com/doconix/django-mako-plus/blob/a90f9b4af19e5fa9f83452989cdcaed21569a181/django_mako_plus/router/resolver.py#L65-L131
doconix/django-mako-plus
django_mako_plus/router/resolver.py
dmp_path
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 resolve to a name in INSTALLED_APPS. If missing, defaults to DEFAULT_APP. dmp_page The page name, which should resolve to a module: project_dir/{dmp_app}/views/{dmp_page}.py If missing, defaults to DEFAULT_PAGE. dmp_function The function name (or View class name) within the module. If missing, defaults to 'process_request' dmp_urlparams The urlparams string to parse. If missing, defaults to ''. The reason for this convenience function is to be similar to Django functions like url(), re_path(), and path(). ''' return PagePattern(regex, kwargs, name, app_name)
python
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 resolve to a name in INSTALLED_APPS. If missing, defaults to DEFAULT_APP. dmp_page The page name, which should resolve to a module: project_dir/{dmp_app}/views/{dmp_page}.py If missing, defaults to DEFAULT_PAGE. dmp_function The function name (or View class name) within the module. If missing, defaults to 'process_request' dmp_urlparams The urlparams string to parse. If missing, defaults to ''. The reason for this convenience function is to be similar to Django functions like url(), re_path(), and path(). ''' return PagePattern(regex, kwargs, name, app_name)
[ "def", "dmp_path", "(", "regex", ",", "kwargs", "=", "None", ",", "name", "=", "None", ",", "app_name", "=", "None", ")", ":", "return", "PagePattern", "(", "regex", ",", "kwargs", ",", "name", ",", "app_name", ")" ]
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, defaults to DEFAULT_APP. dmp_page The page name, which should resolve to a module: project_dir/{dmp_app}/views/{dmp_page}.py If missing, defaults to DEFAULT_PAGE. dmp_function The function name (or View class name) within the module. If missing, defaults to 'process_request' dmp_urlparams The urlparams string to parse. If missing, defaults to ''. The reason for this convenience function is to be similar to Django functions like url(), re_path(), and path().
[ "Creates", "a", "DMP", "-", "style", "convention", "-", "based", "pattern", "that", "resolves", "to", "various", "view", "functions", "based", "on", "the", "dmp_page", "value", "." ]
train
https://github.com/doconix/django-mako-plus/blob/a90f9b4af19e5fa9f83452989cdcaed21569a181/django_mako_plus/router/resolver.py#L140-L160
doconix/django-mako-plus
django_mako_plus/router/resolver.py
PagePattern.resolve
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: routing_data = RoutingData( match.kwargs.pop('dmp_app', None) or self.dmp.options['DEFAULT_APP'], match.kwargs.pop('dmp_page', None) or self.dmp.options['DEFAULT_PAGE'], match.kwargs.pop('dmp_function', None) or 'process_request', match.kwargs.pop('dmp_urlparams', '').strip(), ) if VERSION < (2, 2): return ResolverMatch( RequestViewWrapper(routing_data), match.args, match.kwargs, url_name=match.url_name, app_names=routing_data.app, ) else: return ResolverMatch( RequestViewWrapper(routing_data), match.args, match.kwargs, url_name=match.url_name, app_names=routing_data.app, route=str(self.pattern), ) except ViewDoesNotExist as vdne: # we had a pattern match, but we couldn't get a callable using kwargs from the pattern # create a "pattern" so the programmer can see what happened # this is a hack, but the resolver error page doesn't give other options. # the sad face is to catch the dev's attention in Django's printout msg = "◉︵◉ Pattern matched, but discovery failed: {}".format(vdne) log.debug("%s %s", match.url_name, msg) raise Resolver404({ # this is a bit convoluted, but it makes the PatternStub work with Django 1.x and 2.x 'tried': [[ PatternStub(match.url_name, msg, PatternStub(match.url_name, msg, None)) ]], 'path': path, }) raise Resolver404({'path': path})
python
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: routing_data = RoutingData( match.kwargs.pop('dmp_app', None) or self.dmp.options['DEFAULT_APP'], match.kwargs.pop('dmp_page', None) or self.dmp.options['DEFAULT_PAGE'], match.kwargs.pop('dmp_function', None) or 'process_request', match.kwargs.pop('dmp_urlparams', '').strip(), ) if VERSION < (2, 2): return ResolverMatch( RequestViewWrapper(routing_data), match.args, match.kwargs, url_name=match.url_name, app_names=routing_data.app, ) else: return ResolverMatch( RequestViewWrapper(routing_data), match.args, match.kwargs, url_name=match.url_name, app_names=routing_data.app, route=str(self.pattern), ) except ViewDoesNotExist as vdne: # we had a pattern match, but we couldn't get a callable using kwargs from the pattern # create a "pattern" so the programmer can see what happened # this is a hack, but the resolver error page doesn't give other options. # the sad face is to catch the dev's attention in Django's printout msg = "◉︵◉ Pattern matched, but discovery failed: {}".format(vdne) log.debug("%s %s", match.url_name, msg) raise Resolver404({ # this is a bit convoluted, but it makes the PatternStub work with Django 1.x and 2.x 'tried': [[ PatternStub(match.url_name, msg, PatternStub(match.url_name, msg, None)) ]], 'path': path, }) raise Resolver404({'path': path})
[ "def", "resolve", "(", "self", ",", "path", ")", ":", "match", "=", "super", "(", ")", ".", "resolve", "(", "path", ")", "if", "match", ":", "try", ":", "routing_data", "=", "RoutingData", "(", "match", ".", "kwargs", ".", "pop", "(", "'dmp_app'", ",", "None", ")", "or", "self", ".", "dmp", ".", "options", "[", "'DEFAULT_APP'", "]", ",", "match", ".", "kwargs", ".", "pop", "(", "'dmp_page'", ",", "None", ")", "or", "self", ".", "dmp", ".", "options", "[", "'DEFAULT_PAGE'", "]", ",", "match", ".", "kwargs", ".", "pop", "(", "'dmp_function'", ",", "None", ")", "or", "'process_request'", ",", "match", ".", "kwargs", ".", "pop", "(", "'dmp_urlparams'", ",", "''", ")", ".", "strip", "(", ")", ",", ")", "if", "VERSION", "<", "(", "2", ",", "2", ")", ":", "return", "ResolverMatch", "(", "RequestViewWrapper", "(", "routing_data", ")", ",", "match", ".", "args", ",", "match", ".", "kwargs", ",", "url_name", "=", "match", ".", "url_name", ",", "app_names", "=", "routing_data", ".", "app", ",", ")", "else", ":", "return", "ResolverMatch", "(", "RequestViewWrapper", "(", "routing_data", ")", ",", "match", ".", "args", ",", "match", ".", "kwargs", ",", "url_name", "=", "match", ".", "url_name", ",", "app_names", "=", "routing_data", ".", "app", ",", "route", "=", "str", "(", "self", ".", "pattern", ")", ",", ")", "except", "ViewDoesNotExist", "as", "vdne", ":", "# we had a pattern match, but we couldn't get a callable using kwargs from the pattern", "# create a \"pattern\" so the programmer can see what happened", "# this is a hack, but the resolver error page doesn't give other options.", "# the sad face is to catch the dev's attention in Django's printout", "msg", "=", "\"◉︵◉ Pattern matched, but discovery failed: {}\".forma", "t", "(vdne)", "", "", "", "log", ".", "debug", "(", "\"%s %s\"", ",", "match", ".", "url_name", ",", "msg", ")", "raise", "Resolver404", "(", "{", "# this is a bit convoluted, but it makes the PatternStub work with Django 1.x and 2.x", "'tried'", ":", "[", "[", "PatternStub", "(", "match", ".", "url_name", ",", "msg", ",", "PatternStub", "(", "match", ".", "url_name", ",", "msg", ",", "None", ")", ")", "]", "]", ",", "'path'", ":", "path", ",", "}", ")", "raise", "Resolver404", "(", "{", "'path'", ":", "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.
[ "Different", "from", "Django", "this", "method", "matches", "by", "/", "app", "/", "page", "/", "convention", "using", "its", "pattern", ".", "The", "pattern", "should", "create", "keyword", "arguments", "for", "dmp_app", "dmp_page", "." ]
train
https://github.com/doconix/django-mako-plus/blob/a90f9b4af19e5fa9f83452989cdcaed21569a181/django_mako_plus/router/resolver.py#L183-L227
doconix/django-mako-plus
django_mako_plus/filters.py
alternate_syntax
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 additional variables created within the template. This is a kludge that should be used sparingly. The `dmp_include` template tag is often a better option. The following examples assume you have installed the django_mustache template engine in settings.py: ## Simple expression in Mustache syntax: ${ '{{ name }}' | template_syntax(local, 'django_mustache') } ## Embedded Mustache code block: <%block filter="template_syntax(local, 'django_mustache')"> {{#repo}} <b>{{name}}</b> {{/repo}} {{^repo}} No repos :( {{/repo}} </%block> Rendering Django or Jinja2 templates should be done with `django_syntax` and `jinja2_syntax` because it doesn't require the using parameter. ''' # get the request (the MakoTemplateAdapter above places this in the context) request = local.context['request'] if isinstance(local.context, RequestContext) else None # get the current Mako template object so we can attach the compiled string for later use # Mako caches and automatically recreates this if the file changes mako_template = local.template if not hasattr(mako_template, '__compiled_template_syntax'): mako_template.__compiled_template_syntax = {} # create a closure so we can still get to context and using (Mako filters take exactly one parameter: the string to filter) def wrap(template_st): # get the template object, or create and cache it try: template = mako_template.__compiled_template_syntax[template_st] except KeyError: engine = engines[using] template = engine.from_string(template_st) # using full string, even if long, as the key doesn't really affect performance of python's hash (see http://stackoverflow.com/questions/28150047/efficiency-of-long-str-keys-in-python-dictionary) mako_template.__compiled_template_syntax[template_st] = template # create a copy the context and add any kwargs to it dcontext = dict(local.context) dcontext.update(kwargs) # print a debug statement to the log log.debug('rendering embedded expression or block using %s template engine', using) # render the template with the context return template.render(context=dcontext, request=request) # return the embedded function return wrap
python
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 additional variables created within the template. This is a kludge that should be used sparingly. The `dmp_include` template tag is often a better option. The following examples assume you have installed the django_mustache template engine in settings.py: ## Simple expression in Mustache syntax: ${ '{{ name }}' | template_syntax(local, 'django_mustache') } ## Embedded Mustache code block: <%block filter="template_syntax(local, 'django_mustache')"> {{#repo}} <b>{{name}}</b> {{/repo}} {{^repo}} No repos :( {{/repo}} </%block> Rendering Django or Jinja2 templates should be done with `django_syntax` and `jinja2_syntax` because it doesn't require the using parameter. ''' # get the request (the MakoTemplateAdapter above places this in the context) request = local.context['request'] if isinstance(local.context, RequestContext) else None # get the current Mako template object so we can attach the compiled string for later use # Mako caches and automatically recreates this if the file changes mako_template = local.template if not hasattr(mako_template, '__compiled_template_syntax'): mako_template.__compiled_template_syntax = {} # create a closure so we can still get to context and using (Mako filters take exactly one parameter: the string to filter) def wrap(template_st): # get the template object, or create and cache it try: template = mako_template.__compiled_template_syntax[template_st] except KeyError: engine = engines[using] template = engine.from_string(template_st) # using full string, even if long, as the key doesn't really affect performance of python's hash (see http://stackoverflow.com/questions/28150047/efficiency-of-long-str-keys-in-python-dictionary) mako_template.__compiled_template_syntax[template_st] = template # create a copy the context and add any kwargs to it dcontext = dict(local.context) dcontext.update(kwargs) # print a debug statement to the log log.debug('rendering embedded expression or block using %s template engine', using) # render the template with the context return template.render(context=dcontext, request=request) # return the embedded function return wrap
[ "def", "alternate_syntax", "(", "local", ",", "using", ",", "*", "*", "kwargs", ")", ":", "# get the request (the MakoTemplateAdapter above places this in the context)", "request", "=", "local", ".", "context", "[", "'request'", "]", "if", "isinstance", "(", "local", ".", "context", ",", "RequestContext", ")", "else", "None", "# get the current Mako template object so we can attach the compiled string for later use", "# Mako caches and automatically recreates this if the file changes", "mako_template", "=", "local", ".", "template", "if", "not", "hasattr", "(", "mako_template", ",", "'__compiled_template_syntax'", ")", ":", "mako_template", ".", "__compiled_template_syntax", "=", "{", "}", "# create a closure so we can still get to context and using (Mako filters take exactly one parameter: the string to filter)", "def", "wrap", "(", "template_st", ")", ":", "# get the template object, or create and cache it", "try", ":", "template", "=", "mako_template", ".", "__compiled_template_syntax", "[", "template_st", "]", "except", "KeyError", ":", "engine", "=", "engines", "[", "using", "]", "template", "=", "engine", ".", "from_string", "(", "template_st", ")", "# using full string, even if long, as the key doesn't really affect performance of python's hash (see http://stackoverflow.com/questions/28150047/efficiency-of-long-str-keys-in-python-dictionary)", "mako_template", ".", "__compiled_template_syntax", "[", "template_st", "]", "=", "template", "# create a copy the context and add any kwargs to it", "dcontext", "=", "dict", "(", "local", ".", "context", ")", "dcontext", ".", "update", "(", "kwargs", ")", "# print a debug statement to the log", "log", ".", "debug", "(", "'rendering embedded expression or block using %s template engine'", ",", "using", ")", "# render the template with the context", "return", "template", ".", "render", "(", "context", "=", "dcontext", ",", "request", "=", "request", ")", "# return the embedded function", "return", "wrap" ]
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 is a kludge that should be used sparingly. The `dmp_include` template tag is often a better option. The following examples assume you have installed the django_mustache template engine in settings.py: ## Simple expression in Mustache syntax: ${ '{{ name }}' | template_syntax(local, 'django_mustache') } ## Embedded Mustache code block: <%block filter="template_syntax(local, 'django_mustache')"> {{#repo}} <b>{{name}}</b> {{/repo}} {{^repo}} No repos :( {{/repo}} </%block> Rendering Django or Jinja2 templates should be done with `django_syntax` and `jinja2_syntax` because it doesn't require the using parameter.
[ "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", "." ]
train
https://github.com/doconix/django-mako-plus/blob/a90f9b4af19e5fa9f83452989cdcaed21569a181/django_mako_plus/filters.py#L64-L124
doconix/django-mako-plus
django_mako_plus/router/discover.py
get_view_function
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 doing locks) key = ( module_name, function_name ) try: return CACHED_VIEW_FUNCTIONS[key] except KeyError: with rlock: # try again now that we're locked try: return CACHED_VIEW_FUNCTIONS[key] except KeyError: # if we get here, we need to load the view function func = find_view_function(module_name, function_name, fallback_app, fallback_template, verify_decorator) # cache in production mode if not settings.DEBUG: CACHED_VIEW_FUNCTIONS[key] = func return func # the code should never be able to get here raise Exception("Django-Mako-Plus error: get_view_function() should not have been able to get to this point. Please notify the owner of the DMP project. Thanks.")
python
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 doing locks) key = ( module_name, function_name ) try: return CACHED_VIEW_FUNCTIONS[key] except KeyError: with rlock: # try again now that we're locked try: return CACHED_VIEW_FUNCTIONS[key] except KeyError: # if we get here, we need to load the view function func = find_view_function(module_name, function_name, fallback_app, fallback_template, verify_decorator) # cache in production mode if not settings.DEBUG: CACHED_VIEW_FUNCTIONS[key] = func return func # the code should never be able to get here raise Exception("Django-Mako-Plus error: get_view_function() should not have been able to get to this point. Please notify the owner of the DMP project. Thanks.")
[ "def", "get_view_function", "(", "module_name", ",", "function_name", ",", "fallback_app", "=", "None", ",", "fallback_template", "=", "None", ",", "verify_decorator", "=", "True", ")", ":", "# first check the cache (without doing locks)", "key", "=", "(", "module_name", ",", "function_name", ")", "try", ":", "return", "CACHED_VIEW_FUNCTIONS", "[", "key", "]", "except", "KeyError", ":", "with", "rlock", ":", "# try again now that we're locked", "try", ":", "return", "CACHED_VIEW_FUNCTIONS", "[", "key", "]", "except", "KeyError", ":", "# if we get here, we need to load the view function", "func", "=", "find_view_function", "(", "module_name", ",", "function_name", ",", "fallback_app", ",", "fallback_template", ",", "verify_decorator", ")", "# cache in production mode", "if", "not", "settings", ".", "DEBUG", ":", "CACHED_VIEW_FUNCTIONS", "[", "key", "]", "=", "func", "return", "func", "# the code should never be able to get here", "raise", "Exception", "(", "\"Django-Mako-Plus error: get_view_function() should not have been able to get to this point. Please notify the owner of the DMP project. Thanks.\"", ")" ]
Retrieves a view function from the cache, finding it if the first time. Raises ViewDoesNotExist if not found. This is called by resolver.py.
[ "Retrieves", "a", "view", "function", "from", "the", "cache", "finding", "it", "if", "the", "first", "time", ".", "Raises", "ViewDoesNotExist", "if", "not", "found", ".", "This", "is", "called", "by", "resolver", ".", "py", "." ]
train
https://github.com/doconix/django-mako-plus/blob/a90f9b4af19e5fa9f83452989cdcaed21569a181/django_mako_plus/router/discover.py#L24-L47
doconix/django-mako-plus
django_mako_plus/router/discover.py
find_view_function
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_spec first here beacuse I don't want import_module in # a try/except -- there are lots of reasons that importing can fail, and I just want to # know whether the file actually exists. find_spec raises AttributeError if not found. try: spec = find_spec(module_name) except ValueError: spec = None if spec is None: # no view module, so create a view function that directly renders the template try: return create_view_for_template(fallback_app, fallback_template) except TemplateDoesNotExist as e: raise ViewDoesNotExist('view module {} not found, and fallback template {} could not be loaded ({})'.format(module_name, fallback_template, e)) # load the module and function try: module = import_module(module_name) func = getattr(module, function_name) func.view_type = 'function' except ImportError as e: raise ViewDoesNotExist('module "{}" could not be imported: {}'.format(module_name, e)) except AttributeError as e: raise ViewDoesNotExist('module "{}" found successfully, but "{}" was not found: {}'.format(module_name, function_name, e)) # if class-based view, call as_view() to get a view function to it if inspect.isclass(func) and issubclass(func, View): func = func.as_view() func.view_type = 'class' # if regular view function, check the decorator elif verify_decorator and not view_function.is_decorated(func): raise ViewDoesNotExist("view {}.{} was found successfully, but it must be decorated with @view_function or be a subclass of django.views.generic.View.".format(module_name, function_name)) # attach a converter to the view function if dmp.options['PARAMETER_CONVERTER'] is not None: try: converter = import_qualified(dmp.options['PARAMETER_CONVERTER'])(func) setattr(func, CONVERTER_ATTRIBUTE_NAME, converter) except ImportError as e: raise ImproperlyConfigured('Cannot find PARAMETER_CONVERTER: {}'.format(str(e))) # return the function/class return func
python
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_spec first here beacuse I don't want import_module in # a try/except -- there are lots of reasons that importing can fail, and I just want to # know whether the file actually exists. find_spec raises AttributeError if not found. try: spec = find_spec(module_name) except ValueError: spec = None if spec is None: # no view module, so create a view function that directly renders the template try: return create_view_for_template(fallback_app, fallback_template) except TemplateDoesNotExist as e: raise ViewDoesNotExist('view module {} not found, and fallback template {} could not be loaded ({})'.format(module_name, fallback_template, e)) # load the module and function try: module = import_module(module_name) func = getattr(module, function_name) func.view_type = 'function' except ImportError as e: raise ViewDoesNotExist('module "{}" could not be imported: {}'.format(module_name, e)) except AttributeError as e: raise ViewDoesNotExist('module "{}" found successfully, but "{}" was not found: {}'.format(module_name, function_name, e)) # if class-based view, call as_view() to get a view function to it if inspect.isclass(func) and issubclass(func, View): func = func.as_view() func.view_type = 'class' # if regular view function, check the decorator elif verify_decorator and not view_function.is_decorated(func): raise ViewDoesNotExist("view {}.{} was found successfully, but it must be decorated with @view_function or be a subclass of django.views.generic.View.".format(module_name, function_name)) # attach a converter to the view function if dmp.options['PARAMETER_CONVERTER'] is not None: try: converter = import_qualified(dmp.options['PARAMETER_CONVERTER'])(func) setattr(func, CONVERTER_ATTRIBUTE_NAME, converter) except ImportError as e: raise ImproperlyConfigured('Cannot find PARAMETER_CONVERTER: {}'.format(str(e))) # return the function/class return func
[ "def", "find_view_function", "(", "module_name", ",", "function_name", ",", "fallback_app", "=", "None", ",", "fallback_template", "=", "None", ",", "verify_decorator", "=", "True", ")", ":", "dmp", "=", "apps", ".", "get_app_config", "(", "'django_mako_plus'", ")", "# I'm first calling find_spec first here beacuse I don't want import_module in", "# a try/except -- there are lots of reasons that importing can fail, and I just want to", "# know whether the file actually exists. find_spec raises AttributeError if not found.", "try", ":", "spec", "=", "find_spec", "(", "module_name", ")", "except", "ValueError", ":", "spec", "=", "None", "if", "spec", "is", "None", ":", "# no view module, so create a view function that directly renders the template", "try", ":", "return", "create_view_for_template", "(", "fallback_app", ",", "fallback_template", ")", "except", "TemplateDoesNotExist", "as", "e", ":", "raise", "ViewDoesNotExist", "(", "'view module {} not found, and fallback template {} could not be loaded ({})'", ".", "format", "(", "module_name", ",", "fallback_template", ",", "e", ")", ")", "# load the module and function", "try", ":", "module", "=", "import_module", "(", "module_name", ")", "func", "=", "getattr", "(", "module", ",", "function_name", ")", "func", ".", "view_type", "=", "'function'", "except", "ImportError", "as", "e", ":", "raise", "ViewDoesNotExist", "(", "'module \"{}\" could not be imported: {}'", ".", "format", "(", "module_name", ",", "e", ")", ")", "except", "AttributeError", "as", "e", ":", "raise", "ViewDoesNotExist", "(", "'module \"{}\" found successfully, but \"{}\" was not found: {}'", ".", "format", "(", "module_name", ",", "function_name", ",", "e", ")", ")", "# if class-based view, call as_view() to get a view function to it", "if", "inspect", ".", "isclass", "(", "func", ")", "and", "issubclass", "(", "func", ",", "View", ")", ":", "func", "=", "func", ".", "as_view", "(", ")", "func", ".", "view_type", "=", "'class'", "# if regular view function, check the decorator", "elif", "verify_decorator", "and", "not", "view_function", ".", "is_decorated", "(", "func", ")", ":", "raise", "ViewDoesNotExist", "(", "\"view {}.{} was found successfully, but it must be decorated with @view_function or be a subclass of django.views.generic.View.\"", ".", "format", "(", "module_name", ",", "function_name", ")", ")", "# attach a converter to the view function", "if", "dmp", ".", "options", "[", "'PARAMETER_CONVERTER'", "]", "is", "not", "None", ":", "try", ":", "converter", "=", "import_qualified", "(", "dmp", ".", "options", "[", "'PARAMETER_CONVERTER'", "]", ")", "(", "func", ")", "setattr", "(", "func", ",", "CONVERTER_ATTRIBUTE_NAME", ",", "converter", ")", "except", "ImportError", "as", "e", ":", "raise", "ImproperlyConfigured", "(", "'Cannot find PARAMETER_CONVERTER: {}'", ".", "format", "(", "str", "(", "e", ")", ")", ")", "# return the function/class", "return", "func" ]
Finds a view function, class-based view, or template view. Raises ViewDoesNotExist if not found.
[ "Finds", "a", "view", "function", "class", "-", "based", "view", "or", "template", "view", ".", "Raises", "ViewDoesNotExist", "if", "not", "found", "." ]
train
https://github.com/doconix/django-mako-plus/blob/a90f9b4af19e5fa9f83452989cdcaed21569a181/django_mako_plus/router/discover.py#L50-L99
doconix/django-mako-plus
django_mako_plus/router/discover.py
create_view_for_template
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.get_template_loader(app_name).get_template(template_name) # create the view function def template_view(request, *args, **kwargs): # not caching the template object (getting it each time) because Mako has its own cache dmp = apps.get_app_config('django_mako_plus') template = dmp.engine.get_template_loader(app_name).get_template(template_name) return template.render_to_response(request=request, context=kwargs) template_view.view_type = 'template' return template_view
python
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.get_template_loader(app_name).get_template(template_name) # create the view function def template_view(request, *args, **kwargs): # not caching the template object (getting it each time) because Mako has its own cache dmp = apps.get_app_config('django_mako_plus') template = dmp.engine.get_template_loader(app_name).get_template(template_name) return template.render_to_response(request=request, context=kwargs) template_view.view_type = 'template' return template_view
[ "def", "create_view_for_template", "(", "app_name", ",", "template_name", ")", ":", "# ensure the template exists", "apps", ".", "get_app_config", "(", "'django_mako_plus'", ")", ".", "engine", ".", "get_template_loader", "(", "app_name", ")", ".", "get_template", "(", "template_name", ")", "# create the view function", "def", "template_view", "(", "request", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "# not caching the template object (getting it each time) because Mako has its own cache", "dmp", "=", "apps", ".", "get_app_config", "(", "'django_mako_plus'", ")", "template", "=", "dmp", ".", "engine", ".", "get_template_loader", "(", "app_name", ")", ".", "get_template", "(", "template_name", ")", "return", "template", ".", "render_to_response", "(", "request", "=", "request", ",", "context", "=", "kwargs", ")", "template_view", ".", "view_type", "=", "'template'", "return", "template_view" ]
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.
[ "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", "." ]
train
https://github.com/doconix/django-mako-plus/blob/a90f9b4af19e5fa9f83452989cdcaed21569a181/django_mako_plus/router/discover.py#L102-L116
doconix/django-mako-plus
django_mako_plus/provider/base.py
BaseProvider.iter_related
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]
python
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]
[ "def", "iter_related", "(", "self", ")", ":", "for", "tpl", "in", "self", ".", "provider_run", ".", "templates", ":", "yield", "tpl", ".", "providers", "[", "self", ".", "index", "]" ]
Generator function that iterates this object's related providers, which includes this provider.
[ "Generator", "function", "that", "iterates", "this", "object", "s", "related", "providers", "which", "includes", "this", "provider", "." ]
train
https://github.com/doconix/django-mako-plus/blob/a90f9b4af19e5fa9f83452989cdcaed21569a181/django_mako_plus/provider/base.py#L94-L100
doconix/django-mako-plus
django_mako_plus/provider/base.py
BaseProvider.get_cache_item
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'])
python
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'])
[ "def", "get_cache_item", "(", "self", ")", ":", "if", "settings", ".", "DEBUG", ":", "raise", "AttributeError", "(", "'Caching disabled in DEBUG mode'", ")", "return", "getattr", "(", "self", ".", "template", ",", "self", ".", "options", "[", "'template_cache_key'", "]", ")" ]
Gets the cached item. Raises AttributeError if it hasn't been set.
[ "Gets", "the", "cached", "item", ".", "Raises", "AttributeError", "if", "it", "hasn", "t", "been", "set", "." ]
train
https://github.com/doconix/django-mako-plus/blob/a90f9b4af19e5fa9f83452989cdcaed21569a181/django_mako_plus/provider/base.py#L149-L153
doconix/django-mako-plus
django_mako_plus/util/datastruct.py
flatten
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
python
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
[ "def", "flatten", "(", "*", "args", ")", ":", "for", "arg", "in", "args", ":", "if", "isinstance", "(", "arg", ",", "collections", ".", "Iterable", ")", "and", "not", "isinstance", "(", "arg", ",", "(", "str", ",", "bytes", ")", ")", ":", "yield", "from", "flatten", "(", "*", "arg", ")", "else", ":", "yield", "arg" ]
Generator that recursively flattens embedded lists, tuples, etc.
[ "Generator", "that", "recursively", "flattens", "embedded", "lists", "tuples", "etc", "." ]
train
https://github.com/doconix/django-mako-plus/blob/a90f9b4af19e5fa9f83452989cdcaed21569a181/django_mako_plus/util/datastruct.py#L18-L24
doconix/django-mako-plus
django_mako_plus/util/datastruct.py
crc32
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. ''' result = 0 with open(filename, 'rb') as fin: while True: chunk = fin.read(48) if len(chunk) == 0: break result = zlib.crc32(chunk, result) return result
python
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. ''' result = 0 with open(filename, 'rb') as fin: while True: chunk = fin.read(48) if len(chunk) == 0: break result = zlib.crc32(chunk, result) return result
[ "def", "crc32", "(", "filename", ")", ":", "result", "=", "0", "with", "open", "(", "filename", ",", "'rb'", ")", "as", "fin", ":", "while", "True", ":", "chunk", "=", "fin", ".", "read", "(", "48", ")", "if", "len", "(", "chunk", ")", "==", "0", ":", "break", "result", "=", "zlib", ".", "crc32", "(", "chunk", ",", "result", ")", "return", "result" ]
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.
[ "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", "." ]
train
https://github.com/doconix/django-mako-plus/blob/a90f9b4af19e5fa9f83452989cdcaed21569a181/django_mako_plus/util/datastruct.py#L28-L44
doconix/django-mako-plus
django_mako_plus/management/commands/dmp_makemessages.py
Command.compile_mako_files
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.path, app_name=app_config.name, ) def recurse_path(path): self.message('searching for Mako templates in {}'.format(path), 1) if os.path.exists(path): for filename in os.listdir(path): filepath = os.path.join(path, filename) _, ext = os.path.splitext(filename) if filename.startswith('__'): # __dmpcache__, __pycache__ continue elif os.path.isdir(filepath): recurse_path(filepath) elif ext.lower() in ( '.htm', '.html', '.mako' ): # create the template object, which creates the compiled .py file self.message('compiling {}'.format(filepath), 2) try: get_template_for_path(filepath) except TemplateSyntaxError: if not self.options.get('ignore_template_errors'): raise recurse_path(subdir)
python
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.path, app_name=app_config.name, ) def recurse_path(path): self.message('searching for Mako templates in {}'.format(path), 1) if os.path.exists(path): for filename in os.listdir(path): filepath = os.path.join(path, filename) _, ext = os.path.splitext(filename) if filename.startswith('__'): # __dmpcache__, __pycache__ continue elif os.path.isdir(filepath): recurse_path(filepath) elif ext.lower() in ( '.htm', '.html', '.mako' ): # create the template object, which creates the compiled .py file self.message('compiling {}'.format(filepath), 2) try: get_template_for_path(filepath) except TemplateSyntaxError: if not self.options.get('ignore_template_errors'): raise recurse_path(subdir)
[ "def", "compile_mako_files", "(", "self", ",", "app_config", ")", ":", "# 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", ".", "path", ",", "app_name", "=", "app_config", ".", "name", ",", ")", "def", "recurse_path", "(", "path", ")", ":", "self", ".", "message", "(", "'searching for Mako templates in {}'", ".", "format", "(", "path", ")", ",", "1", ")", "if", "os", ".", "path", ".", "exists", "(", "path", ")", ":", "for", "filename", "in", "os", ".", "listdir", "(", "path", ")", ":", "filepath", "=", "os", ".", "path", ".", "join", "(", "path", ",", "filename", ")", "_", ",", "ext", "=", "os", ".", "path", ".", "splitext", "(", "filename", ")", "if", "filename", ".", "startswith", "(", "'__'", ")", ":", "# __dmpcache__, __pycache__", "continue", "elif", "os", ".", "path", ".", "isdir", "(", "filepath", ")", ":", "recurse_path", "(", "filepath", ")", "elif", "ext", ".", "lower", "(", ")", "in", "(", "'.htm'", ",", "'.html'", ",", "'.mako'", ")", ":", "# create the template object, which creates the compiled .py file", "self", ".", "message", "(", "'compiling {}'", ".", "format", "(", "filepath", ")", ",", "2", ")", "try", ":", "get_template_for_path", "(", "filepath", ")", "except", "TemplateSyntaxError", ":", "if", "not", "self", ".", "options", ".", "get", "(", "'ignore_template_errors'", ")", ":", "raise", "recurse_path", "(", "subdir", ")" ]
Compiles the Mako templates within the apps of this system
[ "Compiles", "the", "Mako", "templates", "within", "the", "apps", "of", "this", "system" ]
train
https://github.com/doconix/django-mako-plus/blob/a90f9b4af19e5fa9f83452989cdcaed21569a181/django_mako_plus/management/commands/dmp_makemessages.py#L70-L100
doconix/django-mako-plus
django_mako_plus/engine.py
MakoTemplates.from_string
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, input_encoding=dmp.options['DEFAULT_TEMPLATE_ENCODING']) return MakoTemplateAdapter(mako_template)
python
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, input_encoding=dmp.options['DEFAULT_TEMPLATE_ENCODING']) return MakoTemplateAdapter(mako_template)
[ "def", "from_string", "(", "self", ",", "template_code", ")", ":", "dmp", "=", "apps", ".", "get_app_config", "(", "'django_mako_plus'", ")", "mako_template", "=", "Template", "(", "template_code", ",", "imports", "=", "dmp", ".", "template_imports", ",", "input_encoding", "=", "dmp", ".", "options", "[", "'DEFAULT_TEMPLATE_ENCODING'", "]", ")", "return", "MakoTemplateAdapter", "(", "mako_template", ")" ]
Compiles a template from the given string. This is one of the required methods of Django template engines.
[ "Compiles", "a", "template", "from", "the", "given", "string", ".", "This", "is", "one", "of", "the", "required", "methods", "of", "Django", "template", "engines", "." ]
train
https://github.com/doconix/django-mako-plus/blob/a90f9b4af19e5fa9f83452989cdcaed21569a181/django_mako_plus/engine.py#L58-L65
doconix/django-mako-plus
django_mako_plus/engine.py
MakoTemplates.get_template
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 template_name MUST be in the format: "app_name/template.html" (even on Windows). DMP splits the template_name string on the slash to get the app name and template name. Template rendering can be limited to a specific def/block within the template by specifying `#def_name`, e.g. `myapp/mytemplate.html#myblockname`. ''' dmp = apps.get_app_config('django_mako_plus') match = RE_TEMPLATE_NAME.match(template_name) if match is None or match.group(1) is None or match.group(3) is None: raise TemplateDoesNotExist('Invalid template_name format for a DMP template. This method requires that the template name be in app_name/template.html format (separated by slash).') if not dmp.is_registered_app(match.group(1)): raise TemplateDoesNotExist('Not a DMP app, so deferring to other template engines for this template') return self.get_template_loader(match.group(1)).get_template(match.group(3), def_name=match.group(5))
python
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 template_name MUST be in the format: "app_name/template.html" (even on Windows). DMP splits the template_name string on the slash to get the app name and template name. Template rendering can be limited to a specific def/block within the template by specifying `#def_name`, e.g. `myapp/mytemplate.html#myblockname`. ''' dmp = apps.get_app_config('django_mako_plus') match = RE_TEMPLATE_NAME.match(template_name) if match is None or match.group(1) is None or match.group(3) is None: raise TemplateDoesNotExist('Invalid template_name format for a DMP template. This method requires that the template name be in app_name/template.html format (separated by slash).') if not dmp.is_registered_app(match.group(1)): raise TemplateDoesNotExist('Not a DMP app, so deferring to other template engines for this template') return self.get_template_loader(match.group(1)).get_template(match.group(3), def_name=match.group(5))
[ "def", "get_template", "(", "self", ",", "template_name", ")", ":", "dmp", "=", "apps", ".", "get_app_config", "(", "'django_mako_plus'", ")", "match", "=", "RE_TEMPLATE_NAME", ".", "match", "(", "template_name", ")", "if", "match", "is", "None", "or", "match", ".", "group", "(", "1", ")", "is", "None", "or", "match", ".", "group", "(", "3", ")", "is", "None", ":", "raise", "TemplateDoesNotExist", "(", "'Invalid template_name format for a DMP template. This method requires that the template name be in app_name/template.html format (separated by slash).'", ")", "if", "not", "dmp", ".", "is_registered_app", "(", "match", ".", "group", "(", "1", ")", ")", ":", "raise", "TemplateDoesNotExist", "(", "'Not a DMP app, so deferring to other template engines for this template'", ")", "return", "self", ".", "get_template_loader", "(", "match", ".", "group", "(", "1", ")", ")", ".", "get_template", "(", "match", ".", "group", "(", "3", ")", ",", "def_name", "=", "match", ".", "group", "(", "5", ")", ")" ]
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 template_name MUST be in the format: "app_name/template.html" (even on Windows). DMP splits the template_name string on the slash to get the app name and template name. Template rendering can be limited to a specific def/block within the template by specifying `#def_name`, e.g. `myapp/mytemplate.html#myblockname`.
[ "Retrieves", "a", "template", "object", "from", "the", "pattern", "app_name", "/", "template", ".", "html", ".", "This", "is", "one", "of", "the", "required", "methods", "of", "Django", "template", "engines", "." ]
train
https://github.com/doconix/django-mako-plus/blob/a90f9b4af19e5fa9f83452989cdcaed21569a181/django_mako_plus/engine.py#L68-L87
doconix/django-mako-plus
django_mako_plus/engine.py
MakoTemplates.get_template_loader
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 app parameter can be either an app name or an AppConfig instance. The subdir parameter is normally 'templates', 'scripts', or 'styles', but it can be any subdirectory name of the given app. Normally, you should not have to call this method. Django automatically generates two shortcut functions for every DMP-registered apps, and these shortcut functions are the preferred way to render templates. This method is useful when you want a custom template loader to a directory that does not conform to the app_dir/templates/* pattern. If the loader is not found in the DMP cache, one of two things occur: 1. If create=True, it is created automatically and returned. This overrides the need to register the app as a DMP app. 2. If create=False, a TemplateDoesNotExist is raised. This is the default behavior. ''' # ensure we have an AppConfig if app is None: raise TemplateDoesNotExist("Cannot locate loader when app is None") if not isinstance(app, AppConfig): app = apps.get_app_config(app) # get the loader with the path of this app+subdir path = os.path.join(app.path, subdir) # if create=False, the loader must already exist in the cache if not create: dmp = apps.get_app_config('django_mako_plus') if not dmp.is_registered_app(app): raise ValueError("{} is not registered with DMP [hint: check urls.py for include('django_mako_plus.urls')].".format(app)) # return the template by path return self.get_template_loader_for_path(path, use_cache=True)
python
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 app parameter can be either an app name or an AppConfig instance. The subdir parameter is normally 'templates', 'scripts', or 'styles', but it can be any subdirectory name of the given app. Normally, you should not have to call this method. Django automatically generates two shortcut functions for every DMP-registered apps, and these shortcut functions are the preferred way to render templates. This method is useful when you want a custom template loader to a directory that does not conform to the app_dir/templates/* pattern. If the loader is not found in the DMP cache, one of two things occur: 1. If create=True, it is created automatically and returned. This overrides the need to register the app as a DMP app. 2. If create=False, a TemplateDoesNotExist is raised. This is the default behavior. ''' # ensure we have an AppConfig if app is None: raise TemplateDoesNotExist("Cannot locate loader when app is None") if not isinstance(app, AppConfig): app = apps.get_app_config(app) # get the loader with the path of this app+subdir path = os.path.join(app.path, subdir) # if create=False, the loader must already exist in the cache if not create: dmp = apps.get_app_config('django_mako_plus') if not dmp.is_registered_app(app): raise ValueError("{} is not registered with DMP [hint: check urls.py for include('django_mako_plus.urls')].".format(app)) # return the template by path return self.get_template_loader_for_path(path, use_cache=True)
[ "def", "get_template_loader", "(", "self", ",", "app", ",", "subdir", "=", "'templates'", ",", "create", "=", "False", ")", ":", "# ensure we have an AppConfig", "if", "app", "is", "None", ":", "raise", "TemplateDoesNotExist", "(", "\"Cannot locate loader when app is None\"", ")", "if", "not", "isinstance", "(", "app", ",", "AppConfig", ")", ":", "app", "=", "apps", ".", "get_app_config", "(", "app", ")", "# get the loader with the path of this app+subdir", "path", "=", "os", ".", "path", ".", "join", "(", "app", ".", "path", ",", "subdir", ")", "# if create=False, the loader must already exist in the cache", "if", "not", "create", ":", "dmp", "=", "apps", ".", "get_app_config", "(", "'django_mako_plus'", ")", "if", "not", "dmp", ".", "is_registered_app", "(", "app", ")", ":", "raise", "ValueError", "(", "\"{} is not registered with DMP [hint: check urls.py for include('django_mako_plus.urls')].\"", ".", "format", "(", "app", ")", ")", "# return the template by path", "return", "self", ".", "get_template_loader_for_path", "(", "path", ",", "use_cache", "=", "True", ")" ]
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 app parameter can be either an app name or an AppConfig instance. The subdir parameter is normally 'templates', 'scripts', or 'styles', but it can be any subdirectory name of the given app. Normally, you should not have to call this method. Django automatically generates two shortcut functions for every DMP-registered apps, and these shortcut functions are the preferred way to render templates. This method is useful when you want a custom template loader to a directory that does not conform to the app_dir/templates/* pattern. If the loader is not found in the DMP cache, one of two things occur: 1. If create=True, it is created automatically and returned. This overrides the need to register the app as a DMP app. 2. If create=False, a TemplateDoesNotExist is raised. This is the default behavior.
[ "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", "." ]
train
https://github.com/doconix/django-mako-plus/blob/a90f9b4af19e5fa9f83452989cdcaed21569a181/django_mako_plus/engine.py#L90-L129
doconix/django-mako-plus
django_mako_plus/engine.py
MakoTemplates.get_template_loader_for_path
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 method. Django automatically adds request.dmp.render() and request.dmp.render_to_string() on each request. This method is useful when you want a custom template loader for a specific directory that may be outside your project directory or that is otherwise not contained in a normal Django app. If the directory is inside an app, call get_template_loader() instead. Unless use_cache=False, this method caches template loaders in the DMP cache for later use. ''' # get from the cache if we are able if use_cache: try: return self.template_loaders[path] except KeyError: pass # not there, so we'll create # create the loader loader = MakoTemplateLoader(path, None) # cache if we are allowed if use_cache: self.template_loaders[path] = loader # return return loader
python
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 method. Django automatically adds request.dmp.render() and request.dmp.render_to_string() on each request. This method is useful when you want a custom template loader for a specific directory that may be outside your project directory or that is otherwise not contained in a normal Django app. If the directory is inside an app, call get_template_loader() instead. Unless use_cache=False, this method caches template loaders in the DMP cache for later use. ''' # get from the cache if we are able if use_cache: try: return self.template_loaders[path] except KeyError: pass # not there, so we'll create # create the loader loader = MakoTemplateLoader(path, None) # cache if we are allowed if use_cache: self.template_loaders[path] = loader # return return loader
[ "def", "get_template_loader_for_path", "(", "self", ",", "path", ",", "use_cache", "=", "True", ")", ":", "# get from the cache if we are able", "if", "use_cache", ":", "try", ":", "return", "self", ".", "template_loaders", "[", "path", "]", "except", "KeyError", ":", "pass", "# not there, so we'll create", "# create the loader", "loader", "=", "MakoTemplateLoader", "(", "path", ",", "None", ")", "# cache if we are allowed", "if", "use_cache", ":", "self", ".", "template_loaders", "[", "path", "]", "=", "loader", "# return", "return", "loader" ]
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 method. Django automatically adds request.dmp.render() and request.dmp.render_to_string() on each request. This method is useful when you want a custom template loader for a specific directory that may be outside your project directory or that is otherwise not contained in a normal Django app. If the directory is inside an app, call get_template_loader() instead. Unless use_cache=False, this method caches template loaders in the DMP cache for later use.
[ "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", "." ]
train
https://github.com/doconix/django-mako-plus/blob/a90f9b4af19e5fa9f83452989cdcaed21569a181/django_mako_plus/engine.py#L132-L165
doconix/django-mako-plus
django_mako_plus/converter/base.py
ParameterConverter._register_converter
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()
python
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()
[ "def", "_register_converter", "(", "cls", ",", "conv_func", ",", "conv_type", ")", ":", "cls", ".", "converters", ".", "append", "(", "ConverterFunctionInfo", "(", "conv_func", ",", "conv_type", ",", "len", "(", "cls", ".", "converters", ")", ")", ")", "cls", ".", "_sort_converters", "(", ")" ]
Triggered by the @converter_function decorator
[ "Triggered", "by", "the" ]
train
https://github.com/doconix/django-mako-plus/blob/a90f9b4af19e5fa9f83452989cdcaed21569a181/django_mako_plus/converter/base.py#L83-L86
doconix/django-mako-plus
django_mako_plus/converter/base.py
ParameterConverter._sort_converters
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: for converter in cls.converters: converter.prepare_sort_key() cls.converters.sort(key=attrgetter('sort_key'))
python
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: for converter in cls.converters: converter.prepare_sort_key() cls.converters.sort(key=attrgetter('sort_key'))
[ "def", "_sort_converters", "(", "cls", ",", "app_ready", "=", "False", ")", ":", "# 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", ":", "for", "converter", "in", "cls", ".", "converters", ":", "converter", ".", "prepare_sort_key", "(", ")", "cls", ".", "converters", ".", "sort", "(", "key", "=", "attrgetter", "(", "'sort_key'", ")", ")" ]
Sorts the converter functions
[ "Sorts", "the", "converter", "functions" ]
train
https://github.com/doconix/django-mako-plus/blob/a90f9b4af19e5fa9f83452989cdcaed21569a181/django_mako_plus/converter/base.py#L90-L98
doconix/django-mako-plus
django_mako_plus/converter/base.py
ParameterConverter.convert_parameters
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 = self.view_parameters.get(request.method.lower()) or self.view_parameters.get(None) if parameters is not None: # add urlparams into the arguments and convert the values for parameter_i, parameter in enumerate(parameters): # skip request object, *args, **kwargs if parameter_i == 0 or parameter.kind is inspect.Parameter.VAR_POSITIONAL or parameter.kind is inspect.Parameter.VAR_KEYWORD: pass # value in kwargs? elif parameter.name in kwargs: kwargs[parameter.name] = self.convert_value(kwargs[parameter.name], parameter, request) # value in args? elif parameter_i - 1 < len(args): args[parameter_i - 1] = self.convert_value(args[parameter_i - 1], parameter, request) # urlparam value? elif urlparam_i < len(request.dmp.urlparams): kwargs[parameter.name] = self.convert_value(request.dmp.urlparams[urlparam_i], parameter, request) urlparam_i += 1 # can we assign a default value? elif parameter.default is not inspect.Parameter.empty: kwargs[parameter.name] = self.convert_value(parameter.default, parameter, request) # fallback is None else: kwargs[parameter.name] = self.convert_value(None, parameter, request) return args, kwargs
python
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 = self.view_parameters.get(request.method.lower()) or self.view_parameters.get(None) if parameters is not None: # add urlparams into the arguments and convert the values for parameter_i, parameter in enumerate(parameters): # skip request object, *args, **kwargs if parameter_i == 0 or parameter.kind is inspect.Parameter.VAR_POSITIONAL or parameter.kind is inspect.Parameter.VAR_KEYWORD: pass # value in kwargs? elif parameter.name in kwargs: kwargs[parameter.name] = self.convert_value(kwargs[parameter.name], parameter, request) # value in args? elif parameter_i - 1 < len(args): args[parameter_i - 1] = self.convert_value(args[parameter_i - 1], parameter, request) # urlparam value? elif urlparam_i < len(request.dmp.urlparams): kwargs[parameter.name] = self.convert_value(request.dmp.urlparams[urlparam_i], parameter, request) urlparam_i += 1 # can we assign a default value? elif parameter.default is not inspect.Parameter.empty: kwargs[parameter.name] = self.convert_value(parameter.default, parameter, request) # fallback is None else: kwargs[parameter.name] = self.convert_value(None, parameter, request) return args, kwargs
[ "def", "convert_parameters", "(", "self", ",", "request", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "args", "=", "list", "(", "args", ")", "urlparam_i", "=", "0", "parameters", "=", "self", ".", "view_parameters", ".", "get", "(", "request", ".", "method", ".", "lower", "(", ")", ")", "or", "self", ".", "view_parameters", ".", "get", "(", "None", ")", "if", "parameters", "is", "not", "None", ":", "# add urlparams into the arguments and convert the values", "for", "parameter_i", ",", "parameter", "in", "enumerate", "(", "parameters", ")", ":", "# skip request object, *args, **kwargs", "if", "parameter_i", "==", "0", "or", "parameter", ".", "kind", "is", "inspect", ".", "Parameter", ".", "VAR_POSITIONAL", "or", "parameter", ".", "kind", "is", "inspect", ".", "Parameter", ".", "VAR_KEYWORD", ":", "pass", "# value in kwargs?", "elif", "parameter", ".", "name", "in", "kwargs", ":", "kwargs", "[", "parameter", ".", "name", "]", "=", "self", ".", "convert_value", "(", "kwargs", "[", "parameter", ".", "name", "]", ",", "parameter", ",", "request", ")", "# value in args?", "elif", "parameter_i", "-", "1", "<", "len", "(", "args", ")", ":", "args", "[", "parameter_i", "-", "1", "]", "=", "self", ".", "convert_value", "(", "args", "[", "parameter_i", "-", "1", "]", ",", "parameter", ",", "request", ")", "# urlparam value?", "elif", "urlparam_i", "<", "len", "(", "request", ".", "dmp", ".", "urlparams", ")", ":", "kwargs", "[", "parameter", ".", "name", "]", "=", "self", ".", "convert_value", "(", "request", ".", "dmp", ".", "urlparams", "[", "urlparam_i", "]", ",", "parameter", ",", "request", ")", "urlparam_i", "+=", "1", "# can we assign a default value?", "elif", "parameter", ".", "default", "is", "not", "inspect", ".", "Parameter", ".", "empty", ":", "kwargs", "[", "parameter", ".", "name", "]", "=", "self", ".", "convert_value", "(", "parameter", ".", "default", ",", "parameter", ",", "request", ")", "# fallback is None", "else", ":", "kwargs", "[", "parameter", ".", "name", "]", "=", "self", ".", "convert_value", "(", "None", ",", "parameter", ",", "request", ")", "return", "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.
[ "Iterates", "the", "urlparams", "and", "converts", "them", "according", "to", "the", "type", "hints", "in", "the", "current", "view", "function", ".", "This", "is", "the", "primary", "function", "of", "the", "class", "." ]
train
https://github.com/doconix/django-mako-plus/blob/a90f9b4af19e5fa9f83452989cdcaed21569a181/django_mako_plus/converter/base.py#L101-L134
doconix/django-mako-plus
django_mako_plus/converter/base.py
ParameterConverter.convert_value
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 instance of django_mako_plus.ViewParameter that holds this parameter's name, type, position, etc. request: the current request object. "converter functions" register with this class using the @parameter_converter decorator. See converters.py for the built-in converters. This function goes through the list of registered converter functions, selects the most-specific one that matches the parameter.type, and calls it to convert the value. If the converter function raises a ValueError, it is caught and switched to an Http404 to tell the browser that the requested URL doesn't resolve to a page. Other useful exceptions that converter functions can raise are: Any extension of BaseRedirectException (RedirectException, InternalRedirectException, JavascriptRedirectException, ...) Http404: returns a Django Http404 response ''' try: # we don't convert anything without type hints if parameter.type is inspect.Parameter.empty: if log.isEnabledFor(logging.DEBUG): log.debug('skipping conversion of parameter `%s` because it has no type hint', parameter.name) return value # find the converter method for this type # I'm iterating through the list to find the most specific match first # The list is sorted by specificity so subclasses come before their superclasses for ci in self.converters: if issubclass(parameter.type, ci.convert_type): if log.isEnabledFor(logging.DEBUG): log.debug('converting parameter `%s` using %s', parameter.name, ci.convert_func) return ci.convert_func(value, parameter) # if we get here, there wasn't a converter or this type raise ImproperlyConfigured(message='No parameter converter exists for type: {}. Do you need to add an @parameter_converter function for the type?'.format(parameter.type)) except (BaseRedirectException, Http404): log.info('Exception raised during conversion of parameter %s (%s): %s', parameter.position, parameter.name, e) raise # allow these to pass through to the router except ValueError as e: log.info('ValueError raised during conversion of parameter %s (%s): %s', parameter.position, parameter.name, e) raise ConverterHttp404(value, parameter, 'A parameter could not be converted - see the logs for more detail') from e except Exception as e: log.info('Exception raised during conversion of parameter %s (%s): %s', parameter.position, parameter.name, e) raise ConverterException(value, parameter, 'A parameter could not be converted - see the logs for more detail') from e
python
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 instance of django_mako_plus.ViewParameter that holds this parameter's name, type, position, etc. request: the current request object. "converter functions" register with this class using the @parameter_converter decorator. See converters.py for the built-in converters. This function goes through the list of registered converter functions, selects the most-specific one that matches the parameter.type, and calls it to convert the value. If the converter function raises a ValueError, it is caught and switched to an Http404 to tell the browser that the requested URL doesn't resolve to a page. Other useful exceptions that converter functions can raise are: Any extension of BaseRedirectException (RedirectException, InternalRedirectException, JavascriptRedirectException, ...) Http404: returns a Django Http404 response ''' try: # we don't convert anything without type hints if parameter.type is inspect.Parameter.empty: if log.isEnabledFor(logging.DEBUG): log.debug('skipping conversion of parameter `%s` because it has no type hint', parameter.name) return value # find the converter method for this type # I'm iterating through the list to find the most specific match first # The list is sorted by specificity so subclasses come before their superclasses for ci in self.converters: if issubclass(parameter.type, ci.convert_type): if log.isEnabledFor(logging.DEBUG): log.debug('converting parameter `%s` using %s', parameter.name, ci.convert_func) return ci.convert_func(value, parameter) # if we get here, there wasn't a converter or this type raise ImproperlyConfigured(message='No parameter converter exists for type: {}. Do you need to add an @parameter_converter function for the type?'.format(parameter.type)) except (BaseRedirectException, Http404): log.info('Exception raised during conversion of parameter %s (%s): %s', parameter.position, parameter.name, e) raise # allow these to pass through to the router except ValueError as e: log.info('ValueError raised during conversion of parameter %s (%s): %s', parameter.position, parameter.name, e) raise ConverterHttp404(value, parameter, 'A parameter could not be converted - see the logs for more detail') from e except Exception as e: log.info('Exception raised during conversion of parameter %s (%s): %s', parameter.position, parameter.name, e) raise ConverterException(value, parameter, 'A parameter could not be converted - see the logs for more detail') from e
[ "def", "convert_value", "(", "self", ",", "value", ",", "parameter", ",", "request", ")", ":", "try", ":", "# we don't convert anything without type hints", "if", "parameter", ".", "type", "is", "inspect", ".", "Parameter", ".", "empty", ":", "if", "log", ".", "isEnabledFor", "(", "logging", ".", "DEBUG", ")", ":", "log", ".", "debug", "(", "'skipping conversion of parameter `%s` because it has no type hint'", ",", "parameter", ".", "name", ")", "return", "value", "# find the converter method for this type", "# I'm iterating through the list to find the most specific match first", "# The list is sorted by specificity so subclasses come before their superclasses", "for", "ci", "in", "self", ".", "converters", ":", "if", "issubclass", "(", "parameter", ".", "type", ",", "ci", ".", "convert_type", ")", ":", "if", "log", ".", "isEnabledFor", "(", "logging", ".", "DEBUG", ")", ":", "log", ".", "debug", "(", "'converting parameter `%s` using %s'", ",", "parameter", ".", "name", ",", "ci", ".", "convert_func", ")", "return", "ci", ".", "convert_func", "(", "value", ",", "parameter", ")", "# if we get here, there wasn't a converter or this type", "raise", "ImproperlyConfigured", "(", "message", "=", "'No parameter converter exists for type: {}. Do you need to add an @parameter_converter function for the type?'", ".", "format", "(", "parameter", ".", "type", ")", ")", "except", "(", "BaseRedirectException", ",", "Http404", ")", ":", "log", ".", "info", "(", "'Exception raised during conversion of parameter %s (%s): %s'", ",", "parameter", ".", "position", ",", "parameter", ".", "name", ",", "e", ")", "raise", "# allow these to pass through to the router", "except", "ValueError", "as", "e", ":", "log", ".", "info", "(", "'ValueError raised during conversion of parameter %s (%s): %s'", ",", "parameter", ".", "position", ",", "parameter", ".", "name", ",", "e", ")", "raise", "ConverterHttp404", "(", "value", ",", "parameter", ",", "'A parameter could not be converted - see the logs for more detail'", ")", "from", "e", "except", "Exception", "as", "e", ":", "log", ".", "info", "(", "'Exception raised during conversion of parameter %s (%s): %s'", ",", "parameter", ".", "position", ",", "parameter", ".", "name", ",", "e", ")", "raise", "ConverterException", "(", "value", ",", "parameter", ",", "'A parameter could not be converted - see the logs for more detail'", ")", "from", "e" ]
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 instance of django_mako_plus.ViewParameter that holds this parameter's name, type, position, etc. request: the current request object. "converter functions" register with this class using the @parameter_converter decorator. See converters.py for the built-in converters. This function goes through the list of registered converter functions, selects the most-specific one that matches the parameter.type, and calls it to convert the value. If the converter function raises a ValueError, it is caught and switched to an Http404 to tell the browser that the requested URL doesn't resolve to a page. Other useful exceptions that converter functions can raise are: Any extension of BaseRedirectException (RedirectException, InternalRedirectException, JavascriptRedirectException, ...) Http404: returns a Django Http404 response
[ "Converts", "a", "parameter", "value", "in", "the", "view", "function", "call", "." ]
train
https://github.com/doconix/django-mako-plus/blob/a90f9b4af19e5fa9f83452989cdcaed21569a181/django_mako_plus/converter/base.py#L137-L195
doconix/django-mako-plus
django_mako_plus/management/commands/dmp_webpack.py
Command.create_entry_file
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 until called DMP_CONTEXT.loadBundle({ %for (app, template), script_paths in script_map.items(): "${ app }/${ template }": () => [ %for path in script_paths: import(/* webpackMode: "eager" */ "./${ os.path.relpath(path, os.path.dirname(filename)) }"), %endfor ], %endfor }) ''') content = template.render( enapps=enapps, script_map=script_map, filename=filename, ).strip() # ensure the parent directories exist if not os.path.exists(os.path.dirname(filename)): os.makedirs(os.path.dirname(filename)) # if the file exists, then consider the options file_exists = os.path.exists(filename) if file_exists and self.running_inline: # running inline means that we're in debug mode and webpack is likely watching, so # we don't want to recreate the entry file (and cause webpack to constantly reload) # unless we have changes with open(filename, 'r') as fin: if content == fin.read(): return False if file_exists and not self.options.get('overwrite'): raise CommandError('Refusing to destroy existing file: {} (use --overwrite option or remove the file)'.format(filename)) # if we get here, write the file self.message('Creating {}'.format(os.path.relpath(filename, settings.BASE_DIR)), level=3) with open(filename, 'w') as fout: fout.write(content) return True
python
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 until called DMP_CONTEXT.loadBundle({ %for (app, template), script_paths in script_map.items(): "${ app }/${ template }": () => [ %for path in script_paths: import(/* webpackMode: "eager" */ "./${ os.path.relpath(path, os.path.dirname(filename)) }"), %endfor ], %endfor }) ''') content = template.render( enapps=enapps, script_map=script_map, filename=filename, ).strip() # ensure the parent directories exist if not os.path.exists(os.path.dirname(filename)): os.makedirs(os.path.dirname(filename)) # if the file exists, then consider the options file_exists = os.path.exists(filename) if file_exists and self.running_inline: # running inline means that we're in debug mode and webpack is likely watching, so # we don't want to recreate the entry file (and cause webpack to constantly reload) # unless we have changes with open(filename, 'r') as fin: if content == fin.read(): return False if file_exists and not self.options.get('overwrite'): raise CommandError('Refusing to destroy existing file: {} (use --overwrite option or remove the file)'.format(filename)) # if we get here, write the file self.message('Creating {}'.format(os.path.relpath(filename, settings.BASE_DIR)), level=3) with open(filename, 'w') as fout: fout.write(content) return True
[ "def", "create_entry_file", "(", "self", ",", "filename", ",", "script_map", ",", "enapps", ")", ":", "if", "len", "(", "script_map", ")", "==", "0", ":", "return", "# create the entry file", "template", "=", "MakoTemplate", "(", "'''\n<%! import os %>\n// dynamic imports are within functions so they don't happen until called\nDMP_CONTEXT.loadBundle({\n %for (app, template), script_paths in script_map.items():\n\n \"${ app }/${ template }\": () => [\n %for path in script_paths:\n import(/* webpackMode: \"eager\" */ \"./${ os.path.relpath(path, os.path.dirname(filename)) }\"),\n %endfor\n ],\n %endfor\n\n})\n'''", ")", "content", "=", "template", ".", "render", "(", "enapps", "=", "enapps", ",", "script_map", "=", "script_map", ",", "filename", "=", "filename", ",", ")", ".", "strip", "(", ")", "# ensure the parent directories exist", "if", "not", "os", ".", "path", ".", "exists", "(", "os", ".", "path", ".", "dirname", "(", "filename", ")", ")", ":", "os", ".", "makedirs", "(", "os", ".", "path", ".", "dirname", "(", "filename", ")", ")", "# if the file exists, then consider the options", "file_exists", "=", "os", ".", "path", ".", "exists", "(", "filename", ")", "if", "file_exists", "and", "self", ".", "running_inline", ":", "# running inline means that we're in debug mode and webpack is likely watching, so", "# we don't want to recreate the entry file (and cause webpack to constantly reload)", "# unless we have changes", "with", "open", "(", "filename", ",", "'r'", ")", "as", "fin", ":", "if", "content", "==", "fin", ".", "read", "(", ")", ":", "return", "False", "if", "file_exists", "and", "not", "self", ".", "options", ".", "get", "(", "'overwrite'", ")", ":", "raise", "CommandError", "(", "'Refusing to destroy existing file: {} (use --overwrite option or remove the file)'", ".", "format", "(", "filename", ")", ")", "# if we get here, write the file", "self", ".", "message", "(", "'Creating {}'", ".", "format", "(", "os", ".", "path", ".", "relpath", "(", "filename", ",", "settings", ".", "BASE_DIR", ")", ")", ",", "level", "=", "3", ")", "with", "open", "(", "filename", ",", "'w'", ")", "as", "fout", ":", "fout", ".", "write", "(", "content", ")", "return", "True" ]
Creates an entry file for the given script map
[ "Creates", "an", "entry", "file", "for", "the", "given", "script", "map" ]
train
https://github.com/doconix/django-mako-plus/blob/a90f9b4af19e5fa9f83452989cdcaed21569a181/django_mako_plus/management/commands/dmp_webpack.py#L89-L136
doconix/django-mako-plus
django_mako_plus/management/commands/dmp_webpack.py
Command.generate_script_map
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/scripts/template1.js', '/abs/path/to/scripts/supertemplate1.js' ], ( 'appname', 'template2' ): [ '/abs/path/to/scripts/template2.js', '/abs/path/to/scripts/supertemplate2.js', '/abs/path/to/scripts/supersuper2.js' ], ... } Any files or subdirectories starting with double-underscores (e.g. __dmpcache__) are skipped. ''' script_map = OrderedDict() template_root = os.path.join(os.path.relpath(config.path, settings.BASE_DIR), 'templates') def recurse(folder): subdirs = [] if os.path.exists(folder): for filename in os.listdir(folder): if filename.startswith('__'): continue filerel = os.path.join(folder, filename) if os.path.isdir(filerel): subdirs.append(filerel) elif os.path.isfile(filerel): template_name = os.path.relpath(filerel, template_root) scripts = self.template_scripts(config, template_name) key = ( config.name, os.path.splitext(template_name)[0] ) self.message('Found template: {}; static files: {}'.format(key, scripts), level=3) script_map[key] = scripts for subdir in subdirs: recurse(subdir) recurse(template_root) return script_map
python
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/scripts/template1.js', '/abs/path/to/scripts/supertemplate1.js' ], ( 'appname', 'template2' ): [ '/abs/path/to/scripts/template2.js', '/abs/path/to/scripts/supertemplate2.js', '/abs/path/to/scripts/supersuper2.js' ], ... } Any files or subdirectories starting with double-underscores (e.g. __dmpcache__) are skipped. ''' script_map = OrderedDict() template_root = os.path.join(os.path.relpath(config.path, settings.BASE_DIR), 'templates') def recurse(folder): subdirs = [] if os.path.exists(folder): for filename in os.listdir(folder): if filename.startswith('__'): continue filerel = os.path.join(folder, filename) if os.path.isdir(filerel): subdirs.append(filerel) elif os.path.isfile(filerel): template_name = os.path.relpath(filerel, template_root) scripts = self.template_scripts(config, template_name) key = ( config.name, os.path.splitext(template_name)[0] ) self.message('Found template: {}; static files: {}'.format(key, scripts), level=3) script_map[key] = scripts for subdir in subdirs: recurse(subdir) recurse(template_root) return script_map
[ "def", "generate_script_map", "(", "self", ",", "config", ")", ":", "script_map", "=", "OrderedDict", "(", ")", "template_root", "=", "os", ".", "path", ".", "join", "(", "os", ".", "path", ".", "relpath", "(", "config", ".", "path", ",", "settings", ".", "BASE_DIR", ")", ",", "'templates'", ")", "def", "recurse", "(", "folder", ")", ":", "subdirs", "=", "[", "]", "if", "os", ".", "path", ".", "exists", "(", "folder", ")", ":", "for", "filename", "in", "os", ".", "listdir", "(", "folder", ")", ":", "if", "filename", ".", "startswith", "(", "'__'", ")", ":", "continue", "filerel", "=", "os", ".", "path", ".", "join", "(", "folder", ",", "filename", ")", "if", "os", ".", "path", ".", "isdir", "(", "filerel", ")", ":", "subdirs", ".", "append", "(", "filerel", ")", "elif", "os", ".", "path", ".", "isfile", "(", "filerel", ")", ":", "template_name", "=", "os", ".", "path", ".", "relpath", "(", "filerel", ",", "template_root", ")", "scripts", "=", "self", ".", "template_scripts", "(", "config", ",", "template_name", ")", "key", "=", "(", "config", ".", "name", ",", "os", ".", "path", ".", "splitext", "(", "template_name", ")", "[", "0", "]", ")", "self", ".", "message", "(", "'Found template: {}; static files: {}'", ".", "format", "(", "key", ",", "scripts", ")", ",", "level", "=", "3", ")", "script_map", "[", "key", "]", "=", "scripts", "for", "subdir", "in", "subdirs", ":", "recurse", "(", "subdir", ")", "recurse", "(", "template_root", ")", "return", "script_map" ]
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/scripts/template1.js', '/abs/path/to/scripts/supertemplate1.js' ], ( 'appname', 'template2' ): [ '/abs/path/to/scripts/template2.js', '/abs/path/to/scripts/supertemplate2.js', '/abs/path/to/scripts/supersuper2.js' ], ... } Any files or subdirectories starting with double-underscores (e.g. __dmpcache__) are skipped.
[ "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", ":" ]
train
https://github.com/doconix/django-mako-plus/blob/a90f9b4af19e5fa9f83452989cdcaed21569a181/django_mako_plus/management/commands/dmp_webpack.py#L138-L175
doconix/django-mako-plus
django_mako_plus/management/commands/dmp_webpack.py
Command.template_scripts
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. ''' dmp = apps.get_app_config('django_mako_plus') template_obj = dmp.engine.get_template_loader(config, create=True).get_mako_template(template_name, force=True) mako_context = create_mako_context(template_obj) inner_run = WebpackProviderRun(mako_context['self']) inner_run.run() scripts = [] for tpl in inner_run.templates: for p in tpl.providers: if os.path.exists(p.absfilepath): scripts.append(p.absfilepath) return scripts
python
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. ''' dmp = apps.get_app_config('django_mako_plus') template_obj = dmp.engine.get_template_loader(config, create=True).get_mako_template(template_name, force=True) mako_context = create_mako_context(template_obj) inner_run = WebpackProviderRun(mako_context['self']) inner_run.run() scripts = [] for tpl in inner_run.templates: for p in tpl.providers: if os.path.exists(p.absfilepath): scripts.append(p.absfilepath) return scripts
[ "def", "template_scripts", "(", "self", ",", "config", ",", "template_name", ")", ":", "dmp", "=", "apps", ".", "get_app_config", "(", "'django_mako_plus'", ")", "template_obj", "=", "dmp", ".", "engine", ".", "get_template_loader", "(", "config", ",", "create", "=", "True", ")", ".", "get_mako_template", "(", "template_name", ",", "force", "=", "True", ")", "mako_context", "=", "create_mako_context", "(", "template_obj", ")", "inner_run", "=", "WebpackProviderRun", "(", "mako_context", "[", "'self'", "]", ")", "inner_run", ".", "run", "(", ")", "scripts", "=", "[", "]", "for", "tpl", "in", "inner_run", ".", "templates", ":", "for", "p", "in", "tpl", ".", "providers", ":", "if", "os", ".", "path", ".", "exists", "(", "p", ".", "absfilepath", ")", ":", "scripts", ".", "append", "(", "p", ".", "absfilepath", ")", "return", "scripts" ]
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", "a", "list", "of", "scripts", "used", "by", "the", "given", "template", "object", "AND", "its", "ancestors", "." ]
train
https://github.com/doconix/django-mako-plus/blob/a90f9b4af19e5fa9f83452989cdcaed21569a181/django_mako_plus/management/commands/dmp_webpack.py#L178-L195
doconix/django-mako-plus
django_mako_plus/exceptions.py
RedirectException.get_response
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
python
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
[ "def", "get_response", "(", "self", ",", "request", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "# normal process", "response", "=", "HttpResponseRedirect", "(", "self", ".", "redirect_to", ")", "response", "[", "REDIRECT_HEADER_KEY", "]", "=", "self", ".", "redirect_to", "return", "response" ]
Returns the redirect response for this exception.
[ "Returns", "the", "redirect", "response", "for", "this", "exception", "." ]
train
https://github.com/doconix/django-mako-plus/blob/a90f9b4af19e5fa9f83452989cdcaed21569a181/django_mako_plus/exceptions.py#L54-L59
doconix/django-mako-plus
django_mako_plus/exceptions.py
JavascriptRedirectException.get_response
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)
python
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)
[ "def", "get_response", "(", "self", ",", "request", ")", ":", "# the redirect key is already placed in the response by HttpResponseJavascriptRedirect", "return", "HttpResponseJavascriptRedirect", "(", "self", ".", "redirect_to", ",", "*", "self", ".", "args", ",", "*", "*", "self", ".", "kwargs", ")" ]
Returns the redirect response for this exception.
[ "Returns", "the", "redirect", "response", "for", "this", "exception", "." ]
train
https://github.com/doconix/django-mako-plus/blob/a90f9b4af19e5fa9f83452989cdcaed21569a181/django_mako_plus/exceptions.py#L114-L117
doconix/django-mako-plus
django_mako_plus/convenience.py
get_template_loader
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)
python
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)
[ "def", "get_template_loader", "(", "app", ",", "subdir", "=", "'templates'", ")", ":", "dmp", "=", "apps", ".", "get_app_config", "(", "'django_mako_plus'", ")", "return", "dmp", ".", "engine", ".", "get_template_loader", "(", "app", ",", "subdir", ",", "create", "=", "True", ")" ]
Convenience method that calls get_template_loader() on the DMP template engine instance.
[ "Convenience", "method", "that", "calls", "get_template_loader", "()", "on", "the", "DMP", "template", "engine", "instance", "." ]
train
https://github.com/doconix/django-mako-plus/blob/a90f9b4af19e5fa9f83452989cdcaed21569a181/django_mako_plus/convenience.py#L9-L15
doconix/django-mako-plus
django_mako_plus/convenience.py
render_template
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)
python
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)
[ "def", "render_template", "(", "request", ",", "app", ",", "template_name", ",", "context", "=", "None", ",", "subdir", "=", "\"templates\"", ",", "def_name", "=", "None", ")", ":", "return", "get_template", "(", "app", ",", "template_name", ",", "subdir", ")", ".", "render", "(", "context", ",", "request", ",", "def_name", ")" ]
Convenience method that directly renders a template, given the app and template names.
[ "Convenience", "method", "that", "directly", "renders", "a", "template", "given", "the", "app", "and", "template", "names", "." ]
train
https://github.com/doconix/django-mako-plus/blob/a90f9b4af19e5fa9f83452989cdcaed21569a181/django_mako_plus/convenience.py#L27-L31
doconix/django-mako-plus
django_mako_plus/convenience.py
get_template_loader_for_path
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)
python
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)
[ "def", "get_template_loader_for_path", "(", "path", ",", "use_cache", "=", "True", ")", ":", "dmp", "=", "apps", ".", "get_app_config", "(", "'django_mako_plus'", ")", "return", "dmp", ".", "engine", ".", "get_template_loader_for_path", "(", "path", ",", "use_cache", ")" ]
Convenience method that calls get_template_loader_for_path() on the DMP template engine instance.
[ "Convenience", "method", "that", "calls", "get_template_loader_for_path", "()", "on", "the", "DMP", "template", "engine", "instance", "." ]
train
https://github.com/doconix/django-mako-plus/blob/a90f9b4af19e5fa9f83452989cdcaed21569a181/django_mako_plus/convenience.py#L34-L40
doconix/django-mako-plus
django_mako_plus/convenience.py
get_template_for_path
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_cache).get_template(template_name)
python
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_cache).get_template(template_name)
[ "def", "get_template_for_path", "(", "path", ",", "use_cache", "=", "True", ")", ":", "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_cache", ")", ".", "get_template", "(", "template_name", ")" ]
Convenience method that retrieves a template given a direct path to it.
[ "Convenience", "method", "that", "retrieves", "a", "template", "given", "a", "direct", "path", "to", "it", "." ]
train
https://github.com/doconix/django-mako-plus/blob/a90f9b4af19e5fa9f83452989cdcaed21569a181/django_mako_plus/convenience.py#L43-L49
doconix/django-mako-plus
django_mako_plus/convenience.py
render_template_for_path
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)
python
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)
[ "def", "render_template_for_path", "(", "request", ",", "path", ",", "context", "=", "None", ",", "use_cache", "=", "True", ",", "def_name", "=", "None", ")", ":", "return", "get_template_for_path", "(", "path", ",", "use_cache", ")", ".", "render", "(", "context", ",", "request", ",", "def_name", ")" ]
Convenience method that directly renders a template, given a direct path to it.
[ "Convenience", "method", "that", "directly", "renders", "a", "template", "given", "a", "direct", "path", "to", "it", "." ]
train
https://github.com/doconix/django-mako-plus/blob/a90f9b4af19e5fa9f83452989cdcaed21569a181/django_mako_plus/convenience.py#L52-L56
doconix/django-mako-plus
django_mako_plus/util/reflect.py
qualified_name
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.__qualname__)
python
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.__qualname__)
[ "def", "qualified_name", "(", "obj", ")", ":", "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", ".", "__qualname__", ")" ]
Returns the fully-qualified name of the given object
[ "Returns", "the", "fully", "-", "qualified", "name", "of", "the", "given", "object" ]
train
https://github.com/doconix/django-mako-plus/blob/a90f9b4af19e5fa9f83452989cdcaed21569a181/django_mako_plus/util/reflect.py#L4-L11
doconix/django-mako-plus
django_mako_plus/util/reflect.py
import_qualified
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: {}'.format(name)) try: return getattr(import_module(parts[0]), parts[1]) except AttributeError: raise ImportError('{} not found in module {}'.format(parts[1], parts[0]))
python
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: {}'.format(name)) try: return getattr(import_module(parts[0]), parts[1]) except AttributeError: raise ImportError('{} not found in module {}'.format(parts[1], parts[0]))
[ "def", "import_qualified", "(", "name", ")", ":", "parts", "=", "name", ".", "rsplit", "(", "'.'", ",", "1", ")", "if", "len", "(", "parts", ")", "!=", "2", ":", "raise", "ImportError", "(", "'Invalid fully-qualified name: {}'", ".", "format", "(", "name", ")", ")", "try", ":", "return", "getattr", "(", "import_module", "(", "parts", "[", "0", "]", ")", ",", "parts", "[", "1", "]", ")", "except", "AttributeError", ":", "raise", "ImportError", "(", "'{} not found in module {}'", ".", "format", "(", "parts", "[", "1", "]", ",", "parts", "[", "0", "]", ")", ")" ]
Imports a fully-qualified name from a module: cls = import_qualified('homepage.views.index.MyForm') Raises an ImportError if it can't be ipmorted.
[ "Imports", "a", "fully", "-", "qualified", "name", "from", "a", "module", ":" ]
train
https://github.com/doconix/django-mako-plus/blob/a90f9b4af19e5fa9f83452989cdcaed21569a181/django_mako_plus/util/reflect.py#L14-L28
doconix/django-mako-plus
django_mako_plus/provider/__init__.py
links
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())
python
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())
[ "def", "links", "(", "tself", ",", "group", "=", "None", ")", ":", "pr", "=", "ProviderRun", "(", "tself", ",", "group", ")", "pr", ".", "run", "(", ")", "return", "mark_safe", "(", "pr", ".", "getvalue", "(", ")", ")" ]
Returns the HTML for the given provider group (or all groups if None)
[ "Returns", "the", "HTML", "for", "the", "given", "provider", "group", "(", "or", "all", "groups", "if", "None", ")" ]
train
https://github.com/doconix/django-mako-plus/blob/a90f9b4af19e5fa9f83452989cdcaed21569a181/django_mako_plus/provider/__init__.py#L12-L16
doconix/django-mako-plus
django_mako_plus/provider/__init__.py
template_links
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 python code instead of from within a rendering template environment. ''' if isinstance(app, str): app = apps.get_app_config(app) if context is None: context = {} dmp = apps.get_app_config('django_mako_plus') template_obj = dmp.engine.get_template_loader(app, create=True).get_mako_template(template_name, force=force) return template_obj_links(request, template_obj, context, group)
python
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 python code instead of from within a rendering template environment. ''' if isinstance(app, str): app = apps.get_app_config(app) if context is None: context = {} dmp = apps.get_app_config('django_mako_plus') template_obj = dmp.engine.get_template_loader(app, create=True).get_mako_template(template_name, force=force) return template_obj_links(request, template_obj, context, group)
[ "def", "template_links", "(", "request", ",", "app", ",", "template_name", ",", "context", "=", "None", ",", "group", "=", "None", ",", "force", "=", "True", ")", ":", "if", "isinstance", "(", "app", ",", "str", ")", ":", "app", "=", "apps", ".", "get_app_config", "(", "app", ")", "if", "context", "is", "None", ":", "context", "=", "{", "}", "dmp", "=", "apps", ".", "get_app_config", "(", "'django_mako_plus'", ")", "template_obj", "=", "dmp", ".", "engine", ".", "get_template_loader", "(", "app", ",", "create", "=", "True", ")", ".", "get_mako_template", "(", "template_name", ",", "force", "=", "force", ")", "return", "template_obj_links", "(", "request", ",", "template_obj", ",", "context", ",", "group", ")" ]
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.
[ "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", "." ]
train
https://github.com/doconix/django-mako-plus/blob/a90f9b4af19e5fa9f83452989cdcaed21569a181/django_mako_plus/provider/__init__.py#L19-L32
doconix/django-mako-plus
django_mako_plus/provider/__init__.py
template_obj_links
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 of from within a rendering template environment. ''' # the template_obj can be a MakoTemplateAdapter or a Mako Template # if our DMP-defined MakoTemplateAdapter, switch to the embedded Mako Template template_obj = getattr(template_obj, 'mako_template', template_obj) # create a mako context so it seems like we are inside a render context_dict = { 'request': request, } if isinstance(context, Context): for d in context: context_dict.update(d) elif context is not None: context_dict.update(context) mako_context = create_mako_context(template_obj, **context_dict) return links(mako_context['self'], group=group)
python
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 of from within a rendering template environment. ''' # the template_obj can be a MakoTemplateAdapter or a Mako Template # if our DMP-defined MakoTemplateAdapter, switch to the embedded Mako Template template_obj = getattr(template_obj, 'mako_template', template_obj) # create a mako context so it seems like we are inside a render context_dict = { 'request': request, } if isinstance(context, Context): for d in context: context_dict.update(d) elif context is not None: context_dict.update(context) mako_context = create_mako_context(template_obj, **context_dict) return links(mako_context['self'], group=group)
[ "def", "template_obj_links", "(", "request", ",", "template_obj", ",", "context", "=", "None", ",", "group", "=", "None", ")", ":", "# the template_obj can be a MakoTemplateAdapter or a Mako Template", "# if our DMP-defined MakoTemplateAdapter, switch to the embedded Mako Template", "template_obj", "=", "getattr", "(", "template_obj", ",", "'mako_template'", ",", "template_obj", ")", "# create a mako context so it seems like we are inside a render", "context_dict", "=", "{", "'request'", ":", "request", ",", "}", "if", "isinstance", "(", "context", ",", "Context", ")", ":", "for", "d", "in", "context", ":", "context_dict", ".", "update", "(", "d", ")", "elif", "context", "is", "not", "None", ":", "context_dict", ".", "update", "(", "context", ")", "mako_context", "=", "create_mako_context", "(", "template_obj", ",", "*", "*", "context_dict", ")", "return", "links", "(", "mako_context", "[", "'self'", "]", ",", "group", "=", "group", ")" ]
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.
[ "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", "." ]
train
https://github.com/doconix/django-mako-plus/blob/a90f9b4af19e5fa9f83452989cdcaed21569a181/django_mako_plus/provider/__init__.py#L35-L55
doconix/django-mako-plus
django_mako_plus/provider/link.py
CssLinkProvider.build_default_link
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, ) attrs.update(self.options['link_attrs']) attrs["data-context"] = self.provider_run.uid # can't be overridden return '<link{} />'.format(flatatt(attrs))
python
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, ) attrs.update(self.options['link_attrs']) attrs["data-context"] = self.provider_run.uid # can't be overridden return '<link{} />'.format(flatatt(attrs))
[ "def", "build_default_link", "(", "self", ")", ":", "attrs", "=", "{", "}", "attrs", "[", "\"rel\"", "]", "=", "\"stylesheet\"", "attrs", "[", "\"href\"", "]", "=", "\"{}?{:x}\"", ".", "format", "(", "os", ".", "path", ".", "join", "(", "settings", ".", "STATIC_URL", ",", "self", ".", "filepath", ")", ".", "replace", "(", "os", ".", "path", ".", "sep", ",", "'/'", ")", ",", "self", ".", "version_id", ",", ")", "attrs", ".", "update", "(", "self", ".", "options", "[", "'link_attrs'", "]", ")", "attrs", "[", "\"data-context\"", "]", "=", "self", ".", "provider_run", ".", "uid", "# can't be overridden", "return", "'<link{} />'", ".", "format", "(", "flatatt", "(", "attrs", ")", ")" ]
Called when 'link' is not defined in the settings
[ "Called", "when", "link", "is", "not", "defined", "in", "the", "settings" ]
train
https://github.com/doconix/django-mako-plus/blob/a90f9b4af19e5fa9f83452989cdcaed21569a181/django_mako_plus/provider/link.py#L155-L165
doconix/django-mako-plus
django_mako_plus/provider/link.py
JsLinkProvider.build_default_filepath
def build_default_filepath(self): '''Called when 'filepath' is not defined in the settings''' return os.path.join( self.app_config.name, 'scripts', self.template_relpath + '.js', )
python
def build_default_filepath(self): '''Called when 'filepath' is not defined in the settings''' return os.path.join( self.app_config.name, 'scripts', self.template_relpath + '.js', )
[ "def", "build_default_filepath", "(", "self", ")", ":", "return", "os", ".", "path", ".", "join", "(", "self", ".", "app_config", ".", "name", ",", "'scripts'", ",", "self", ".", "template_relpath", "+", "'.js'", ",", ")" ]
Called when 'filepath' is not defined in the settings
[ "Called", "when", "filepath", "is", "not", "defined", "in", "the", "settings" ]
train
https://github.com/doconix/django-mako-plus/blob/a90f9b4af19e5fa9f83452989cdcaed21569a181/django_mako_plus/provider/link.py#L180-L186
doconix/django-mako-plus
django_mako_plus/tags.py
django_include
def django_include(context, template_name, **kwargs): ''' Mako tag to include a Django template withing the current DMP (Mako) template. Since this is a Django template, it is search for using the Django search algorithm (instead of the DMP app-based concept). See https://docs.djangoproject.com/en/2.1/topics/templates/. The current context is sent to the included template, which makes all context variables available to the Django template. Any additional kwargs are added to the context. ''' try: djengine = engines['django'] except KeyError as e: raise TemplateDoesNotExist("Django template engine not configured in settings, so template cannot be found: {}".format(template_name)) from e djtemplate = djengine.get_template(template_name) djcontext = {} djcontext.update(context) djcontext.update(kwargs) return djtemplate.render(djcontext, context['request'])
python
def django_include(context, template_name, **kwargs): ''' Mako tag to include a Django template withing the current DMP (Mako) template. Since this is a Django template, it is search for using the Django search algorithm (instead of the DMP app-based concept). See https://docs.djangoproject.com/en/2.1/topics/templates/. The current context is sent to the included template, which makes all context variables available to the Django template. Any additional kwargs are added to the context. ''' try: djengine = engines['django'] except KeyError as e: raise TemplateDoesNotExist("Django template engine not configured in settings, so template cannot be found: {}".format(template_name)) from e djtemplate = djengine.get_template(template_name) djcontext = {} djcontext.update(context) djcontext.update(kwargs) return djtemplate.render(djcontext, context['request'])
[ "def", "django_include", "(", "context", ",", "template_name", ",", "*", "*", "kwargs", ")", ":", "try", ":", "djengine", "=", "engines", "[", "'django'", "]", "except", "KeyError", "as", "e", ":", "raise", "TemplateDoesNotExist", "(", "\"Django template engine not configured in settings, so template cannot be found: {}\"", ".", "format", "(", "template_name", ")", ")", "from", "e", "djtemplate", "=", "djengine", ".", "get_template", "(", "template_name", ")", "djcontext", "=", "{", "}", "djcontext", ".", "update", "(", "context", ")", "djcontext", ".", "update", "(", "kwargs", ")", "return", "djtemplate", ".", "render", "(", "djcontext", ",", "context", "[", "'request'", "]", ")" ]
Mako tag to include a Django template withing the current DMP (Mako) template. Since this is a Django template, it is search for using the Django search algorithm (instead of the DMP app-based concept). See https://docs.djangoproject.com/en/2.1/topics/templates/. The current context is sent to the included template, which makes all context variables available to the Django template. Any additional kwargs are added to the context.
[ "Mako", "tag", "to", "include", "a", "Django", "template", "withing", "the", "current", "DMP", "(", "Mako", ")", "template", ".", "Since", "this", "is", "a", "Django", "template", "it", "is", "search", "for", "using", "the", "Django", "search", "algorithm", "(", "instead", "of", "the", "DMP", "app", "-", "based", "concept", ")", ".", "See", "https", ":", "//", "docs", ".", "djangoproject", ".", "com", "/", "en", "/", "2", ".", "1", "/", "topics", "/", "templates", "/", "." ]
train
https://github.com/doconix/django-mako-plus/blob/a90f9b4af19e5fa9f83452989cdcaed21569a181/django_mako_plus/tags.py#L14-L33
doconix/django-mako-plus
django_mako_plus/tags.py
_toggle_autoescape
def _toggle_autoescape(context, escape_on=True): ''' Internal method to toggle autoescaping on or off. This function needs access to the caller, so the calling method must be decorated with @supports_caller. ''' previous = is_autoescape(context) setattr(context.caller_stack, AUTOESCAPE_KEY, escape_on) try: context['caller'].body() finally: setattr(context.caller_stack, AUTOESCAPE_KEY, previous)
python
def _toggle_autoescape(context, escape_on=True): ''' Internal method to toggle autoescaping on or off. This function needs access to the caller, so the calling method must be decorated with @supports_caller. ''' previous = is_autoescape(context) setattr(context.caller_stack, AUTOESCAPE_KEY, escape_on) try: context['caller'].body() finally: setattr(context.caller_stack, AUTOESCAPE_KEY, previous)
[ "def", "_toggle_autoescape", "(", "context", ",", "escape_on", "=", "True", ")", ":", "previous", "=", "is_autoescape", "(", "context", ")", "setattr", "(", "context", ".", "caller_stack", ",", "AUTOESCAPE_KEY", ",", "escape_on", ")", "try", ":", "context", "[", "'caller'", "]", ".", "body", "(", ")", "finally", ":", "setattr", "(", "context", ".", "caller_stack", ",", "AUTOESCAPE_KEY", ",", "previous", ")" ]
Internal method to toggle autoescaping on or off. This function needs access to the caller, so the calling method must be decorated with @supports_caller.
[ "Internal", "method", "to", "toggle", "autoescaping", "on", "or", "off", ".", "This", "function", "needs", "access", "to", "the", "caller", "so", "the", "calling", "method", "must", "be", "decorated", "with" ]
train
https://github.com/doconix/django-mako-plus/blob/a90f9b4af19e5fa9f83452989cdcaed21569a181/django_mako_plus/tags.py#L48-L59
doconix/django-mako-plus
django_mako_plus/management/commands/dmp_cleanup.py
pretty_relpath
def pretty_relpath(path, start): ''' Returns a relative path, but only if it doesn't start with a non-pretty parent directory ".." ''' relpath = os.path.relpath(path, start) if relpath.startswith('..'): return path return relpath
python
def pretty_relpath(path, start): ''' Returns a relative path, but only if it doesn't start with a non-pretty parent directory ".." ''' relpath = os.path.relpath(path, start) if relpath.startswith('..'): return path return relpath
[ "def", "pretty_relpath", "(", "path", ",", "start", ")", ":", "relpath", "=", "os", ".", "path", ".", "relpath", "(", "path", ",", "start", ")", "if", "relpath", ".", "startswith", "(", "'..'", ")", ":", "return", "path", "return", "relpath" ]
Returns a relative path, but only if it doesn't start with a non-pretty parent directory ".."
[ "Returns", "a", "relative", "path", "but", "only", "if", "it", "doesn", "t", "start", "with", "a", "non", "-", "pretty", "parent", "directory", ".." ]
train
https://github.com/doconix/django-mako-plus/blob/a90f9b4af19e5fa9f83452989cdcaed21569a181/django_mako_plus/management/commands/dmp_cleanup.py#L84-L91
doconix/django-mako-plus
django_mako_plus/router/decorators.py
view_function.is_decorated
def is_decorated(cls, f): '''Returns True if the given function is decorated with @view_function''' real_func = inspect.unwrap(f) return real_func in cls.DECORATED_FUNCTIONS
python
def is_decorated(cls, f): '''Returns True if the given function is decorated with @view_function''' real_func = inspect.unwrap(f) return real_func in cls.DECORATED_FUNCTIONS
[ "def", "is_decorated", "(", "cls", ",", "f", ")", ":", "real_func", "=", "inspect", ".", "unwrap", "(", "f", ")", "return", "real_func", "in", "cls", ".", "DECORATED_FUNCTIONS" ]
Returns True if the given function is decorated with @view_function
[ "Returns", "True", "if", "the", "given", "function", "is", "decorated", "with" ]
train
https://github.com/doconix/django-mako-plus/blob/a90f9b4af19e5fa9f83452989cdcaed21569a181/django_mako_plus/router/decorators.py#L56-L59
doconix/django-mako-plus
django_mako_plus/provider/runner.py
ProviderRun.initialize_providers
def initialize_providers(cls): '''Initializes the providers (called from dmp app ready())''' dmp = apps.get_app_config('django_mako_plus') # regular content providers cls.CONTENT_PROVIDERS = [] for provider_settings in dmp.options[cls.SETTINGS_KEY]: # import the class for this provider assert 'provider' in provider_settings, "Invalid entry in settings.py: CONTENT_PROVIDERS item must have 'provider' key" provider_cls = import_string(provider_settings['provider']) # combine options from all of its bases, then from settings.py options = {} for base in reversed(inspect.getmro(provider_cls)): options.update(getattr(base, 'DEFAULT_OPTIONS', {})) options.update(provider_settings) # add to the list if options['enabled']: pe = ProviderEntry(provider_cls, options) pe.options['template_cache_key'] = '_dmp_provider_{}_'.format(id(pe)) cls.CONTENT_PROVIDERS.append(pe)
python
def initialize_providers(cls): '''Initializes the providers (called from dmp app ready())''' dmp = apps.get_app_config('django_mako_plus') # regular content providers cls.CONTENT_PROVIDERS = [] for provider_settings in dmp.options[cls.SETTINGS_KEY]: # import the class for this provider assert 'provider' in provider_settings, "Invalid entry in settings.py: CONTENT_PROVIDERS item must have 'provider' key" provider_cls = import_string(provider_settings['provider']) # combine options from all of its bases, then from settings.py options = {} for base in reversed(inspect.getmro(provider_cls)): options.update(getattr(base, 'DEFAULT_OPTIONS', {})) options.update(provider_settings) # add to the list if options['enabled']: pe = ProviderEntry(provider_cls, options) pe.options['template_cache_key'] = '_dmp_provider_{}_'.format(id(pe)) cls.CONTENT_PROVIDERS.append(pe)
[ "def", "initialize_providers", "(", "cls", ")", ":", "dmp", "=", "apps", ".", "get_app_config", "(", "'django_mako_plus'", ")", "# regular content providers", "cls", ".", "CONTENT_PROVIDERS", "=", "[", "]", "for", "provider_settings", "in", "dmp", ".", "options", "[", "cls", ".", "SETTINGS_KEY", "]", ":", "# import the class for this provider", "assert", "'provider'", "in", "provider_settings", ",", "\"Invalid entry in settings.py: CONTENT_PROVIDERS item must have 'provider' key\"", "provider_cls", "=", "import_string", "(", "provider_settings", "[", "'provider'", "]", ")", "# combine options from all of its bases, then from settings.py", "options", "=", "{", "}", "for", "base", "in", "reversed", "(", "inspect", ".", "getmro", "(", "provider_cls", ")", ")", ":", "options", ".", "update", "(", "getattr", "(", "base", ",", "'DEFAULT_OPTIONS'", ",", "{", "}", ")", ")", "options", ".", "update", "(", "provider_settings", ")", "# add to the list", "if", "options", "[", "'enabled'", "]", ":", "pe", "=", "ProviderEntry", "(", "provider_cls", ",", "options", ")", "pe", ".", "options", "[", "'template_cache_key'", "]", "=", "'_dmp_provider_{}_'", ".", "format", "(", "id", "(", "pe", ")", ")", "cls", ".", "CONTENT_PROVIDERS", ".", "append", "(", "pe", ")" ]
Initializes the providers (called from dmp app ready())
[ "Initializes", "the", "providers", "(", "called", "from", "dmp", "app", "ready", "()", ")" ]
train
https://github.com/doconix/django-mako-plus/blob/a90f9b4af19e5fa9f83452989cdcaed21569a181/django_mako_plus/provider/runner.py#L34-L52
doconix/django-mako-plus
django_mako_plus/provider/runner.py
ProviderRun.run
def run(self): '''Performs the run through the templates and their providers''' for tpl in self.templates: for provider in tpl.providers: provider.provide()
python
def run(self): '''Performs the run through the templates and their providers''' for tpl in self.templates: for provider in tpl.providers: provider.provide()
[ "def", "run", "(", "self", ")", ":", "for", "tpl", "in", "self", ".", "templates", ":", "for", "provider", "in", "tpl", ".", "providers", ":", "provider", ".", "provide", "(", ")" ]
Performs the run through the templates and their providers
[ "Performs", "the", "run", "through", "the", "templates", "and", "their", "providers" ]
train
https://github.com/doconix/django-mako-plus/blob/a90f9b4af19e5fa9f83452989cdcaed21569a181/django_mako_plus/provider/runner.py#L87-L91
doconix/django-mako-plus
django_mako_plus/provider/runner.py
ProviderRun.write
def write(self, content): '''Provider instances use this to write to the buffer''' self.buffer.write(content) if settings.DEBUG: self.buffer.write('\n')
python
def write(self, content): '''Provider instances use this to write to the buffer''' self.buffer.write(content) if settings.DEBUG: self.buffer.write('\n')
[ "def", "write", "(", "self", ",", "content", ")", ":", "self", ".", "buffer", ".", "write", "(", "content", ")", "if", "settings", ".", "DEBUG", ":", "self", ".", "buffer", ".", "write", "(", "'\\n'", ")" ]
Provider instances use this to write to the buffer
[ "Provider", "instances", "use", "this", "to", "write", "to", "the", "buffer" ]
train
https://github.com/doconix/django-mako-plus/blob/a90f9b4af19e5fa9f83452989cdcaed21569a181/django_mako_plus/provider/runner.py#L93-L97
doconix/django-mako-plus
django_mako_plus/converter/info.py
ConverterFunctionInfo.prepare_sort_key
def prepare_sort_key(self): ''' Triggered by view_function._sort_converters when our sort key should be created. This can't be called in the constructor because Django models might not be ready yet. ''' if isinstance(self.convert_type, str): try: app_name, model_name = self.convert_type.split('.') except ValueError: raise ImproperlyConfigured('"{}" is not a valid converter type. String-based converter types must be specified in "app.Model" format.'.format(self.convert_type)) try: self.convert_type = apps.get_model(app_name, model_name) except LookupError as e: raise ImproperlyConfigured('"{}" is not a valid model name. {}'.format(self.convert_type, e)) # we reverse sort by ( len(mro), source code order ) so subclasses match first # on same types, last declared method sorts first self.sort_key = ( -1 * len(inspect.getmro(self.convert_type)), -1 * self.source_order )
python
def prepare_sort_key(self): ''' Triggered by view_function._sort_converters when our sort key should be created. This can't be called in the constructor because Django models might not be ready yet. ''' if isinstance(self.convert_type, str): try: app_name, model_name = self.convert_type.split('.') except ValueError: raise ImproperlyConfigured('"{}" is not a valid converter type. String-based converter types must be specified in "app.Model" format.'.format(self.convert_type)) try: self.convert_type = apps.get_model(app_name, model_name) except LookupError as e: raise ImproperlyConfigured('"{}" is not a valid model name. {}'.format(self.convert_type, e)) # we reverse sort by ( len(mro), source code order ) so subclasses match first # on same types, last declared method sorts first self.sort_key = ( -1 * len(inspect.getmro(self.convert_type)), -1 * self.source_order )
[ "def", "prepare_sort_key", "(", "self", ")", ":", "if", "isinstance", "(", "self", ".", "convert_type", ",", "str", ")", ":", "try", ":", "app_name", ",", "model_name", "=", "self", ".", "convert_type", ".", "split", "(", "'.'", ")", "except", "ValueError", ":", "raise", "ImproperlyConfigured", "(", "'\"{}\" is not a valid converter type. String-based converter types must be specified in \"app.Model\" format.'", ".", "format", "(", "self", ".", "convert_type", ")", ")", "try", ":", "self", ".", "convert_type", "=", "apps", ".", "get_model", "(", "app_name", ",", "model_name", ")", "except", "LookupError", "as", "e", ":", "raise", "ImproperlyConfigured", "(", "'\"{}\" is not a valid model name. {}'", ".", "format", "(", "self", ".", "convert_type", ",", "e", ")", ")", "# we reverse sort by ( len(mro), source code order ) so subclasses match first", "# on same types, last declared method sorts first", "self", ".", "sort_key", "=", "(", "-", "1", "*", "len", "(", "inspect", ".", "getmro", "(", "self", ".", "convert_type", ")", ")", ",", "-", "1", "*", "self", ".", "source_order", ")" ]
Triggered by view_function._sort_converters when our sort key should be created. This can't be called in the constructor because Django models might not be ready yet.
[ "Triggered", "by", "view_function", ".", "_sort_converters", "when", "our", "sort", "key", "should", "be", "created", ".", "This", "can", "t", "be", "called", "in", "the", "constructor", "because", "Django", "models", "might", "not", "be", "ready", "yet", "." ]
train
https://github.com/doconix/django-mako-plus/blob/a90f9b4af19e5fa9f83452989cdcaed21569a181/django_mako_plus/converter/info.py#L19-L36
doconix/django-mako-plus
django_mako_plus/provider/compile.py
CompileProvider.build_command
def build_command(self): '''Returns the command to run, as a list (see subprocess module)''' # if defined in settings, run the function or return the string if self.options['command']: return self.options['command'](self) if callable(self.options['command']) else self.options['command'] # build the default return self.build_default_command()
python
def build_command(self): '''Returns the command to run, as a list (see subprocess module)''' # if defined in settings, run the function or return the string if self.options['command']: return self.options['command'](self) if callable(self.options['command']) else self.options['command'] # build the default return self.build_default_command()
[ "def", "build_command", "(", "self", ")", ":", "# if defined in settings, run the function or return the string", "if", "self", ".", "options", "[", "'command'", "]", ":", "return", "self", ".", "options", "[", "'command'", "]", "(", "self", ")", "if", "callable", "(", "self", ".", "options", "[", "'command'", "]", ")", "else", "self", ".", "options", "[", "'command'", "]", "# build the default", "return", "self", ".", "build_default_command", "(", ")" ]
Returns the command to run, as a list (see subprocess module)
[ "Returns", "the", "command", "to", "run", "as", "a", "list", "(", "see", "subprocess", "module", ")" ]
train
https://github.com/doconix/django-mako-plus/blob/a90f9b4af19e5fa9f83452989cdcaed21569a181/django_mako_plus/provider/compile.py#L104-L110
doconix/django-mako-plus
django_mako_plus/provider/compile.py
CompileProvider.needs_compile
def needs_compile(self): '''Returns True if self.sourcepath is newer than self.targetpath''' try: source_mtime = os.stat(self.sourcepath).st_mtime except OSError: # no source for this template, so just return return False try: target_mtime = os.stat(self.targetpath).st_mtime except OSError: # target doesn't exist, so compile return True # both source and target exist, so compile if source newer return source_mtime > target_mtime
python
def needs_compile(self): '''Returns True if self.sourcepath is newer than self.targetpath''' try: source_mtime = os.stat(self.sourcepath).st_mtime except OSError: # no source for this template, so just return return False try: target_mtime = os.stat(self.targetpath).st_mtime except OSError: # target doesn't exist, so compile return True # both source and target exist, so compile if source newer return source_mtime > target_mtime
[ "def", "needs_compile", "(", "self", ")", ":", "try", ":", "source_mtime", "=", "os", ".", "stat", "(", "self", ".", "sourcepath", ")", ".", "st_mtime", "except", "OSError", ":", "# no source for this template, so just return", "return", "False", "try", ":", "target_mtime", "=", "os", ".", "stat", "(", "self", ".", "targetpath", ")", ".", "st_mtime", "except", "OSError", ":", "# target doesn't exist, so compile", "return", "True", "# both source and target exist, so compile if source newer", "return", "source_mtime", ">", "target_mtime" ]
Returns True if self.sourcepath is newer than self.targetpath
[ "Returns", "True", "if", "self", ".", "sourcepath", "is", "newer", "than", "self", ".", "targetpath" ]
train
https://github.com/doconix/django-mako-plus/blob/a90f9b4af19e5fa9f83452989cdcaed21569a181/django_mako_plus/provider/compile.py#L117-L128
doconix/django-mako-plus
django_mako_plus/template/util.py
template_inheritance
def template_inheritance(obj): ''' Generator that iterates the template and its ancestors. The order is from most specialized (furthest descendant) to most general (furthest ancestor). obj can be either: 1. Mako Template object 2. Mako `self` object (available within a rendering template) ''' if isinstance(obj, MakoTemplate): obj = create_mako_context(obj)['self'] elif isinstance(obj, MakoContext): obj = obj['self'] while obj is not None: yield obj.template obj = obj.inherits
python
def template_inheritance(obj): ''' Generator that iterates the template and its ancestors. The order is from most specialized (furthest descendant) to most general (furthest ancestor). obj can be either: 1. Mako Template object 2. Mako `self` object (available within a rendering template) ''' if isinstance(obj, MakoTemplate): obj = create_mako_context(obj)['self'] elif isinstance(obj, MakoContext): obj = obj['self'] while obj is not None: yield obj.template obj = obj.inherits
[ "def", "template_inheritance", "(", "obj", ")", ":", "if", "isinstance", "(", "obj", ",", "MakoTemplate", ")", ":", "obj", "=", "create_mako_context", "(", "obj", ")", "[", "'self'", "]", "elif", "isinstance", "(", "obj", ",", "MakoContext", ")", ":", "obj", "=", "obj", "[", "'self'", "]", "while", "obj", "is", "not", "None", ":", "yield", "obj", ".", "template", "obj", "=", "obj", ".", "inherits" ]
Generator that iterates the template and its ancestors. The order is from most specialized (furthest descendant) to most general (furthest ancestor). obj can be either: 1. Mako Template object 2. Mako `self` object (available within a rendering template)
[ "Generator", "that", "iterates", "the", "template", "and", "its", "ancestors", ".", "The", "order", "is", "from", "most", "specialized", "(", "furthest", "descendant", ")", "to", "most", "general", "(", "furthest", "ancestor", ")", "." ]
train
https://github.com/doconix/django-mako-plus/blob/a90f9b4af19e5fa9f83452989cdcaed21569a181/django_mako_plus/template/util.py#L11-L27
doconix/django-mako-plus
django_mako_plus/template/util.py
get_template_debug
def get_template_debug(template_name, error): ''' This structure is what Django wants when errors occur in templates. It gives the user a nice stack trace in the error page during debug. ''' # This is taken from mako.exceptions.html_error_template(), which has an issue # in Py3 where files get loaded as bytes but `lines = src.split('\n')` below # splits with a string. Not sure if this is a bug or if I'm missing something, # but doing a custom debugging template allows a workaround as well as a custom # DMP look. # I used to have a file in the templates directory for this, but too many users # reported TemplateNotFound errors. This function is a bit of a hack, but it only # happens during development (and mako.exceptions does this same thing). # /justification stacktrace_template = MakoTemplate(r""" <%! from mako.exceptions import syntax_highlight, pygments_html_formatter %> <style> .stacktrace { margin:5px 5px 5px 5px; } .highlight { padding:0px 10px 0px 10px; background-color:#9F9FDF; } .nonhighlight { padding:0px; background-color:#DFDFDF; } .sample { padding:10px; margin:10px 10px 10px 10px; font-family:monospace; } .sampleline { padding:0px 10px 0px 10px; } .sourceline { margin:5px 5px 10px 5px; font-family:monospace;} .location { font-size:80%; } .highlight { white-space:pre; } .sampleline { white-space:pre; } % if pygments_html_formatter: ${pygments_html_formatter.get_style_defs() | n} .linenos { min-width: 2.5em; text-align: right; } pre { margin: 0; } .syntax-highlighted { padding: 0 10px; } .syntax-highlightedtable { border-spacing: 1px; } .nonhighlight { border-top: 1px solid #DFDFDF; border-bottom: 1px solid #DFDFDF; } .stacktrace .nonhighlight { margin: 5px 15px 10px; } .sourceline { margin: 0 0; font-family:monospace; } .code { background-color: #F8F8F8; width: 100%; } .error .code { background-color: #FFBDBD; } .error .syntax-highlighted { background-color: #FFBDBD; } % endif ## adjustments to Django css table.source { background-color: #fdfdfd; } table.source > tbody > tr > th { width: auto; } table.source > tbody > tr > td { font-family: inherit; white-space: normal; padding: 15px; } #template { background-color: #b3daff; } </style> <% src = tback.source line = tback.lineno if isinstance(src, bytes): src = src.decode() if src: lines = src.split('\n') else: lines = None %> <h3>${tback.errorname}: ${tback.message}</h3> % if lines: <div class="sample"> <div class="nonhighlight"> % for index in range(max(0, line-4),min(len(lines), line+5)): <% if pygments_html_formatter: pygments_html_formatter.linenostart = index + 1 %> % if index + 1 == line: <% if pygments_html_formatter: old_cssclass = pygments_html_formatter.cssclass pygments_html_formatter.cssclass = 'error ' + old_cssclass %> ${lines[index] | n,syntax_highlight(language='mako')} <% if pygments_html_formatter: pygments_html_formatter.cssclass = old_cssclass %> % else: ${lines[index] | n,syntax_highlight(language='mako')} % endif % endfor </div> </div> % endif <div class="stacktrace"> % for (filename, lineno, function, line) in tback.reverse_traceback: <div class="location">${filename}, line ${lineno}:</div> <div class="nonhighlight"> <% if pygments_html_formatter: pygments_html_formatter.linenostart = lineno %> <div class="sourceline">${line | n,syntax_highlight(filename)}</div> </div> % endfor </div> """) tback = RichTraceback(error, error.__traceback__) lines = stacktrace_template.render_unicode(tback=tback) return { 'message': '', 'source_lines': [ ( '', mark_safe(lines) ), ], 'before': '', 'during': '', 'after': '', 'top': 0, 'bottom': 0, 'total': 0, 'line': tback.lineno or 0, 'name': template_name, 'start': 0, 'end': 0, }
python
def get_template_debug(template_name, error): ''' This structure is what Django wants when errors occur in templates. It gives the user a nice stack trace in the error page during debug. ''' # This is taken from mako.exceptions.html_error_template(), which has an issue # in Py3 where files get loaded as bytes but `lines = src.split('\n')` below # splits with a string. Not sure if this is a bug or if I'm missing something, # but doing a custom debugging template allows a workaround as well as a custom # DMP look. # I used to have a file in the templates directory for this, but too many users # reported TemplateNotFound errors. This function is a bit of a hack, but it only # happens during development (and mako.exceptions does this same thing). # /justification stacktrace_template = MakoTemplate(r""" <%! from mako.exceptions import syntax_highlight, pygments_html_formatter %> <style> .stacktrace { margin:5px 5px 5px 5px; } .highlight { padding:0px 10px 0px 10px; background-color:#9F9FDF; } .nonhighlight { padding:0px; background-color:#DFDFDF; } .sample { padding:10px; margin:10px 10px 10px 10px; font-family:monospace; } .sampleline { padding:0px 10px 0px 10px; } .sourceline { margin:5px 5px 10px 5px; font-family:monospace;} .location { font-size:80%; } .highlight { white-space:pre; } .sampleline { white-space:pre; } % if pygments_html_formatter: ${pygments_html_formatter.get_style_defs() | n} .linenos { min-width: 2.5em; text-align: right; } pre { margin: 0; } .syntax-highlighted { padding: 0 10px; } .syntax-highlightedtable { border-spacing: 1px; } .nonhighlight { border-top: 1px solid #DFDFDF; border-bottom: 1px solid #DFDFDF; } .stacktrace .nonhighlight { margin: 5px 15px 10px; } .sourceline { margin: 0 0; font-family:monospace; } .code { background-color: #F8F8F8; width: 100%; } .error .code { background-color: #FFBDBD; } .error .syntax-highlighted { background-color: #FFBDBD; } % endif ## adjustments to Django css table.source { background-color: #fdfdfd; } table.source > tbody > tr > th { width: auto; } table.source > tbody > tr > td { font-family: inherit; white-space: normal; padding: 15px; } #template { background-color: #b3daff; } </style> <% src = tback.source line = tback.lineno if isinstance(src, bytes): src = src.decode() if src: lines = src.split('\n') else: lines = None %> <h3>${tback.errorname}: ${tback.message}</h3> % if lines: <div class="sample"> <div class="nonhighlight"> % for index in range(max(0, line-4),min(len(lines), line+5)): <% if pygments_html_formatter: pygments_html_formatter.linenostart = index + 1 %> % if index + 1 == line: <% if pygments_html_formatter: old_cssclass = pygments_html_formatter.cssclass pygments_html_formatter.cssclass = 'error ' + old_cssclass %> ${lines[index] | n,syntax_highlight(language='mako')} <% if pygments_html_formatter: pygments_html_formatter.cssclass = old_cssclass %> % else: ${lines[index] | n,syntax_highlight(language='mako')} % endif % endfor </div> </div> % endif <div class="stacktrace"> % for (filename, lineno, function, line) in tback.reverse_traceback: <div class="location">${filename}, line ${lineno}:</div> <div class="nonhighlight"> <% if pygments_html_formatter: pygments_html_formatter.linenostart = lineno %> <div class="sourceline">${line | n,syntax_highlight(filename)}</div> </div> % endfor </div> """) tback = RichTraceback(error, error.__traceback__) lines = stacktrace_template.render_unicode(tback=tback) return { 'message': '', 'source_lines': [ ( '', mark_safe(lines) ), ], 'before': '', 'during': '', 'after': '', 'top': 0, 'bottom': 0, 'total': 0, 'line': tback.lineno or 0, 'name': template_name, 'start': 0, 'end': 0, }
[ "def", "get_template_debug", "(", "template_name", ",", "error", ")", ":", "# This is taken from mako.exceptions.html_error_template(), which has an issue", "# in Py3 where files get loaded as bytes but `lines = src.split('\\n')` below", "# splits with a string. Not sure if this is a bug or if I'm missing something,", "# but doing a custom debugging template allows a workaround as well as a custom", "# DMP look.", "# I used to have a file in the templates directory for this, but too many users", "# reported TemplateNotFound errors. This function is a bit of a hack, but it only", "# happens during development (and mako.exceptions does this same thing).", "# /justification", "stacktrace_template", "=", "MakoTemplate", "(", "r\"\"\"\n<%! from mako.exceptions import syntax_highlight, pygments_html_formatter %>\n<style>\n .stacktrace { margin:5px 5px 5px 5px; }\n .highlight { padding:0px 10px 0px 10px; background-color:#9F9FDF; }\n .nonhighlight { padding:0px; background-color:#DFDFDF; }\n .sample { padding:10px; margin:10px 10px 10px 10px;\n font-family:monospace; }\n .sampleline { padding:0px 10px 0px 10px; }\n .sourceline { margin:5px 5px 10px 5px; font-family:monospace;}\n .location { font-size:80%; }\n .highlight { white-space:pre; }\n .sampleline { white-space:pre; }\n\n % if pygments_html_formatter:\n ${pygments_html_formatter.get_style_defs() | n}\n .linenos { min-width: 2.5em; text-align: right; }\n pre { margin: 0; }\n .syntax-highlighted { padding: 0 10px; }\n .syntax-highlightedtable { border-spacing: 1px; }\n .nonhighlight { border-top: 1px solid #DFDFDF;\n border-bottom: 1px solid #DFDFDF; }\n .stacktrace .nonhighlight { margin: 5px 15px 10px; }\n .sourceline { margin: 0 0; font-family:monospace; }\n .code { background-color: #F8F8F8; width: 100%; }\n .error .code { background-color: #FFBDBD; }\n .error .syntax-highlighted { background-color: #FFBDBD; }\n % endif\n\n ## adjustments to Django css\n table.source {\n background-color: #fdfdfd;\n }\n table.source > tbody > tr > th {\n width: auto;\n }\n table.source > tbody > tr > td {\n font-family: inherit;\n white-space: normal;\n padding: 15px;\n }\n #template {\n background-color: #b3daff;\n }\n\n</style>\n<%\n\n src = tback.source\n line = tback.lineno\n if isinstance(src, bytes):\n src = src.decode()\n if src:\n lines = src.split('\\n')\n else:\n lines = None\n%>\n<h3>${tback.errorname}: ${tback.message}</h3>\n\n% if lines:\n <div class=\"sample\">\n <div class=\"nonhighlight\">\n % for index in range(max(0, line-4),min(len(lines), line+5)):\n <%\n if pygments_html_formatter:\n pygments_html_formatter.linenostart = index + 1\n %>\n % if index + 1 == line:\n <%\n if pygments_html_formatter:\n old_cssclass = pygments_html_formatter.cssclass\n pygments_html_formatter.cssclass = 'error ' + old_cssclass\n %>\n ${lines[index] | n,syntax_highlight(language='mako')}\n <%\n if pygments_html_formatter:\n pygments_html_formatter.cssclass = old_cssclass\n %>\n % else:\n ${lines[index] | n,syntax_highlight(language='mako')}\n % endif\n % endfor\n </div>\n </div>\n% endif\n\n<div class=\"stacktrace\">\n% for (filename, lineno, function, line) in tback.reverse_traceback:\n <div class=\"location\">${filename}, line ${lineno}:</div>\n <div class=\"nonhighlight\">\n <%\n if pygments_html_formatter:\n pygments_html_formatter.linenostart = lineno\n %>\n <div class=\"sourceline\">${line | n,syntax_highlight(filename)}</div>\n </div>\n% endfor\n</div>\n\"\"\"", ")", "tback", "=", "RichTraceback", "(", "error", ",", "error", ".", "__traceback__", ")", "lines", "=", "stacktrace_template", ".", "render_unicode", "(", "tback", "=", "tback", ")", "return", "{", "'message'", ":", "''", ",", "'source_lines'", ":", "[", "(", "''", ",", "mark_safe", "(", "lines", ")", ")", ",", "]", ",", "'before'", ":", "''", ",", "'during'", ":", "''", ",", "'after'", ":", "''", ",", "'top'", ":", "0", ",", "'bottom'", ":", "0", ",", "'total'", ":", "0", ",", "'line'", ":", "tback", ".", "lineno", "or", "0", ",", "'name'", ":", "template_name", ",", "'start'", ":", "0", ",", "'end'", ":", "0", ",", "}" ]
This structure is what Django wants when errors occur in templates. It gives the user a nice stack trace in the error page during debug.
[ "This", "structure", "is", "what", "Django", "wants", "when", "errors", "occur", "in", "templates", ".", "It", "gives", "the", "user", "a", "nice", "stack", "trace", "in", "the", "error", "page", "during", "debug", "." ]
train
https://github.com/doconix/django-mako-plus/blob/a90f9b4af19e5fa9f83452989cdcaed21569a181/django_mako_plus/template/util.py#L40-L170
doconix/django-mako-plus
django_mako_plus/template/adapter.py
MakoTemplateAdapter.name
def name(self): '''Returns the name of this template (if created from a file) or "string" if not''' if self.mako_template.filename: return os.path.basename(self.mako_template.filename) return 'string'
python
def name(self): '''Returns the name of this template (if created from a file) or "string" if not''' if self.mako_template.filename: return os.path.basename(self.mako_template.filename) return 'string'
[ "def", "name", "(", "self", ")", ":", "if", "self", ".", "mako_template", ".", "filename", ":", "return", "os", ".", "path", ".", "basename", "(", "self", ".", "mako_template", ".", "filename", ")", "return", "'string'" ]
Returns the name of this template (if created from a file) or "string" if not
[ "Returns", "the", "name", "of", "this", "template", "(", "if", "created", "from", "a", "file", ")", "or", "string", "if", "not" ]
train
https://github.com/doconix/django-mako-plus/blob/a90f9b4af19e5fa9f83452989cdcaed21569a181/django_mako_plus/template/adapter.py#L39-L43
doconix/django-mako-plus
django_mako_plus/template/adapter.py
MakoTemplateAdapter.render
def render(self, context=None, request=None, def_name=None): ''' Renders a template using the Mako system. This method signature conforms to the Django template API, which specifies that template.render() returns a string. @context A dictionary of name=value variables to send to the template page. This can be a real dictionary or a Django Context object. @request The request context from Django. If this is None, any TEMPLATE_CONTEXT_PROCESSORS defined in your settings file will be ignored but the template will otherwise render fine. @def_name Limits output to a specific top-level Mako <%block> or <%def> section within the template. If the section is a <%def>, any parameters must be in the context dictionary. For example, def_name="foo" will call <%block name="foo"></%block> or <%def name="foo()"></def> within the template. Returns the rendered template as a unicode string. The method triggers two signals: 1. dmp_signal_pre_render_template: you can (optionally) return a new Mako Template object from a receiver to replace the normal template object that is used for the render operation. 2. dmp_signal_post_render_template: you can (optionally) return a string to replace the string from the normal template object render. ''' dmp = apps.get_app_config('django_mako_plus') # set up the context dictionary, which is the variables available throughout the template context_dict = {} # if request is None, add some default items because the context processors won't happen if request is None: context_dict['settings'] = settings context_dict['STATIC_URL'] = settings.STATIC_URL # let the context_processors add variables to the context. if not isinstance(context, Context): context = Context(context) if request is None else RequestContext(request, context) with context.bind_template(self): for d in context: context_dict.update(d) context_dict.pop('self', None) # some contexts have self in them, and it messes up render_unicode below because we get two selfs # send the pre-render signal if dmp.options['SIGNALS'] and request is not None: for receiver, ret_template_obj in dmp_signal_pre_render_template.send(sender=self, request=request, context=context, template=self.mako_template): if ret_template_obj is not None: if isinstance(ret_template_obj, MakoTemplateAdapter): self.mako_template = ret_template_obj.mako_template # if the signal function sends a MakoTemplateAdapter back, use the real mako template inside of it else: self.mako_template = ret_template_obj # if something else, we assume it is a mako.template.Template, so use it as the template # do we need to limit down to a specific def? # this only finds within the exact template (won't go up the inheritance tree) render_obj = self.mako_template if def_name is None: def_name = self.def_name if def_name: # do we need to limit to just a def? render_obj = self.mako_template.get_def(def_name) # PRIMARY FUNCTION: render the template if log.isEnabledFor(logging.INFO): log.info('rendering template %s%s%s', self.name, ('::' if def_name else ''), def_name or '') if settings.DEBUG: try: content = render_obj.render_unicode(**context_dict) except Exception as e: log.exception('exception raised during template rendering: %s', e) # to the console e.template_debug = get_template_debug('%s%s%s' % (self.name, ('::' if def_name else ''), def_name or ''), e) raise else: # this is outside the above "try" loop because in non-DEBUG mode, we want to let the exception throw out of here (without having to re-raise it) content = render_obj.render_unicode(**context_dict) # send the post-render signal if dmp.options['SIGNALS'] and request is not None: for receiver, ret_content in dmp_signal_post_render_template.send(sender=self, request=request, context=context, template=self.mako_template, content=content): if ret_content is not None: content = ret_content # sets it to the last non-None return in the signal receiver chain # return return mark_safe(content)
python
def render(self, context=None, request=None, def_name=None): ''' Renders a template using the Mako system. This method signature conforms to the Django template API, which specifies that template.render() returns a string. @context A dictionary of name=value variables to send to the template page. This can be a real dictionary or a Django Context object. @request The request context from Django. If this is None, any TEMPLATE_CONTEXT_PROCESSORS defined in your settings file will be ignored but the template will otherwise render fine. @def_name Limits output to a specific top-level Mako <%block> or <%def> section within the template. If the section is a <%def>, any parameters must be in the context dictionary. For example, def_name="foo" will call <%block name="foo"></%block> or <%def name="foo()"></def> within the template. Returns the rendered template as a unicode string. The method triggers two signals: 1. dmp_signal_pre_render_template: you can (optionally) return a new Mako Template object from a receiver to replace the normal template object that is used for the render operation. 2. dmp_signal_post_render_template: you can (optionally) return a string to replace the string from the normal template object render. ''' dmp = apps.get_app_config('django_mako_plus') # set up the context dictionary, which is the variables available throughout the template context_dict = {} # if request is None, add some default items because the context processors won't happen if request is None: context_dict['settings'] = settings context_dict['STATIC_URL'] = settings.STATIC_URL # let the context_processors add variables to the context. if not isinstance(context, Context): context = Context(context) if request is None else RequestContext(request, context) with context.bind_template(self): for d in context: context_dict.update(d) context_dict.pop('self', None) # some contexts have self in them, and it messes up render_unicode below because we get two selfs # send the pre-render signal if dmp.options['SIGNALS'] and request is not None: for receiver, ret_template_obj in dmp_signal_pre_render_template.send(sender=self, request=request, context=context, template=self.mako_template): if ret_template_obj is not None: if isinstance(ret_template_obj, MakoTemplateAdapter): self.mako_template = ret_template_obj.mako_template # if the signal function sends a MakoTemplateAdapter back, use the real mako template inside of it else: self.mako_template = ret_template_obj # if something else, we assume it is a mako.template.Template, so use it as the template # do we need to limit down to a specific def? # this only finds within the exact template (won't go up the inheritance tree) render_obj = self.mako_template if def_name is None: def_name = self.def_name if def_name: # do we need to limit to just a def? render_obj = self.mako_template.get_def(def_name) # PRIMARY FUNCTION: render the template if log.isEnabledFor(logging.INFO): log.info('rendering template %s%s%s', self.name, ('::' if def_name else ''), def_name or '') if settings.DEBUG: try: content = render_obj.render_unicode(**context_dict) except Exception as e: log.exception('exception raised during template rendering: %s', e) # to the console e.template_debug = get_template_debug('%s%s%s' % (self.name, ('::' if def_name else ''), def_name or ''), e) raise else: # this is outside the above "try" loop because in non-DEBUG mode, we want to let the exception throw out of here (without having to re-raise it) content = render_obj.render_unicode(**context_dict) # send the post-render signal if dmp.options['SIGNALS'] and request is not None: for receiver, ret_content in dmp_signal_post_render_template.send(sender=self, request=request, context=context, template=self.mako_template, content=content): if ret_content is not None: content = ret_content # sets it to the last non-None return in the signal receiver chain # return return mark_safe(content)
[ "def", "render", "(", "self", ",", "context", "=", "None", ",", "request", "=", "None", ",", "def_name", "=", "None", ")", ":", "dmp", "=", "apps", ".", "get_app_config", "(", "'django_mako_plus'", ")", "# set up the context dictionary, which is the variables available throughout the template", "context_dict", "=", "{", "}", "# if request is None, add some default items because the context processors won't happen", "if", "request", "is", "None", ":", "context_dict", "[", "'settings'", "]", "=", "settings", "context_dict", "[", "'STATIC_URL'", "]", "=", "settings", ".", "STATIC_URL", "# let the context_processors add variables to the context.", "if", "not", "isinstance", "(", "context", ",", "Context", ")", ":", "context", "=", "Context", "(", "context", ")", "if", "request", "is", "None", "else", "RequestContext", "(", "request", ",", "context", ")", "with", "context", ".", "bind_template", "(", "self", ")", ":", "for", "d", "in", "context", ":", "context_dict", ".", "update", "(", "d", ")", "context_dict", ".", "pop", "(", "'self'", ",", "None", ")", "# some contexts have self in them, and it messes up render_unicode below because we get two selfs", "# send the pre-render signal", "if", "dmp", ".", "options", "[", "'SIGNALS'", "]", "and", "request", "is", "not", "None", ":", "for", "receiver", ",", "ret_template_obj", "in", "dmp_signal_pre_render_template", ".", "send", "(", "sender", "=", "self", ",", "request", "=", "request", ",", "context", "=", "context", ",", "template", "=", "self", ".", "mako_template", ")", ":", "if", "ret_template_obj", "is", "not", "None", ":", "if", "isinstance", "(", "ret_template_obj", ",", "MakoTemplateAdapter", ")", ":", "self", ".", "mako_template", "=", "ret_template_obj", ".", "mako_template", "# if the signal function sends a MakoTemplateAdapter back, use the real mako template inside of it", "else", ":", "self", ".", "mako_template", "=", "ret_template_obj", "# if something else, we assume it is a mako.template.Template, so use it as the template", "# do we need to limit down to a specific def?", "# this only finds within the exact template (won't go up the inheritance tree)", "render_obj", "=", "self", ".", "mako_template", "if", "def_name", "is", "None", ":", "def_name", "=", "self", ".", "def_name", "if", "def_name", ":", "# do we need to limit to just a def?", "render_obj", "=", "self", ".", "mako_template", ".", "get_def", "(", "def_name", ")", "# PRIMARY FUNCTION: render the template", "if", "log", ".", "isEnabledFor", "(", "logging", ".", "INFO", ")", ":", "log", ".", "info", "(", "'rendering template %s%s%s'", ",", "self", ".", "name", ",", "(", "'::'", "if", "def_name", "else", "''", ")", ",", "def_name", "or", "''", ")", "if", "settings", ".", "DEBUG", ":", "try", ":", "content", "=", "render_obj", ".", "render_unicode", "(", "*", "*", "context_dict", ")", "except", "Exception", "as", "e", ":", "log", ".", "exception", "(", "'exception raised during template rendering: %s'", ",", "e", ")", "# to the console", "e", ".", "template_debug", "=", "get_template_debug", "(", "'%s%s%s'", "%", "(", "self", ".", "name", ",", "(", "'::'", "if", "def_name", "else", "''", ")", ",", "def_name", "or", "''", ")", ",", "e", ")", "raise", "else", ":", "# this is outside the above \"try\" loop because in non-DEBUG mode, we want to let the exception throw out of here (without having to re-raise it)", "content", "=", "render_obj", ".", "render_unicode", "(", "*", "*", "context_dict", ")", "# send the post-render signal", "if", "dmp", ".", "options", "[", "'SIGNALS'", "]", "and", "request", "is", "not", "None", ":", "for", "receiver", ",", "ret_content", "in", "dmp_signal_post_render_template", ".", "send", "(", "sender", "=", "self", ",", "request", "=", "request", ",", "context", "=", "context", ",", "template", "=", "self", ".", "mako_template", ",", "content", "=", "content", ")", ":", "if", "ret_content", "is", "not", "None", ":", "content", "=", "ret_content", "# sets it to the last non-None return in the signal receiver chain", "# return", "return", "mark_safe", "(", "content", ")" ]
Renders a template using the Mako system. This method signature conforms to the Django template API, which specifies that template.render() returns a string. @context A dictionary of name=value variables to send to the template page. This can be a real dictionary or a Django Context object. @request The request context from Django. If this is None, any TEMPLATE_CONTEXT_PROCESSORS defined in your settings file will be ignored but the template will otherwise render fine. @def_name Limits output to a specific top-level Mako <%block> or <%def> section within the template. If the section is a <%def>, any parameters must be in the context dictionary. For example, def_name="foo" will call <%block name="foo"></%block> or <%def name="foo()"></def> within the template. Returns the rendered template as a unicode string. The method triggers two signals: 1. dmp_signal_pre_render_template: you can (optionally) return a new Mako Template object from a receiver to replace the normal template object that is used for the render operation. 2. dmp_signal_post_render_template: you can (optionally) return a string to replace the string from the normal template object render.
[ "Renders", "a", "template", "using", "the", "Mako", "system", ".", "This", "method", "signature", "conforms", "to", "the", "Django", "template", "API", "which", "specifies", "that", "template", ".", "render", "()", "returns", "a", "string", "." ]
train
https://github.com/doconix/django-mako-plus/blob/a90f9b4af19e5fa9f83452989cdcaed21569a181/django_mako_plus/template/adapter.py#L57-L131
doconix/django-mako-plus
django_mako_plus/template/adapter.py
MakoTemplateAdapter.render_to_response
def render_to_response(self, context=None, request=None, def_name=None, content_type=None, status=None, charset=None): ''' Renders the template and returns an HttpRequest object containing its content. This method returns a django.http.Http404 exception if the template is not found. If the template raises a django_mako_plus.RedirectException, the browser is redirected to the given page, and a new request from the browser restarts the entire DMP routing process. If the template raises a django_mako_plus.InternalRedirectException, the entire DMP routing process is restarted internally (the browser doesn't see the redirect). @request The request context from Django. If this is None, any TEMPLATE_CONTEXT_PROCESSORS defined in your settings file will be ignored but the template will otherwise render fine. @template The template file path to render. This is relative to the app_path/controller_TEMPLATES_DIR/ directory. For example, to render app_path/templates/page1, set template="page1.html", assuming you have set up the variables as described in the documentation above. @context A dictionary of name=value variables to send to the template page. This can be a real dictionary or a Django Context object. @def_name Limits output to a specific top-level Mako <%block> or <%def> section within the template. For example, def_name="foo" will call <%block name="foo"></%block> or <%def name="foo()"></def> within the template. @content_type The MIME type of the response. Defaults to settings.DEFAULT_CONTENT_TYPE (usually 'text/html'). @status The HTTP response status code. Defaults to 200 (OK). @charset The charset to encode the processed template string (the output) with. Defaults to settings.DEFAULT_CHARSET (usually 'utf-8'). The method triggers two signals: 1. dmp_signal_pre_render_template: you can (optionally) return a new Mako Template object from a receiver to replace the normal template object that is used for the render operation. 2. dmp_signal_post_render_template: you can (optionally) return a string to replace the string from the normal template object render. ''' try: if content_type is None: content_type = mimetypes.types_map.get(os.path.splitext(self.mako_template.filename)[1].lower(), settings.DEFAULT_CONTENT_TYPE) if charset is None: charset = settings.DEFAULT_CHARSET if status is None: status = 200 content = self.render(context=context, request=request, def_name=def_name) return HttpResponse(content.encode(charset), content_type='%s; charset=%s' % (content_type, charset), status=status) except RedirectException: # redirect to another page e = sys.exc_info()[1] if request is None: log.info('a template redirected processing to %s', e.redirect_to) else: log.info('view function %s.%s redirected processing to %s', request.dmp.module, request.dmp.function, e.redirect_to) # send the signal dmp = apps.get_app_config('django_mako_plus') if dmp.options['SIGNALS']: dmp_signal_redirect_exception.send(sender=sys.modules[__name__], request=request, exc=e) # send the browser the redirect command return e.get_response(request)
python
def render_to_response(self, context=None, request=None, def_name=None, content_type=None, status=None, charset=None): ''' Renders the template and returns an HttpRequest object containing its content. This method returns a django.http.Http404 exception if the template is not found. If the template raises a django_mako_plus.RedirectException, the browser is redirected to the given page, and a new request from the browser restarts the entire DMP routing process. If the template raises a django_mako_plus.InternalRedirectException, the entire DMP routing process is restarted internally (the browser doesn't see the redirect). @request The request context from Django. If this is None, any TEMPLATE_CONTEXT_PROCESSORS defined in your settings file will be ignored but the template will otherwise render fine. @template The template file path to render. This is relative to the app_path/controller_TEMPLATES_DIR/ directory. For example, to render app_path/templates/page1, set template="page1.html", assuming you have set up the variables as described in the documentation above. @context A dictionary of name=value variables to send to the template page. This can be a real dictionary or a Django Context object. @def_name Limits output to a specific top-level Mako <%block> or <%def> section within the template. For example, def_name="foo" will call <%block name="foo"></%block> or <%def name="foo()"></def> within the template. @content_type The MIME type of the response. Defaults to settings.DEFAULT_CONTENT_TYPE (usually 'text/html'). @status The HTTP response status code. Defaults to 200 (OK). @charset The charset to encode the processed template string (the output) with. Defaults to settings.DEFAULT_CHARSET (usually 'utf-8'). The method triggers two signals: 1. dmp_signal_pre_render_template: you can (optionally) return a new Mako Template object from a receiver to replace the normal template object that is used for the render operation. 2. dmp_signal_post_render_template: you can (optionally) return a string to replace the string from the normal template object render. ''' try: if content_type is None: content_type = mimetypes.types_map.get(os.path.splitext(self.mako_template.filename)[1].lower(), settings.DEFAULT_CONTENT_TYPE) if charset is None: charset = settings.DEFAULT_CHARSET if status is None: status = 200 content = self.render(context=context, request=request, def_name=def_name) return HttpResponse(content.encode(charset), content_type='%s; charset=%s' % (content_type, charset), status=status) except RedirectException: # redirect to another page e = sys.exc_info()[1] if request is None: log.info('a template redirected processing to %s', e.redirect_to) else: log.info('view function %s.%s redirected processing to %s', request.dmp.module, request.dmp.function, e.redirect_to) # send the signal dmp = apps.get_app_config('django_mako_plus') if dmp.options['SIGNALS']: dmp_signal_redirect_exception.send(sender=sys.modules[__name__], request=request, exc=e) # send the browser the redirect command return e.get_response(request)
[ "def", "render_to_response", "(", "self", ",", "context", "=", "None", ",", "request", "=", "None", ",", "def_name", "=", "None", ",", "content_type", "=", "None", ",", "status", "=", "None", ",", "charset", "=", "None", ")", ":", "try", ":", "if", "content_type", "is", "None", ":", "content_type", "=", "mimetypes", ".", "types_map", ".", "get", "(", "os", ".", "path", ".", "splitext", "(", "self", ".", "mako_template", ".", "filename", ")", "[", "1", "]", ".", "lower", "(", ")", ",", "settings", ".", "DEFAULT_CONTENT_TYPE", ")", "if", "charset", "is", "None", ":", "charset", "=", "settings", ".", "DEFAULT_CHARSET", "if", "status", "is", "None", ":", "status", "=", "200", "content", "=", "self", ".", "render", "(", "context", "=", "context", ",", "request", "=", "request", ",", "def_name", "=", "def_name", ")", "return", "HttpResponse", "(", "content", ".", "encode", "(", "charset", ")", ",", "content_type", "=", "'%s; charset=%s'", "%", "(", "content_type", ",", "charset", ")", ",", "status", "=", "status", ")", "except", "RedirectException", ":", "# redirect to another page", "e", "=", "sys", ".", "exc_info", "(", ")", "[", "1", "]", "if", "request", "is", "None", ":", "log", ".", "info", "(", "'a template redirected processing to %s'", ",", "e", ".", "redirect_to", ")", "else", ":", "log", ".", "info", "(", "'view function %s.%s redirected processing to %s'", ",", "request", ".", "dmp", ".", "module", ",", "request", ".", "dmp", ".", "function", ",", "e", ".", "redirect_to", ")", "# send the signal", "dmp", "=", "apps", ".", "get_app_config", "(", "'django_mako_plus'", ")", "if", "dmp", ".", "options", "[", "'SIGNALS'", "]", ":", "dmp_signal_redirect_exception", ".", "send", "(", "sender", "=", "sys", ".", "modules", "[", "__name__", "]", ",", "request", "=", "request", ",", "exc", "=", "e", ")", "# send the browser the redirect command", "return", "e", ".", "get_response", "(", "request", ")" ]
Renders the template and returns an HttpRequest object containing its content. This method returns a django.http.Http404 exception if the template is not found. If the template raises a django_mako_plus.RedirectException, the browser is redirected to the given page, and a new request from the browser restarts the entire DMP routing process. If the template raises a django_mako_plus.InternalRedirectException, the entire DMP routing process is restarted internally (the browser doesn't see the redirect). @request The request context from Django. If this is None, any TEMPLATE_CONTEXT_PROCESSORS defined in your settings file will be ignored but the template will otherwise render fine. @template The template file path to render. This is relative to the app_path/controller_TEMPLATES_DIR/ directory. For example, to render app_path/templates/page1, set template="page1.html", assuming you have set up the variables as described in the documentation above. @context A dictionary of name=value variables to send to the template page. This can be a real dictionary or a Django Context object. @def_name Limits output to a specific top-level Mako <%block> or <%def> section within the template. For example, def_name="foo" will call <%block name="foo"></%block> or <%def name="foo()"></def> within the template. @content_type The MIME type of the response. Defaults to settings.DEFAULT_CONTENT_TYPE (usually 'text/html'). @status The HTTP response status code. Defaults to 200 (OK). @charset The charset to encode the processed template string (the output) with. Defaults to settings.DEFAULT_CHARSET (usually 'utf-8'). The method triggers two signals: 1. dmp_signal_pre_render_template: you can (optionally) return a new Mako Template object from a receiver to replace the normal template object that is used for the render operation. 2. dmp_signal_post_render_template: you can (optionally) return a string to replace the string from the normal template object render.
[ "Renders", "the", "template", "and", "returns", "an", "HttpRequest", "object", "containing", "its", "content", "." ]
train
https://github.com/doconix/django-mako-plus/blob/a90f9b4af19e5fa9f83452989cdcaed21569a181/django_mako_plus/template/adapter.py#L134-L184
doconix/django-mako-plus
django_mako_plus/management/mixins.py
DMPCommandMixIn.get_action_by_dest
def get_action_by_dest(self, parser, dest): '''Retrieves the given parser action object by its dest= attribute''' for action in parser._actions: if action.dest == dest: return action return None
python
def get_action_by_dest(self, parser, dest): '''Retrieves the given parser action object by its dest= attribute''' for action in parser._actions: if action.dest == dest: return action return None
[ "def", "get_action_by_dest", "(", "self", ",", "parser", ",", "dest", ")", ":", "for", "action", "in", "parser", ".", "_actions", ":", "if", "action", ".", "dest", "==", "dest", ":", "return", "action", "return", "None" ]
Retrieves the given parser action object by its dest= attribute
[ "Retrieves", "the", "given", "parser", "action", "object", "by", "its", "dest", "=", "attribute" ]
train
https://github.com/doconix/django-mako-plus/blob/a90f9b4af19e5fa9f83452989cdcaed21569a181/django_mako_plus/management/mixins.py#L34-L39
doconix/django-mako-plus
django_mako_plus/management/mixins.py
DMPCommandMixIn.execute
def execute(self, *args, **options): '''Placing this in execute because then subclass handle() don't have to call super''' if options['verbose']: options['verbosity'] = 3 if options['quiet']: options['verbosity'] = 0 self.verbosity = options.get('verbosity', 1) super().execute(*args, **options)
python
def execute(self, *args, **options): '''Placing this in execute because then subclass handle() don't have to call super''' if options['verbose']: options['verbosity'] = 3 if options['quiet']: options['verbosity'] = 0 self.verbosity = options.get('verbosity', 1) super().execute(*args, **options)
[ "def", "execute", "(", "self", ",", "*", "args", ",", "*", "*", "options", ")", ":", "if", "options", "[", "'verbose'", "]", ":", "options", "[", "'verbosity'", "]", "=", "3", "if", "options", "[", "'quiet'", "]", ":", "options", "[", "'verbosity'", "]", "=", "0", "self", ".", "verbosity", "=", "options", ".", "get", "(", "'verbosity'", ",", "1", ")", "super", "(", ")", ".", "execute", "(", "*", "args", ",", "*", "*", "options", ")" ]
Placing this in execute because then subclass handle() don't have to call super
[ "Placing", "this", "in", "execute", "because", "then", "subclass", "handle", "()", "don", "t", "have", "to", "call", "super" ]
train
https://github.com/doconix/django-mako-plus/blob/a90f9b4af19e5fa9f83452989cdcaed21569a181/django_mako_plus/management/mixins.py#L42-L49
doconix/django-mako-plus
django_mako_plus/management/mixins.py
DMPCommandMixIn.message
def message(self, msg='', level=1, tab=0): '''Print a message to the console''' if self.verbosity >= level: self.stdout.write('{}{}'.format(' ' * tab, msg))
python
def message(self, msg='', level=1, tab=0): '''Print a message to the console''' if self.verbosity >= level: self.stdout.write('{}{}'.format(' ' * tab, msg))
[ "def", "message", "(", "self", ",", "msg", "=", "''", ",", "level", "=", "1", ",", "tab", "=", "0", ")", ":", "if", "self", ".", "verbosity", ">=", "level", ":", "self", ".", "stdout", ".", "write", "(", "'{}{}'", ".", "format", "(", "' '", "*", "tab", ",", "msg", ")", ")" ]
Print a message to the console
[ "Print", "a", "message", "to", "the", "console" ]
train
https://github.com/doconix/django-mako-plus/blob/a90f9b4af19e5fa9f83452989cdcaed21569a181/django_mako_plus/management/mixins.py#L57-L60
doconix/django-mako-plus
django_mako_plus/util/base58.py
b58enc
def b58enc(uid): '''Encodes a UID to an 11-length string, encoded using base58 url-safe alphabet''' # note: i tested a buffer array too, but string concat was 2x faster if not isinstance(uid, int): raise ValueError('Invalid integer: {}'.format(uid)) if uid == 0: return BASE58CHARS[0] enc_uid = "" while uid: uid, r = divmod(uid, 58) enc_uid = BASE58CHARS[r] + enc_uid return enc_uid
python
def b58enc(uid): '''Encodes a UID to an 11-length string, encoded using base58 url-safe alphabet''' # note: i tested a buffer array too, but string concat was 2x faster if not isinstance(uid, int): raise ValueError('Invalid integer: {}'.format(uid)) if uid == 0: return BASE58CHARS[0] enc_uid = "" while uid: uid, r = divmod(uid, 58) enc_uid = BASE58CHARS[r] + enc_uid return enc_uid
[ "def", "b58enc", "(", "uid", ")", ":", "# note: i tested a buffer array too, but string concat was 2x faster", "if", "not", "isinstance", "(", "uid", ",", "int", ")", ":", "raise", "ValueError", "(", "'Invalid integer: {}'", ".", "format", "(", "uid", ")", ")", "if", "uid", "==", "0", ":", "return", "BASE58CHARS", "[", "0", "]", "enc_uid", "=", "\"\"", "while", "uid", ":", "uid", ",", "r", "=", "divmod", "(", "uid", ",", "58", ")", "enc_uid", "=", "BASE58CHARS", "[", "r", "]", "+", "enc_uid", "return", "enc_uid" ]
Encodes a UID to an 11-length string, encoded using base58 url-safe alphabet
[ "Encodes", "a", "UID", "to", "an", "11", "-", "length", "string", "encoded", "using", "base58", "url", "-", "safe", "alphabet" ]
train
https://github.com/doconix/django-mako-plus/blob/a90f9b4af19e5fa9f83452989cdcaed21569a181/django_mako_plus/util/base58.py#L9-L20
doconix/django-mako-plus
django_mako_plus/util/base58.py
b58dec
def b58dec(enc_uid): '''Decodes a UID from base58, url-safe alphabet back to int.''' if isinstance(enc_uid, str): pass elif isinstance(enc_uid, bytes): enc_uid = enc_uid.decode('utf8') else: raise ValueError('Cannot decode this type: {}'.format(enc_uid)) uid = 0 try: for i, ch in enumerate(enc_uid): uid = (uid * 58) + BASE58INDEX[ch] except KeyError: raise ValueError('Invalid character: "{}" ("{}", index 5)'.format(ch, enc_uid, i)) return uid
python
def b58dec(enc_uid): '''Decodes a UID from base58, url-safe alphabet back to int.''' if isinstance(enc_uid, str): pass elif isinstance(enc_uid, bytes): enc_uid = enc_uid.decode('utf8') else: raise ValueError('Cannot decode this type: {}'.format(enc_uid)) uid = 0 try: for i, ch in enumerate(enc_uid): uid = (uid * 58) + BASE58INDEX[ch] except KeyError: raise ValueError('Invalid character: "{}" ("{}", index 5)'.format(ch, enc_uid, i)) return uid
[ "def", "b58dec", "(", "enc_uid", ")", ":", "if", "isinstance", "(", "enc_uid", ",", "str", ")", ":", "pass", "elif", "isinstance", "(", "enc_uid", ",", "bytes", ")", ":", "enc_uid", "=", "enc_uid", ".", "decode", "(", "'utf8'", ")", "else", ":", "raise", "ValueError", "(", "'Cannot decode this type: {}'", ".", "format", "(", "enc_uid", ")", ")", "uid", "=", "0", "try", ":", "for", "i", ",", "ch", "in", "enumerate", "(", "enc_uid", ")", ":", "uid", "=", "(", "uid", "*", "58", ")", "+", "BASE58INDEX", "[", "ch", "]", "except", "KeyError", ":", "raise", "ValueError", "(", "'Invalid character: \"{}\" (\"{}\", index 5)'", ".", "format", "(", "ch", ",", "enc_uid", ",", "i", ")", ")", "return", "uid" ]
Decodes a UID from base58, url-safe alphabet back to int.
[ "Decodes", "a", "UID", "from", "base58", "url", "-", "safe", "alphabet", "back", "to", "int", "." ]
train
https://github.com/doconix/django-mako-plus/blob/a90f9b4af19e5fa9f83452989cdcaed21569a181/django_mako_plus/util/base58.py#L22-L36
doconix/django-mako-plus
django_mako_plus/management/commands/dmp_collectstatic.py
minify
def minify(text, minifier): '''Minifies the source text (if needed)''' # there really isn't a good way to know if a file is already minified. # our heuristic is if source is more than 50 bytes greater of dest OR # if a hard return is found in the first 50 chars, we assume it is not minified. minified = minifier(text) if abs(len(text) - len(minified)) > 50 or '\n' in text[:50]: return minified return text
python
def minify(text, minifier): '''Minifies the source text (if needed)''' # there really isn't a good way to know if a file is already minified. # our heuristic is if source is more than 50 bytes greater of dest OR # if a hard return is found in the first 50 chars, we assume it is not minified. minified = minifier(text) if abs(len(text) - len(minified)) > 50 or '\n' in text[:50]: return minified return text
[ "def", "minify", "(", "text", ",", "minifier", ")", ":", "# there really isn't a good way to know if a file is already minified.", "# our heuristic is if source is more than 50 bytes greater of dest OR", "# if a hard return is found in the first 50 chars, we assume it is not minified.", "minified", "=", "minifier", "(", "text", ")", "if", "abs", "(", "len", "(", "text", ")", "-", "len", "(", "minified", ")", ")", ">", "50", "or", "'\\n'", "in", "text", "[", ":", "50", "]", ":", "return", "minified", "return", "text" ]
Minifies the source text (if needed)
[ "Minifies", "the", "source", "text", "(", "if", "needed", ")" ]
train
https://github.com/doconix/django-mako-plus/blob/a90f9b4af19e5fa9f83452989cdcaed21569a181/django_mako_plus/management/commands/dmp_collectstatic.py#L235-L243
doconix/django-mako-plus
django_mako_plus/management/commands/dmp_collectstatic.py
Rule.match
def match(self, fname, flevel, ftype): '''Returns the result score if the file matches this rule''' # if filetype is the same # and level isn't set or level is the same # and pattern matche the filename if self.filetype == ftype and (self.level is None or self.level == flevel) and fnmatch.fnmatch(fname, self.pattern): return self.score return 0
python
def match(self, fname, flevel, ftype): '''Returns the result score if the file matches this rule''' # if filetype is the same # and level isn't set or level is the same # and pattern matche the filename if self.filetype == ftype and (self.level is None or self.level == flevel) and fnmatch.fnmatch(fname, self.pattern): return self.score return 0
[ "def", "match", "(", "self", ",", "fname", ",", "flevel", ",", "ftype", ")", ":", "# if filetype is the same", "# and level isn't set or level is the same", "# and pattern matche the filename", "if", "self", ".", "filetype", "==", "ftype", "and", "(", "self", ".", "level", "is", "None", "or", "self", ".", "level", "==", "flevel", ")", "and", "fnmatch", ".", "fnmatch", "(", "fname", ",", "self", ".", "pattern", ")", ":", "return", "self", ".", "score", "return", "0" ]
Returns the result score if the file matches this rule
[ "Returns", "the", "result", "score", "if", "the", "file", "matches", "this", "rule" ]
train
https://github.com/doconix/django-mako-plus/blob/a90f9b4af19e5fa9f83452989cdcaed21569a181/django_mako_plus/management/commands/dmp_collectstatic.py#L31-L38
doconix/django-mako-plus
django_mako_plus/management/commands/dmp_collectstatic.py
Command.create_rules
def create_rules(self): '''Adds rules for the command line options''' dmp = apps.get_app_config('django_mako_plus') # the default rules = [ # files are included by default Rule('*', level=None, filetype=TYPE_FILE, score=1), # files at the app level are skipped Rule('*', level=0, filetype=TYPE_FILE, score=-2), # directories are recursed by default Rule('*', level=None, filetype=TYPE_DIRECTORY, score=1), # directories at the app level are skipped Rule('*', level=0, filetype=TYPE_DIRECTORY, score=-2), # media, scripts, styles directories are what we want to copy Rule('media', level=0, filetype=TYPE_DIRECTORY, score=6), Rule('scripts', level=0, filetype=TYPE_DIRECTORY, score=6), Rule('styles', level=0, filetype=TYPE_DIRECTORY, score=6), # ignore the template cache directories Rule(dmp.options['TEMPLATES_CACHE_DIR'], level=None, filetype=TYPE_DIRECTORY, score=-3), # ignore python cache directories Rule('__pycache__', level=None, filetype=TYPE_DIRECTORY, score=-3), # ignore compiled python files Rule('*.pyc', level=None, filetype=TYPE_FILE, score=-3), ] # include rules have score of 50 because they trump all initial rules for pattern in (self.options.get('include_dir') or []): self.message('Setting rule - recurse directories: {}'.format(pattern), 1) rules.append(Rule(pattern, level=None, filetype=TYPE_DIRECTORY, score=50)) for pattern in (self.options.get('include_file') or []): self.message('Setting rule - include files: {}'.format(pattern), 1) rules.append(Rule(pattern, level=None, filetype=TYPE_FILE, score=50)) # skip rules have score of 100 because they trump everything, including the includes from the command line for pattern in (self.options.get('skip_dir') or []): self.message('Setting rule - skip directories: {}'.format(pattern), 1) rules.append(Rule(pattern, level=None, filetype=TYPE_DIRECTORY, score=-100)) for pattern in (self.options.get('skip_file') or []): self.message('Setting rule - skip files: {}'.format(pattern), 1) rules.append(Rule(pattern, level=None, filetype=TYPE_FILE, score=-100)) return rules
python
def create_rules(self): '''Adds rules for the command line options''' dmp = apps.get_app_config('django_mako_plus') # the default rules = [ # files are included by default Rule('*', level=None, filetype=TYPE_FILE, score=1), # files at the app level are skipped Rule('*', level=0, filetype=TYPE_FILE, score=-2), # directories are recursed by default Rule('*', level=None, filetype=TYPE_DIRECTORY, score=1), # directories at the app level are skipped Rule('*', level=0, filetype=TYPE_DIRECTORY, score=-2), # media, scripts, styles directories are what we want to copy Rule('media', level=0, filetype=TYPE_DIRECTORY, score=6), Rule('scripts', level=0, filetype=TYPE_DIRECTORY, score=6), Rule('styles', level=0, filetype=TYPE_DIRECTORY, score=6), # ignore the template cache directories Rule(dmp.options['TEMPLATES_CACHE_DIR'], level=None, filetype=TYPE_DIRECTORY, score=-3), # ignore python cache directories Rule('__pycache__', level=None, filetype=TYPE_DIRECTORY, score=-3), # ignore compiled python files Rule('*.pyc', level=None, filetype=TYPE_FILE, score=-3), ] # include rules have score of 50 because they trump all initial rules for pattern in (self.options.get('include_dir') or []): self.message('Setting rule - recurse directories: {}'.format(pattern), 1) rules.append(Rule(pattern, level=None, filetype=TYPE_DIRECTORY, score=50)) for pattern in (self.options.get('include_file') or []): self.message('Setting rule - include files: {}'.format(pattern), 1) rules.append(Rule(pattern, level=None, filetype=TYPE_FILE, score=50)) # skip rules have score of 100 because they trump everything, including the includes from the command line for pattern in (self.options.get('skip_dir') or []): self.message('Setting rule - skip directories: {}'.format(pattern), 1) rules.append(Rule(pattern, level=None, filetype=TYPE_DIRECTORY, score=-100)) for pattern in (self.options.get('skip_file') or []): self.message('Setting rule - skip files: {}'.format(pattern), 1) rules.append(Rule(pattern, level=None, filetype=TYPE_FILE, score=-100)) return rules
[ "def", "create_rules", "(", "self", ")", ":", "dmp", "=", "apps", ".", "get_app_config", "(", "'django_mako_plus'", ")", "# the default", "rules", "=", "[", "# files are included by default", "Rule", "(", "'*'", ",", "level", "=", "None", ",", "filetype", "=", "TYPE_FILE", ",", "score", "=", "1", ")", ",", "# files at the app level are skipped", "Rule", "(", "'*'", ",", "level", "=", "0", ",", "filetype", "=", "TYPE_FILE", ",", "score", "=", "-", "2", ")", ",", "# directories are recursed by default", "Rule", "(", "'*'", ",", "level", "=", "None", ",", "filetype", "=", "TYPE_DIRECTORY", ",", "score", "=", "1", ")", ",", "# directories at the app level are skipped", "Rule", "(", "'*'", ",", "level", "=", "0", ",", "filetype", "=", "TYPE_DIRECTORY", ",", "score", "=", "-", "2", ")", ",", "# media, scripts, styles directories are what we want to copy", "Rule", "(", "'media'", ",", "level", "=", "0", ",", "filetype", "=", "TYPE_DIRECTORY", ",", "score", "=", "6", ")", ",", "Rule", "(", "'scripts'", ",", "level", "=", "0", ",", "filetype", "=", "TYPE_DIRECTORY", ",", "score", "=", "6", ")", ",", "Rule", "(", "'styles'", ",", "level", "=", "0", ",", "filetype", "=", "TYPE_DIRECTORY", ",", "score", "=", "6", ")", ",", "# ignore the template cache directories", "Rule", "(", "dmp", ".", "options", "[", "'TEMPLATES_CACHE_DIR'", "]", ",", "level", "=", "None", ",", "filetype", "=", "TYPE_DIRECTORY", ",", "score", "=", "-", "3", ")", ",", "# ignore python cache directories", "Rule", "(", "'__pycache__'", ",", "level", "=", "None", ",", "filetype", "=", "TYPE_DIRECTORY", ",", "score", "=", "-", "3", ")", ",", "# ignore compiled python files", "Rule", "(", "'*.pyc'", ",", "level", "=", "None", ",", "filetype", "=", "TYPE_FILE", ",", "score", "=", "-", "3", ")", ",", "]", "# include rules have score of 50 because they trump all initial rules", "for", "pattern", "in", "(", "self", ".", "options", ".", "get", "(", "'include_dir'", ")", "or", "[", "]", ")", ":", "self", ".", "message", "(", "'Setting rule - recurse directories: {}'", ".", "format", "(", "pattern", ")", ",", "1", ")", "rules", ".", "append", "(", "Rule", "(", "pattern", ",", "level", "=", "None", ",", "filetype", "=", "TYPE_DIRECTORY", ",", "score", "=", "50", ")", ")", "for", "pattern", "in", "(", "self", ".", "options", ".", "get", "(", "'include_file'", ")", "or", "[", "]", ")", ":", "self", ".", "message", "(", "'Setting rule - include files: {}'", ".", "format", "(", "pattern", ")", ",", "1", ")", "rules", ".", "append", "(", "Rule", "(", "pattern", ",", "level", "=", "None", ",", "filetype", "=", "TYPE_FILE", ",", "score", "=", "50", ")", ")", "# skip rules have score of 100 because they trump everything, including the includes from the command line", "for", "pattern", "in", "(", "self", ".", "options", ".", "get", "(", "'skip_dir'", ")", "or", "[", "]", ")", ":", "self", ".", "message", "(", "'Setting rule - skip directories: {}'", ".", "format", "(", "pattern", ")", ",", "1", ")", "rules", ".", "append", "(", "Rule", "(", "pattern", ",", "level", "=", "None", ",", "filetype", "=", "TYPE_DIRECTORY", ",", "score", "=", "-", "100", ")", ")", "for", "pattern", "in", "(", "self", ".", "options", ".", "get", "(", "'skip_file'", ")", "or", "[", "]", ")", ":", "self", ".", "message", "(", "'Setting rule - skip files: {}'", ".", "format", "(", "pattern", ")", ",", "1", ")", "rules", ".", "append", "(", "Rule", "(", "pattern", ",", "level", "=", "None", ",", "filetype", "=", "TYPE_FILE", ",", "score", "=", "-", "100", ")", ")", "return", "rules" ]
Adds rules for the command line options
[ "Adds", "rules", "for", "the", "command", "line", "options" ]
train
https://github.com/doconix/django-mako-plus/blob/a90f9b4af19e5fa9f83452989cdcaed21569a181/django_mako_plus/management/commands/dmp_collectstatic.py#L125-L165
doconix/django-mako-plus
django_mako_plus/management/commands/dmp_collectstatic.py
Command.copy_dir
def copy_dir(self, source, dest, level=0): '''Copies the static files from one directory to another. If this command is run, we assume the user wants to overwrite any existing files.''' encoding = settings.DEFAULT_CHARSET or 'utf8' msglevel = 2 if level == 0 else 3 self.message('Directory: {}'.format(source), msglevel, level) # create a directory for this app if not os.path.exists(dest): self.message('Creating directory: {}'.format(dest), msglevel, level+1) os.mkdir(dest) # go through the files in this app for fname in os.listdir(source): source_path = os.path.join(source, fname) dest_path = os.path.join(dest, fname) ext = os.path.splitext(fname)[1].lower() # get the score for this file score = 0 for rule in self.rules: score += rule.match(fname, level, TYPE_DIRECTORY if os.path.isdir(source_path) else TYPE_FILE) # if score is not above zero, we skip this file if score <= 0: self.message('Skipping file with score {}: {}'.format(score, source_path), msglevel, level+1) continue ### if we get here, we need to copy the file ### # if a directory, recurse to it if os.path.isdir(source_path): self.message('Creating directory with score {}: {}'.format(score, source_path), msglevel, level+1) # create it in the destination and recurse if not os.path.exists(dest_path): os.mkdir(dest_path) elif not os.path.isdir(dest_path): # could be a file or link os.unlink(dest_path) os.mkdir(dest_path) self.copy_dir(source_path, dest_path, level+1) # if a regular Javscript file, run through the static file processors (scripts group) elif ext == '.js' and not self.options.get('no_minify') and jsmin: self.message('Including and minifying file with score {}: {}'.format(score, source_path), msglevel, level+1) with open(source_path, encoding=encoding) as fin: with open(dest_path, 'w', encoding=encoding) as fout: minified = minify(fin.read(), jsmin) fout.write(minified) # if a CSS file, run through the static file processors (styles group) elif ext == '.css' and not self.options.get('no_minify') and cssmin: self.message('Including and minifying file with score {}: {}'.format(score, source_path), msglevel, level+1) with open(source_path, encoding=encoding) as fin: with open(dest_path, 'w', encoding=encoding) as fout: minified = minify(fin.read(), cssmin) fout.write(minified) # otherwise, just copy the file else: self.message('Including file with score {}: {}'.format(score, source_path), msglevel, level+1) shutil.copy2(source_path, dest_path)
python
def copy_dir(self, source, dest, level=0): '''Copies the static files from one directory to another. If this command is run, we assume the user wants to overwrite any existing files.''' encoding = settings.DEFAULT_CHARSET or 'utf8' msglevel = 2 if level == 0 else 3 self.message('Directory: {}'.format(source), msglevel, level) # create a directory for this app if not os.path.exists(dest): self.message('Creating directory: {}'.format(dest), msglevel, level+1) os.mkdir(dest) # go through the files in this app for fname in os.listdir(source): source_path = os.path.join(source, fname) dest_path = os.path.join(dest, fname) ext = os.path.splitext(fname)[1].lower() # get the score for this file score = 0 for rule in self.rules: score += rule.match(fname, level, TYPE_DIRECTORY if os.path.isdir(source_path) else TYPE_FILE) # if score is not above zero, we skip this file if score <= 0: self.message('Skipping file with score {}: {}'.format(score, source_path), msglevel, level+1) continue ### if we get here, we need to copy the file ### # if a directory, recurse to it if os.path.isdir(source_path): self.message('Creating directory with score {}: {}'.format(score, source_path), msglevel, level+1) # create it in the destination and recurse if not os.path.exists(dest_path): os.mkdir(dest_path) elif not os.path.isdir(dest_path): # could be a file or link os.unlink(dest_path) os.mkdir(dest_path) self.copy_dir(source_path, dest_path, level+1) # if a regular Javscript file, run through the static file processors (scripts group) elif ext == '.js' and not self.options.get('no_minify') and jsmin: self.message('Including and minifying file with score {}: {}'.format(score, source_path), msglevel, level+1) with open(source_path, encoding=encoding) as fin: with open(dest_path, 'w', encoding=encoding) as fout: minified = minify(fin.read(), jsmin) fout.write(minified) # if a CSS file, run through the static file processors (styles group) elif ext == '.css' and not self.options.get('no_minify') and cssmin: self.message('Including and minifying file with score {}: {}'.format(score, source_path), msglevel, level+1) with open(source_path, encoding=encoding) as fin: with open(dest_path, 'w', encoding=encoding) as fout: minified = minify(fin.read(), cssmin) fout.write(minified) # otherwise, just copy the file else: self.message('Including file with score {}: {}'.format(score, source_path), msglevel, level+1) shutil.copy2(source_path, dest_path)
[ "def", "copy_dir", "(", "self", ",", "source", ",", "dest", ",", "level", "=", "0", ")", ":", "encoding", "=", "settings", ".", "DEFAULT_CHARSET", "or", "'utf8'", "msglevel", "=", "2", "if", "level", "==", "0", "else", "3", "self", ".", "message", "(", "'Directory: {}'", ".", "format", "(", "source", ")", ",", "msglevel", ",", "level", ")", "# create a directory for this app", "if", "not", "os", ".", "path", ".", "exists", "(", "dest", ")", ":", "self", ".", "message", "(", "'Creating directory: {}'", ".", "format", "(", "dest", ")", ",", "msglevel", ",", "level", "+", "1", ")", "os", ".", "mkdir", "(", "dest", ")", "# go through the files in this app", "for", "fname", "in", "os", ".", "listdir", "(", "source", ")", ":", "source_path", "=", "os", ".", "path", ".", "join", "(", "source", ",", "fname", ")", "dest_path", "=", "os", ".", "path", ".", "join", "(", "dest", ",", "fname", ")", "ext", "=", "os", ".", "path", ".", "splitext", "(", "fname", ")", "[", "1", "]", ".", "lower", "(", ")", "# get the score for this file", "score", "=", "0", "for", "rule", "in", "self", ".", "rules", ":", "score", "+=", "rule", ".", "match", "(", "fname", ",", "level", ",", "TYPE_DIRECTORY", "if", "os", ".", "path", ".", "isdir", "(", "source_path", ")", "else", "TYPE_FILE", ")", "# if score is not above zero, we skip this file", "if", "score", "<=", "0", ":", "self", ".", "message", "(", "'Skipping file with score {}: {}'", ".", "format", "(", "score", ",", "source_path", ")", ",", "msglevel", ",", "level", "+", "1", ")", "continue", "### if we get here, we need to copy the file ###", "# if a directory, recurse to it", "if", "os", ".", "path", ".", "isdir", "(", "source_path", ")", ":", "self", ".", "message", "(", "'Creating directory with score {}: {}'", ".", "format", "(", "score", ",", "source_path", ")", ",", "msglevel", ",", "level", "+", "1", ")", "# create it in the destination and recurse", "if", "not", "os", ".", "path", ".", "exists", "(", "dest_path", ")", ":", "os", ".", "mkdir", "(", "dest_path", ")", "elif", "not", "os", ".", "path", ".", "isdir", "(", "dest_path", ")", ":", "# could be a file or link", "os", ".", "unlink", "(", "dest_path", ")", "os", ".", "mkdir", "(", "dest_path", ")", "self", ".", "copy_dir", "(", "source_path", ",", "dest_path", ",", "level", "+", "1", ")", "# if a regular Javscript file, run through the static file processors (scripts group)", "elif", "ext", "==", "'.js'", "and", "not", "self", ".", "options", ".", "get", "(", "'no_minify'", ")", "and", "jsmin", ":", "self", ".", "message", "(", "'Including and minifying file with score {}: {}'", ".", "format", "(", "score", ",", "source_path", ")", ",", "msglevel", ",", "level", "+", "1", ")", "with", "open", "(", "source_path", ",", "encoding", "=", "encoding", ")", "as", "fin", ":", "with", "open", "(", "dest_path", ",", "'w'", ",", "encoding", "=", "encoding", ")", "as", "fout", ":", "minified", "=", "minify", "(", "fin", ".", "read", "(", ")", ",", "jsmin", ")", "fout", ".", "write", "(", "minified", ")", "# if a CSS file, run through the static file processors (styles group)", "elif", "ext", "==", "'.css'", "and", "not", "self", ".", "options", ".", "get", "(", "'no_minify'", ")", "and", "cssmin", ":", "self", ".", "message", "(", "'Including and minifying file with score {}: {}'", ".", "format", "(", "score", ",", "source_path", ")", ",", "msglevel", ",", "level", "+", "1", ")", "with", "open", "(", "source_path", ",", "encoding", "=", "encoding", ")", "as", "fin", ":", "with", "open", "(", "dest_path", ",", "'w'", ",", "encoding", "=", "encoding", ")", "as", "fout", ":", "minified", "=", "minify", "(", "fin", ".", "read", "(", ")", ",", "cssmin", ")", "fout", ".", "write", "(", "minified", ")", "# otherwise, just copy the file", "else", ":", "self", ".", "message", "(", "'Including file with score {}: {}'", ".", "format", "(", "score", ",", "source_path", ")", ",", "msglevel", ",", "level", "+", "1", ")", "shutil", ".", "copy2", "(", "source_path", ",", "dest_path", ")" ]
Copies the static files from one directory to another. If this command is run, we assume the user wants to overwrite any existing files.
[ "Copies", "the", "static", "files", "from", "one", "directory", "to", "another", ".", "If", "this", "command", "is", "run", "we", "assume", "the", "user", "wants", "to", "overwrite", "any", "existing", "files", "." ]
train
https://github.com/doconix/django-mako-plus/blob/a90f9b4af19e5fa9f83452989cdcaed21569a181/django_mako_plus/management/commands/dmp_collectstatic.py#L168-L228
doconix/django-mako-plus
django_mako_plus/templatetags/django_mako_plus.py
dmp_include
def dmp_include(context, template_name, def_name=None, **kwargs): ''' Includes a DMP (Mako) template into a normal django template. context: automatically provided template_name: specified as "app/template" def_name: optional block to render within the template Example: {% load django_mako_plus %} {% dmp_include "homepage/bsnav_dj.html" %} or {% dmp_include "homepage/bsnav_dj.html" "blockname" %} ''' dmp = apps.get_app_config('django_mako_plus') template = dmp.engine.get_template(template_name) dmpcontext = context.flatten() dmpcontext.update(kwargs) return mark_safe(template.render( context=dmpcontext, request=context.get('request'), def_name=def_name ))
python
def dmp_include(context, template_name, def_name=None, **kwargs): ''' Includes a DMP (Mako) template into a normal django template. context: automatically provided template_name: specified as "app/template" def_name: optional block to render within the template Example: {% load django_mako_plus %} {% dmp_include "homepage/bsnav_dj.html" %} or {% dmp_include "homepage/bsnav_dj.html" "blockname" %} ''' dmp = apps.get_app_config('django_mako_plus') template = dmp.engine.get_template(template_name) dmpcontext = context.flatten() dmpcontext.update(kwargs) return mark_safe(template.render( context=dmpcontext, request=context.get('request'), def_name=def_name ))
[ "def", "dmp_include", "(", "context", ",", "template_name", ",", "def_name", "=", "None", ",", "*", "*", "kwargs", ")", ":", "dmp", "=", "apps", ".", "get_app_config", "(", "'django_mako_plus'", ")", "template", "=", "dmp", ".", "engine", ".", "get_template", "(", "template_name", ")", "dmpcontext", "=", "context", ".", "flatten", "(", ")", "dmpcontext", ".", "update", "(", "kwargs", ")", "return", "mark_safe", "(", "template", ".", "render", "(", "context", "=", "dmpcontext", ",", "request", "=", "context", ".", "get", "(", "'request'", ")", ",", "def_name", "=", "def_name", ")", ")" ]
Includes a DMP (Mako) template into a normal django template. context: automatically provided template_name: specified as "app/template" def_name: optional block to render within the template Example: {% load django_mako_plus %} {% dmp_include "homepage/bsnav_dj.html" %} or {% dmp_include "homepage/bsnav_dj.html" "blockname" %}
[ "Includes", "a", "DMP", "(", "Mako", ")", "template", "into", "a", "normal", "django", "template", "." ]
train
https://github.com/doconix/django-mako-plus/blob/a90f9b4af19e5fa9f83452989cdcaed21569a181/django_mako_plus/templatetags/django_mako_plus.py#L17-L39
doconix/django-mako-plus
django_mako_plus/router/data.py
RoutingData.render
def render(self, template, context=None, def_name=None, subdir='templates', content_type=None, status=None, charset=None): '''App-specific render function that renders templates in the *current app*, attached to the request for convenience''' template_adapter = self.get_template_loader(subdir).get_template(template) return getattr(template_adapter, 'render_to_response')(context=context, request=self.request, def_name=def_name, content_type=content_type, status=status, charset=charset)
python
def render(self, template, context=None, def_name=None, subdir='templates', content_type=None, status=None, charset=None): '''App-specific render function that renders templates in the *current app*, attached to the request for convenience''' template_adapter = self.get_template_loader(subdir).get_template(template) return getattr(template_adapter, 'render_to_response')(context=context, request=self.request, def_name=def_name, content_type=content_type, status=status, charset=charset)
[ "def", "render", "(", "self", ",", "template", ",", "context", "=", "None", ",", "def_name", "=", "None", ",", "subdir", "=", "'templates'", ",", "content_type", "=", "None", ",", "status", "=", "None", ",", "charset", "=", "None", ")", ":", "template_adapter", "=", "self", ".", "get_template_loader", "(", "subdir", ")", ".", "get_template", "(", "template", ")", "return", "getattr", "(", "template_adapter", ",", "'render_to_response'", ")", "(", "context", "=", "context", ",", "request", "=", "self", ".", "request", ",", "def_name", "=", "def_name", ",", "content_type", "=", "content_type", ",", "status", "=", "status", ",", "charset", "=", "charset", ")" ]
App-specific render function that renders templates in the *current app*, attached to the request for convenience
[ "App", "-", "specific", "render", "function", "that", "renders", "templates", "in", "the", "*", "current", "app", "*", "attached", "to", "the", "request", "for", "convenience" ]
train
https://github.com/doconix/django-mako-plus/blob/a90f9b4af19e5fa9f83452989cdcaed21569a181/django_mako_plus/router/data.py#L87-L90
doconix/django-mako-plus
django_mako_plus/router/data.py
RoutingData.render_to_string
def render_to_string(self, template, context=None, def_name=None, subdir='templates'): '''App-specific render function that renders templates in the *current app*, attached to the request for convenience''' template_adapter = self.get_template_loader(subdir).get_template(template) return getattr(template_adapter, 'render')(context=context, request=self.request, def_name=def_name)
python
def render_to_string(self, template, context=None, def_name=None, subdir='templates'): '''App-specific render function that renders templates in the *current app*, attached to the request for convenience''' template_adapter = self.get_template_loader(subdir).get_template(template) return getattr(template_adapter, 'render')(context=context, request=self.request, def_name=def_name)
[ "def", "render_to_string", "(", "self", ",", "template", ",", "context", "=", "None", ",", "def_name", "=", "None", ",", "subdir", "=", "'templates'", ")", ":", "template_adapter", "=", "self", ".", "get_template_loader", "(", "subdir", ")", ".", "get_template", "(", "template", ")", "return", "getattr", "(", "template_adapter", ",", "'render'", ")", "(", "context", "=", "context", ",", "request", "=", "self", ".", "request", ",", "def_name", "=", "def_name", ")" ]
App-specific render function that renders templates in the *current app*, attached to the request for convenience
[ "App", "-", "specific", "render", "function", "that", "renders", "templates", "in", "the", "*", "current", "app", "*", "attached", "to", "the", "request", "for", "convenience" ]
train
https://github.com/doconix/django-mako-plus/blob/a90f9b4af19e5fa9f83452989cdcaed21569a181/django_mako_plus/router/data.py#L93-L96
doconix/django-mako-plus
django_mako_plus/router/data.py
RoutingData.get_template_loader
def get_template_loader(self, subdir='templates'): '''App-specific function to get the current app's template loader''' if self.request is None: raise ValueError("this method can only be called after the view middleware is run. Check that `django_mako_plus.middleware` is in MIDDLEWARE.") dmp = apps.get_app_config('django_mako_plus') return dmp.engine.get_template_loader(self.app, subdir)
python
def get_template_loader(self, subdir='templates'): '''App-specific function to get the current app's template loader''' if self.request is None: raise ValueError("this method can only be called after the view middleware is run. Check that `django_mako_plus.middleware` is in MIDDLEWARE.") dmp = apps.get_app_config('django_mako_plus') return dmp.engine.get_template_loader(self.app, subdir)
[ "def", "get_template_loader", "(", "self", ",", "subdir", "=", "'templates'", ")", ":", "if", "self", ".", "request", "is", "None", ":", "raise", "ValueError", "(", "\"this method can only be called after the view middleware is run. Check that `django_mako_plus.middleware` is in MIDDLEWARE.\"", ")", "dmp", "=", "apps", ".", "get_app_config", "(", "'django_mako_plus'", ")", "return", "dmp", ".", "engine", ".", "get_template_loader", "(", "self", ".", "app", ",", "subdir", ")" ]
App-specific function to get the current app's template loader
[ "App", "-", "specific", "function", "to", "get", "the", "current", "app", "s", "template", "loader" ]
train
https://github.com/doconix/django-mako-plus/blob/a90f9b4af19e5fa9f83452989cdcaed21569a181/django_mako_plus/router/data.py#L104-L109
doconix/django-mako-plus
django_mako_plus/apps.py
Config.ready
def ready(self): '''Called by Django when the app is ready for use.''' # set up the options self.options = {} self.options.update(DEFAULT_OPTIONS) for template_engine in settings.TEMPLATES: if template_engine.get('BACKEND', '').startswith('django_mako_plus'): self.options.update(template_engine.get('OPTIONS', {})) # dmp-enabled apps registry self.registration_lock = threading.RLock() self.registered_apps = {} # init the template engine self.engine = engines['django_mako_plus'] # default imports on every compiled template self.template_imports = [ 'import django_mako_plus', 'import django.utils.html', # used in template.py ] self.template_imports.extend(self.options['DEFAULT_TEMPLATE_IMPORTS']) # initialize the list of providers ProviderRun.initialize_providers() # set up the parameter converters (can't import until apps are set up) from .converter.base import ParameterConverter ParameterConverter._sort_converters(app_ready=True)
python
def ready(self): '''Called by Django when the app is ready for use.''' # set up the options self.options = {} self.options.update(DEFAULT_OPTIONS) for template_engine in settings.TEMPLATES: if template_engine.get('BACKEND', '').startswith('django_mako_plus'): self.options.update(template_engine.get('OPTIONS', {})) # dmp-enabled apps registry self.registration_lock = threading.RLock() self.registered_apps = {} # init the template engine self.engine = engines['django_mako_plus'] # default imports on every compiled template self.template_imports = [ 'import django_mako_plus', 'import django.utils.html', # used in template.py ] self.template_imports.extend(self.options['DEFAULT_TEMPLATE_IMPORTS']) # initialize the list of providers ProviderRun.initialize_providers() # set up the parameter converters (can't import until apps are set up) from .converter.base import ParameterConverter ParameterConverter._sort_converters(app_ready=True)
[ "def", "ready", "(", "self", ")", ":", "# set up the options", "self", ".", "options", "=", "{", "}", "self", ".", "options", ".", "update", "(", "DEFAULT_OPTIONS", ")", "for", "template_engine", "in", "settings", ".", "TEMPLATES", ":", "if", "template_engine", ".", "get", "(", "'BACKEND'", ",", "''", ")", ".", "startswith", "(", "'django_mako_plus'", ")", ":", "self", ".", "options", ".", "update", "(", "template_engine", ".", "get", "(", "'OPTIONS'", ",", "{", "}", ")", ")", "# dmp-enabled apps registry", "self", ".", "registration_lock", "=", "threading", ".", "RLock", "(", ")", "self", ".", "registered_apps", "=", "{", "}", "# init the template engine", "self", ".", "engine", "=", "engines", "[", "'django_mako_plus'", "]", "# default imports on every compiled template", "self", ".", "template_imports", "=", "[", "'import django_mako_plus'", ",", "'import django.utils.html'", ",", "# used in template.py", "]", "self", ".", "template_imports", ".", "extend", "(", "self", ".", "options", "[", "'DEFAULT_TEMPLATE_IMPORTS'", "]", ")", "# initialize the list of providers", "ProviderRun", ".", "initialize_providers", "(", ")", "# set up the parameter converters (can't import until apps are set up)", "from", ".", "converter", ".", "base", "import", "ParameterConverter", "ParameterConverter", ".", "_sort_converters", "(", "app_ready", "=", "True", ")" ]
Called by Django when the app is ready for use.
[ "Called", "by", "Django", "when", "the", "app", "is", "ready", "for", "use", "." ]
train
https://github.com/doconix/django-mako-plus/blob/a90f9b4af19e5fa9f83452989cdcaed21569a181/django_mako_plus/apps.py#L18-L46
doconix/django-mako-plus
django_mako_plus/apps.py
Config.register_app
def register_app(self, app=None): ''' Registers an app as a "DMP-enabled" app. Normally, DMP does this automatically when included in urls.py. If app is None, the DEFAULT_APP is registered. ''' app = app or self.options['DEFAULT_APP'] if not app: raise ImproperlyConfigured('An app name is required because DEFAULT_APP is empty - please use a ' 'valid app name or set the DEFAULT_APP in settings') if isinstance(app, str): app = apps.get_app_config(app) # since this only runs at startup, this lock doesn't affect performance with self.registration_lock: # short circuit if already registered if app.name in self.registered_apps: return # first time for this app, so add to our dictionary self.registered_apps[app.name] = app # set up the template, script, and style renderers # these create and cache just by accessing them self.engine.get_template_loader(app, 'templates', create=True) self.engine.get_template_loader(app, 'scripts', create=True) self.engine.get_template_loader(app, 'styles', create=True) # send the registration signal if self.options['SIGNALS']: dmp_signal_register_app.send(sender=self, app_config=app)
python
def register_app(self, app=None): ''' Registers an app as a "DMP-enabled" app. Normally, DMP does this automatically when included in urls.py. If app is None, the DEFAULT_APP is registered. ''' app = app or self.options['DEFAULT_APP'] if not app: raise ImproperlyConfigured('An app name is required because DEFAULT_APP is empty - please use a ' 'valid app name or set the DEFAULT_APP in settings') if isinstance(app, str): app = apps.get_app_config(app) # since this only runs at startup, this lock doesn't affect performance with self.registration_lock: # short circuit if already registered if app.name in self.registered_apps: return # first time for this app, so add to our dictionary self.registered_apps[app.name] = app # set up the template, script, and style renderers # these create and cache just by accessing them self.engine.get_template_loader(app, 'templates', create=True) self.engine.get_template_loader(app, 'scripts', create=True) self.engine.get_template_loader(app, 'styles', create=True) # send the registration signal if self.options['SIGNALS']: dmp_signal_register_app.send(sender=self, app_config=app)
[ "def", "register_app", "(", "self", ",", "app", "=", "None", ")", ":", "app", "=", "app", "or", "self", ".", "options", "[", "'DEFAULT_APP'", "]", "if", "not", "app", ":", "raise", "ImproperlyConfigured", "(", "'An app name is required because DEFAULT_APP is empty - please use a '", "'valid app name or set the DEFAULT_APP in settings'", ")", "if", "isinstance", "(", "app", ",", "str", ")", ":", "app", "=", "apps", ".", "get_app_config", "(", "app", ")", "# since this only runs at startup, this lock doesn't affect performance", "with", "self", ".", "registration_lock", ":", "# short circuit if already registered", "if", "app", ".", "name", "in", "self", ".", "registered_apps", ":", "return", "# first time for this app, so add to our dictionary", "self", ".", "registered_apps", "[", "app", ".", "name", "]", "=", "app", "# set up the template, script, and style renderers", "# these create and cache just by accessing them", "self", ".", "engine", ".", "get_template_loader", "(", "app", ",", "'templates'", ",", "create", "=", "True", ")", "self", ".", "engine", ".", "get_template_loader", "(", "app", ",", "'scripts'", ",", "create", "=", "True", ")", "self", ".", "engine", ".", "get_template_loader", "(", "app", ",", "'styles'", ",", "create", "=", "True", ")", "# send the registration signal", "if", "self", ".", "options", "[", "'SIGNALS'", "]", ":", "dmp_signal_register_app", ".", "send", "(", "sender", "=", "self", ",", "app_config", "=", "app", ")" ]
Registers an app as a "DMP-enabled" app. Normally, DMP does this automatically when included in urls.py. If app is None, the DEFAULT_APP is registered.
[ "Registers", "an", "app", "as", "a", "DMP", "-", "enabled", "app", ".", "Normally", "DMP", "does", "this", "automatically", "when", "included", "in", "urls", ".", "py", "." ]
train
https://github.com/doconix/django-mako-plus/blob/a90f9b4af19e5fa9f83452989cdcaed21569a181/django_mako_plus/apps.py#L49-L80
doconix/django-mako-plus
django_mako_plus/apps.py
Config.is_registered_app
def is_registered_app(self, app): '''Returns true if the given app/app name is registered with DMP''' if app is None: return False if isinstance(app, AppConfig): app = app.name return app in self.registered_apps
python
def is_registered_app(self, app): '''Returns true if the given app/app name is registered with DMP''' if app is None: return False if isinstance(app, AppConfig): app = app.name return app in self.registered_apps
[ "def", "is_registered_app", "(", "self", ",", "app", ")", ":", "if", "app", "is", "None", ":", "return", "False", "if", "isinstance", "(", "app", ",", "AppConfig", ")", ":", "app", "=", "app", ".", "name", "return", "app", "in", "self", ".", "registered_apps" ]
Returns true if the given app/app name is registered with DMP
[ "Returns", "true", "if", "the", "given", "app", "/", "app", "name", "is", "registered", "with", "DMP" ]
train
https://github.com/doconix/django-mako-plus/blob/a90f9b4af19e5fa9f83452989cdcaed21569a181/django_mako_plus/apps.py#L88-L94
doconix/django-mako-plus
django_mako_plus/router/urlparams.py
URLParamList.get
def get(self, idx, default=''): '''Returns the element at idx, or default if idx is beyond the length of the list''' # if the index is beyond the length of the list, return '' if isinstance(idx, int) and (idx >= len(self) or idx < -1 * len(self)): return default # else do the regular list function (for int, slice types, etc.) return super().__getitem__(idx)
python
def get(self, idx, default=''): '''Returns the element at idx, or default if idx is beyond the length of the list''' # if the index is beyond the length of the list, return '' if isinstance(idx, int) and (idx >= len(self) or idx < -1 * len(self)): return default # else do the regular list function (for int, slice types, etc.) return super().__getitem__(idx)
[ "def", "get", "(", "self", ",", "idx", ",", "default", "=", "''", ")", ":", "# if the index is beyond the length of the list, return ''", "if", "isinstance", "(", "idx", ",", "int", ")", "and", "(", "idx", ">=", "len", "(", "self", ")", "or", "idx", "<", "-", "1", "*", "len", "(", "self", ")", ")", ":", "return", "default", "# else do the regular list function (for int, slice types, etc.)", "return", "super", "(", ")", ".", "__getitem__", "(", "idx", ")" ]
Returns the element at idx, or default if idx is beyond the length of the list
[ "Returns", "the", "element", "at", "idx", "or", "default", "if", "idx", "is", "beyond", "the", "length", "of", "the", "list" ]
train
https://github.com/doconix/django-mako-plus/blob/a90f9b4af19e5fa9f83452989cdcaed21569a181/django_mako_plus/router/urlparams.py#L16-L22
doconix/django-mako-plus
django_mako_plus/converter/converters.py
convert_int
def convert_int(value, parameter): ''' Converts to int or float: '', '-', None convert to parameter default Anything else uses int() or float() constructor ''' value = _check_default(value, parameter, ( '', '-', None )) if value is None or isinstance(value, int): return value try: return int(value) except Exception as e: raise ValueError(str(e))
python
def convert_int(value, parameter): ''' Converts to int or float: '', '-', None convert to parameter default Anything else uses int() or float() constructor ''' value = _check_default(value, parameter, ( '', '-', None )) if value is None or isinstance(value, int): return value try: return int(value) except Exception as e: raise ValueError(str(e))
[ "def", "convert_int", "(", "value", ",", "parameter", ")", ":", "value", "=", "_check_default", "(", "value", ",", "parameter", ",", "(", "''", ",", "'-'", ",", "None", ")", ")", "if", "value", "is", "None", "or", "isinstance", "(", "value", ",", "int", ")", ":", "return", "value", "try", ":", "return", "int", "(", "value", ")", "except", "Exception", "as", "e", ":", "raise", "ValueError", "(", "str", "(", "e", ")", ")" ]
Converts to int or float: '', '-', None convert to parameter default Anything else uses int() or float() constructor
[ "Converts", "to", "int", "or", "float", ":", "-", "None", "convert", "to", "parameter", "default", "Anything", "else", "uses", "int", "()", "or", "float", "()", "constructor" ]
train
https://github.com/doconix/django-mako-plus/blob/a90f9b4af19e5fa9f83452989cdcaed21569a181/django_mako_plus/converter/converters.py#L41-L53
doconix/django-mako-plus
django_mako_plus/converter/converters.py
convert_float
def convert_float(value, parameter): ''' Converts to int or float: '', '-', None convert to parameter default Anything else uses int() or float() constructor ''' value = _check_default(value, parameter, ( '', '-', None )) if value is None or isinstance(value, float): return value try: return float(value) except Exception as e: raise ValueError(str(e))
python
def convert_float(value, parameter): ''' Converts to int or float: '', '-', None convert to parameter default Anything else uses int() or float() constructor ''' value = _check_default(value, parameter, ( '', '-', None )) if value is None or isinstance(value, float): return value try: return float(value) except Exception as e: raise ValueError(str(e))
[ "def", "convert_float", "(", "value", ",", "parameter", ")", ":", "value", "=", "_check_default", "(", "value", ",", "parameter", ",", "(", "''", ",", "'-'", ",", "None", ")", ")", "if", "value", "is", "None", "or", "isinstance", "(", "value", ",", "float", ")", ":", "return", "value", "try", ":", "return", "float", "(", "value", ")", "except", "Exception", "as", "e", ":", "raise", "ValueError", "(", "str", "(", "e", ")", ")" ]
Converts to int or float: '', '-', None convert to parameter default Anything else uses int() or float() constructor
[ "Converts", "to", "int", "or", "float", ":", "-", "None", "convert", "to", "parameter", "default", "Anything", "else", "uses", "int", "()", "or", "float", "()", "constructor" ]
train
https://github.com/doconix/django-mako-plus/blob/a90f9b4af19e5fa9f83452989cdcaed21569a181/django_mako_plus/converter/converters.py#L59-L71
doconix/django-mako-plus
django_mako_plus/converter/converters.py
convert_decimal
def convert_decimal(value, parameter): ''' Converts to decimal.Decimal: '', '-', None convert to parameter default Anything else uses Decimal constructor ''' value = _check_default(value, parameter, ( '', '-', None )) if value is None or isinstance(value, decimal.Decimal): return value try: return decimal.Decimal(value) except Exception as e: raise ValueError(str(e))
python
def convert_decimal(value, parameter): ''' Converts to decimal.Decimal: '', '-', None convert to parameter default Anything else uses Decimal constructor ''' value = _check_default(value, parameter, ( '', '-', None )) if value is None or isinstance(value, decimal.Decimal): return value try: return decimal.Decimal(value) except Exception as e: raise ValueError(str(e))
[ "def", "convert_decimal", "(", "value", ",", "parameter", ")", ":", "value", "=", "_check_default", "(", "value", ",", "parameter", ",", "(", "''", ",", "'-'", ",", "None", ")", ")", "if", "value", "is", "None", "or", "isinstance", "(", "value", ",", "decimal", ".", "Decimal", ")", ":", "return", "value", "try", ":", "return", "decimal", ".", "Decimal", "(", "value", ")", "except", "Exception", "as", "e", ":", "raise", "ValueError", "(", "str", "(", "e", ")", ")" ]
Converts to decimal.Decimal: '', '-', None convert to parameter default Anything else uses Decimal constructor
[ "Converts", "to", "decimal", ".", "Decimal", ":", "-", "None", "convert", "to", "parameter", "default", "Anything", "else", "uses", "Decimal", "constructor" ]
train
https://github.com/doconix/django-mako-plus/blob/a90f9b4af19e5fa9f83452989cdcaed21569a181/django_mako_plus/converter/converters.py#L77-L89
doconix/django-mako-plus
django_mako_plus/converter/converters.py
convert_boolean
def convert_boolean(value, parameter, default=False): ''' Converts to boolean (only the first char of the value is used): '', '-', None convert to parameter default 'f', 'F', '0', False always convert to False Anything else converts to True. ''' value = _check_default(value, parameter, ( '', '-', None )) if isinstance(value, bool): return value if isinstance(value, str) and len(value) > 0: value = value[0] return value not in ( 'f', 'F', '0', False, None )
python
def convert_boolean(value, parameter, default=False): ''' Converts to boolean (only the first char of the value is used): '', '-', None convert to parameter default 'f', 'F', '0', False always convert to False Anything else converts to True. ''' value = _check_default(value, parameter, ( '', '-', None )) if isinstance(value, bool): return value if isinstance(value, str) and len(value) > 0: value = value[0] return value not in ( 'f', 'F', '0', False, None )
[ "def", "convert_boolean", "(", "value", ",", "parameter", ",", "default", "=", "False", ")", ":", "value", "=", "_check_default", "(", "value", ",", "parameter", ",", "(", "''", ",", "'-'", ",", "None", ")", ")", "if", "isinstance", "(", "value", ",", "bool", ")", ":", "return", "value", "if", "isinstance", "(", "value", ",", "str", ")", "and", "len", "(", "value", ")", ">", "0", ":", "value", "=", "value", "[", "0", "]", "return", "value", "not", "in", "(", "'f'", ",", "'F'", ",", "'0'", ",", "False", ",", "None", ")" ]
Converts to boolean (only the first char of the value is used): '', '-', None convert to parameter default 'f', 'F', '0', False always convert to False Anything else converts to True.
[ "Converts", "to", "boolean", "(", "only", "the", "first", "char", "of", "the", "value", "is", "used", ")", ":", "-", "None", "convert", "to", "parameter", "default", "f", "F", "0", "False", "always", "convert", "to", "False", "Anything", "else", "converts", "to", "True", "." ]
train
https://github.com/doconix/django-mako-plus/blob/a90f9b4af19e5fa9f83452989cdcaed21569a181/django_mako_plus/converter/converters.py#L95-L107
doconix/django-mako-plus
django_mako_plus/converter/converters.py
convert_datetime
def convert_datetime(value, parameter): ''' Converts to datetime.datetime: '', '-', None convert to parameter default The first matching format in settings.DATETIME_INPUT_FORMATS converts to datetime ''' value = _check_default(value, parameter, ( '', '-', None )) if value is None or isinstance(value, datetime.datetime): return value for fmt in settings.DATETIME_INPUT_FORMATS: try: return datetime.datetime.strptime(value, fmt) except (ValueError, TypeError): continue raise ValueError("`{}` does not match a format in settings.DATETIME_INPUT_FORMATS".format(value))
python
def convert_datetime(value, parameter): ''' Converts to datetime.datetime: '', '-', None convert to parameter default The first matching format in settings.DATETIME_INPUT_FORMATS converts to datetime ''' value = _check_default(value, parameter, ( '', '-', None )) if value is None or isinstance(value, datetime.datetime): return value for fmt in settings.DATETIME_INPUT_FORMATS: try: return datetime.datetime.strptime(value, fmt) except (ValueError, TypeError): continue raise ValueError("`{}` does not match a format in settings.DATETIME_INPUT_FORMATS".format(value))
[ "def", "convert_datetime", "(", "value", ",", "parameter", ")", ":", "value", "=", "_check_default", "(", "value", ",", "parameter", ",", "(", "''", ",", "'-'", ",", "None", ")", ")", "if", "value", "is", "None", "or", "isinstance", "(", "value", ",", "datetime", ".", "datetime", ")", ":", "return", "value", "for", "fmt", "in", "settings", ".", "DATETIME_INPUT_FORMATS", ":", "try", ":", "return", "datetime", ".", "datetime", ".", "strptime", "(", "value", ",", "fmt", ")", "except", "(", "ValueError", ",", "TypeError", ")", ":", "continue", "raise", "ValueError", "(", "\"`{}` does not match a format in settings.DATETIME_INPUT_FORMATS\"", ".", "format", "(", "value", ")", ")" ]
Converts to datetime.datetime: '', '-', None convert to parameter default The first matching format in settings.DATETIME_INPUT_FORMATS converts to datetime
[ "Converts", "to", "datetime", ".", "datetime", ":", "-", "None", "convert", "to", "parameter", "default", "The", "first", "matching", "format", "in", "settings", ".", "DATETIME_INPUT_FORMATS", "converts", "to", "datetime" ]
train
https://github.com/doconix/django-mako-plus/blob/a90f9b4af19e5fa9f83452989cdcaed21569a181/django_mako_plus/converter/converters.py#L113-L127
doconix/django-mako-plus
django_mako_plus/converter/converters.py
convert_date
def convert_date(value, parameter): ''' Converts to datetime.date: '', '-', None convert to parameter default The first matching format in settings.DATE_INPUT_FORMATS converts to datetime ''' value = _check_default(value, parameter, ( '', '-', None )) if value is None or isinstance(value, datetime.date): return value for fmt in settings.DATE_INPUT_FORMATS: try: return datetime.datetime.strptime(value, fmt).date() except (ValueError, TypeError): continue raise ValueError("`{}` does not match a format in settings.DATE_INPUT_FORMATS".format(value))
python
def convert_date(value, parameter): ''' Converts to datetime.date: '', '-', None convert to parameter default The first matching format in settings.DATE_INPUT_FORMATS converts to datetime ''' value = _check_default(value, parameter, ( '', '-', None )) if value is None or isinstance(value, datetime.date): return value for fmt in settings.DATE_INPUT_FORMATS: try: return datetime.datetime.strptime(value, fmt).date() except (ValueError, TypeError): continue raise ValueError("`{}` does not match a format in settings.DATE_INPUT_FORMATS".format(value))
[ "def", "convert_date", "(", "value", ",", "parameter", ")", ":", "value", "=", "_check_default", "(", "value", ",", "parameter", ",", "(", "''", ",", "'-'", ",", "None", ")", ")", "if", "value", "is", "None", "or", "isinstance", "(", "value", ",", "datetime", ".", "date", ")", ":", "return", "value", "for", "fmt", "in", "settings", ".", "DATE_INPUT_FORMATS", ":", "try", ":", "return", "datetime", ".", "datetime", ".", "strptime", "(", "value", ",", "fmt", ")", ".", "date", "(", ")", "except", "(", "ValueError", ",", "TypeError", ")", ":", "continue", "raise", "ValueError", "(", "\"`{}` does not match a format in settings.DATE_INPUT_FORMATS\"", ".", "format", "(", "value", ")", ")" ]
Converts to datetime.date: '', '-', None convert to parameter default The first matching format in settings.DATE_INPUT_FORMATS converts to datetime
[ "Converts", "to", "datetime", ".", "date", ":", "-", "None", "convert", "to", "parameter", "default", "The", "first", "matching", "format", "in", "settings", ".", "DATE_INPUT_FORMATS", "converts", "to", "datetime" ]
train
https://github.com/doconix/django-mako-plus/blob/a90f9b4af19e5fa9f83452989cdcaed21569a181/django_mako_plus/converter/converters.py#L133-L147
doconix/django-mako-plus
django_mako_plus/converter/converters.py
convert_id_to_model
def convert_id_to_model(value, parameter): ''' Converts to a Model object. '', '-', '0', None convert to parameter default Anything else is assumed an object id and sent to `.get(id=value)`. ''' value = _check_default(value, parameter, ( '', '-', '0', None )) if isinstance(value, (int, str)): # only convert if we have the id try: return parameter.type.objects.get(id=value) except (MultipleObjectsReturned, ObjectDoesNotExist) as e: raise ValueError(str(e)) return value
python
def convert_id_to_model(value, parameter): ''' Converts to a Model object. '', '-', '0', None convert to parameter default Anything else is assumed an object id and sent to `.get(id=value)`. ''' value = _check_default(value, parameter, ( '', '-', '0', None )) if isinstance(value, (int, str)): # only convert if we have the id try: return parameter.type.objects.get(id=value) except (MultipleObjectsReturned, ObjectDoesNotExist) as e: raise ValueError(str(e)) return value
[ "def", "convert_id_to_model", "(", "value", ",", "parameter", ")", ":", "value", "=", "_check_default", "(", "value", ",", "parameter", ",", "(", "''", ",", "'-'", ",", "'0'", ",", "None", ")", ")", "if", "isinstance", "(", "value", ",", "(", "int", ",", "str", ")", ")", ":", "# only convert if we have the id", "try", ":", "return", "parameter", ".", "type", ".", "objects", ".", "get", "(", "id", "=", "value", ")", "except", "(", "MultipleObjectsReturned", ",", "ObjectDoesNotExist", ")", "as", "e", ":", "raise", "ValueError", "(", "str", "(", "e", ")", ")", "return", "value" ]
Converts to a Model object. '', '-', '0', None convert to parameter default Anything else is assumed an object id and sent to `.get(id=value)`.
[ "Converts", "to", "a", "Model", "object", ".", "-", "0", "None", "convert", "to", "parameter", "default", "Anything", "else", "is", "assumed", "an", "object", "id", "and", "sent", "to", ".", "get", "(", "id", "=", "value", ")", "." ]
train
https://github.com/doconix/django-mako-plus/blob/a90f9b4af19e5fa9f83452989cdcaed21569a181/django_mako_plus/converter/converters.py#L153-L165
doconix/django-mako-plus
django_mako_plus/converter/converters.py
_check_default
def _check_default(value, parameter, default_chars): '''Returns the default if the value is "empty"''' # not using a set here because it fails when value is unhashable if value in default_chars: if parameter.default is inspect.Parameter.empty: raise ValueError('Value was empty, but no default value is given in view function for parameter: {} ({})'.format(parameter.position, parameter.name)) return parameter.default return value
python
def _check_default(value, parameter, default_chars): '''Returns the default if the value is "empty"''' # not using a set here because it fails when value is unhashable if value in default_chars: if parameter.default is inspect.Parameter.empty: raise ValueError('Value was empty, but no default value is given in view function for parameter: {} ({})'.format(parameter.position, parameter.name)) return parameter.default return value
[ "def", "_check_default", "(", "value", ",", "parameter", ",", "default_chars", ")", ":", "# not using a set here because it fails when value is unhashable", "if", "value", "in", "default_chars", ":", "if", "parameter", ".", "default", "is", "inspect", ".", "Parameter", ".", "empty", ":", "raise", "ValueError", "(", "'Value was empty, but no default value is given in view function for parameter: {} ({})'", ".", "format", "(", "parameter", ".", "position", ",", "parameter", ".", "name", ")", ")", "return", "parameter", ".", "default", "return", "value" ]
Returns the default if the value is "empty"
[ "Returns", "the", "default", "if", "the", "value", "is", "empty" ]
train
https://github.com/doconix/django-mako-plus/blob/a90f9b4af19e5fa9f83452989cdcaed21569a181/django_mako_plus/converter/converters.py#L171-L178
doconix/django-mako-plus
django_mako_plus/converter/decorators.py
parameter_converter
def parameter_converter(*convert_types): ''' Decorator that denotes a function as a url parameter converter. ''' def inner(func): for ct in convert_types: ParameterConverter._register_converter(func, ct) return func return inner
python
def parameter_converter(*convert_types): ''' Decorator that denotes a function as a url parameter converter. ''' def inner(func): for ct in convert_types: ParameterConverter._register_converter(func, ct) return func return inner
[ "def", "parameter_converter", "(", "*", "convert_types", ")", ":", "def", "inner", "(", "func", ")", ":", "for", "ct", "in", "convert_types", ":", "ParameterConverter", ".", "_register_converter", "(", "func", ",", "ct", ")", "return", "func", "return", "inner" ]
Decorator that denotes a function as a url parameter converter.
[ "Decorator", "that", "denotes", "a", "function", "as", "a", "url", "parameter", "converter", "." ]
train
https://github.com/doconix/django-mako-plus/blob/a90f9b4af19e5fa9f83452989cdcaed21569a181/django_mako_plus/converter/decorators.py#L5-L13
insilichem/ommprotocol
ommprotocol/md.py
protocol
def protocol(handler, cfg): """ Run all the stages in protocol Parameters ---------- handler : SystemHandler Container of initial conditions of simulation cfg : dict Imported YAML file. """ # Stages if 'stages' not in cfg: raise ValueError('Protocol must include stages of simulation') pos, vel, box = handler.positions, handler.velocities, handler.box stages = cfg.pop('stages') for stage_options in stages: options = DEFAULT_OPTIONS.copy() options.update(cfg) stage_system_options = prepare_system_options(stage_options) options.update(stage_options) options['system_options'].update(stage_system_options) stage = Stage(handler, positions=pos, velocities=vel, box=box, total_stages=len(stages), **options) pos, vel, box = stage.run() del stage
python
def protocol(handler, cfg): """ Run all the stages in protocol Parameters ---------- handler : SystemHandler Container of initial conditions of simulation cfg : dict Imported YAML file. """ # Stages if 'stages' not in cfg: raise ValueError('Protocol must include stages of simulation') pos, vel, box = handler.positions, handler.velocities, handler.box stages = cfg.pop('stages') for stage_options in stages: options = DEFAULT_OPTIONS.copy() options.update(cfg) stage_system_options = prepare_system_options(stage_options) options.update(stage_options) options['system_options'].update(stage_system_options) stage = Stage(handler, positions=pos, velocities=vel, box=box, total_stages=len(stages), **options) pos, vel, box = stage.run() del stage
[ "def", "protocol", "(", "handler", ",", "cfg", ")", ":", "# Stages", "if", "'stages'", "not", "in", "cfg", ":", "raise", "ValueError", "(", "'Protocol must include stages of simulation'", ")", "pos", ",", "vel", ",", "box", "=", "handler", ".", "positions", ",", "handler", ".", "velocities", ",", "handler", ".", "box", "stages", "=", "cfg", ".", "pop", "(", "'stages'", ")", "for", "stage_options", "in", "stages", ":", "options", "=", "DEFAULT_OPTIONS", ".", "copy", "(", ")", "options", ".", "update", "(", "cfg", ")", "stage_system_options", "=", "prepare_system_options", "(", "stage_options", ")", "options", ".", "update", "(", "stage_options", ")", "options", "[", "'system_options'", "]", ".", "update", "(", "stage_system_options", ")", "stage", "=", "Stage", "(", "handler", ",", "positions", "=", "pos", ",", "velocities", "=", "vel", ",", "box", "=", "box", ",", "total_stages", "=", "len", "(", "stages", ")", ",", "*", "*", "options", ")", "pos", ",", "vel", ",", "box", "=", "stage", ".", "run", "(", ")", "del", "stage" ]
Run all the stages in protocol Parameters ---------- handler : SystemHandler Container of initial conditions of simulation cfg : dict Imported YAML file.
[ "Run", "all", "the", "stages", "in", "protocol" ]
train
https://github.com/insilichem/ommprotocol/blob/7283fddba7203e5ac3542fdab41fc1279d3b444e/ommprotocol/md.py#L65-L92
insilichem/ommprotocol
ommprotocol/md.py
Stage.run
def run(self): """ Launch MD simulation, which may consist of: 1. Optional minimization 2. Actual MD simulation, with n steps. This method also handles reporters. Returns ------- positions, velocities : unit.Quantity([natoms, 3]) Position, velocity of each atom in the system box : unit.Quantity([1, 3]) Periodic conditions box vectors """ if self.verbose: status = '#{}'.format(self.stage_index) if self.total_stages is not None: status += '/{}'.format(self.total_stages) status += ': {}'.format(self.name) pieces = [] if self.restrained_atoms is not None: pieces.append('restrained {}'.format(self.restrained_atoms)) if self.constrained_atoms is not None: pieces.append('constrained {}'.format(self.constrained_atoms)) if self.distance_restrained_atoms is not None: pieces.append('distance restrained for {} atom pairs'.format(len(self.distance_restrained_atoms))) if pieces: status += ' [{}]'.format(', '.join(pieces)) logger.info(status) # Add forces self.apply_restraints() self.apply_constraints() if self.barostat: self.apply_barostat() if self.minimization: if self.verbose: logger.info(' Minimizing...') self.minimize() uses_pbc = self.system.usesPeriodicBoundaryConditions() if self.steps: # Stdout progress if self.report and self.progress_reporter not in self.simulation.reporters: self.simulation.reporters.append(self.progress_reporter) # Log report if self.report and self.log_reporter not in self.simulation.reporters: self.simulation.reporters.append(self.log_reporter) # Trajectory / movie files if self.trajectory and self.trajectory_reporter not in self.simulation.reporters: self.simulation.reporters.append(self.trajectory_reporter) # Checkpoint or restart files if self.restart and self.restart_reporter not in self.simulation.reporters: self.simulation.reporters.append(self.restart_reporter) # MD simulation if self.verbose: pbc = 'PBC ' if uses_pbc else '' conditions = 'NPT' if self.barostat else 'NVT' logger.info(' Running {}MD for {} steps @ {}K, {}'.format(pbc, self.steps, self.temperature, conditions)) with self.handle_exceptions(): self.simulate() if self.save_state_at_end: path = self.new_filename(suffix='.state') self.simulation.saveState(path) # Save and return state state = self.simulation.context.getState(getPositions=True, getVelocities=True, enforcePeriodicBox=uses_pbc) return state.getPositions(), state.getVelocities(), state.getPeriodicBoxVectors()
python
def run(self): """ Launch MD simulation, which may consist of: 1. Optional minimization 2. Actual MD simulation, with n steps. This method also handles reporters. Returns ------- positions, velocities : unit.Quantity([natoms, 3]) Position, velocity of each atom in the system box : unit.Quantity([1, 3]) Periodic conditions box vectors """ if self.verbose: status = '#{}'.format(self.stage_index) if self.total_stages is not None: status += '/{}'.format(self.total_stages) status += ': {}'.format(self.name) pieces = [] if self.restrained_atoms is not None: pieces.append('restrained {}'.format(self.restrained_atoms)) if self.constrained_atoms is not None: pieces.append('constrained {}'.format(self.constrained_atoms)) if self.distance_restrained_atoms is not None: pieces.append('distance restrained for {} atom pairs'.format(len(self.distance_restrained_atoms))) if pieces: status += ' [{}]'.format(', '.join(pieces)) logger.info(status) # Add forces self.apply_restraints() self.apply_constraints() if self.barostat: self.apply_barostat() if self.minimization: if self.verbose: logger.info(' Minimizing...') self.minimize() uses_pbc = self.system.usesPeriodicBoundaryConditions() if self.steps: # Stdout progress if self.report and self.progress_reporter not in self.simulation.reporters: self.simulation.reporters.append(self.progress_reporter) # Log report if self.report and self.log_reporter not in self.simulation.reporters: self.simulation.reporters.append(self.log_reporter) # Trajectory / movie files if self.trajectory and self.trajectory_reporter not in self.simulation.reporters: self.simulation.reporters.append(self.trajectory_reporter) # Checkpoint or restart files if self.restart and self.restart_reporter not in self.simulation.reporters: self.simulation.reporters.append(self.restart_reporter) # MD simulation if self.verbose: pbc = 'PBC ' if uses_pbc else '' conditions = 'NPT' if self.barostat else 'NVT' logger.info(' Running {}MD for {} steps @ {}K, {}'.format(pbc, self.steps, self.temperature, conditions)) with self.handle_exceptions(): self.simulate() if self.save_state_at_end: path = self.new_filename(suffix='.state') self.simulation.saveState(path) # Save and return state state = self.simulation.context.getState(getPositions=True, getVelocities=True, enforcePeriodicBox=uses_pbc) return state.getPositions(), state.getVelocities(), state.getPeriodicBoxVectors()
[ "def", "run", "(", "self", ")", ":", "if", "self", ".", "verbose", ":", "status", "=", "'#{}'", ".", "format", "(", "self", ".", "stage_index", ")", "if", "self", ".", "total_stages", "is", "not", "None", ":", "status", "+=", "'/{}'", ".", "format", "(", "self", ".", "total_stages", ")", "status", "+=", "': {}'", ".", "format", "(", "self", ".", "name", ")", "pieces", "=", "[", "]", "if", "self", ".", "restrained_atoms", "is", "not", "None", ":", "pieces", ".", "append", "(", "'restrained {}'", ".", "format", "(", "self", ".", "restrained_atoms", ")", ")", "if", "self", ".", "constrained_atoms", "is", "not", "None", ":", "pieces", ".", "append", "(", "'constrained {}'", ".", "format", "(", "self", ".", "constrained_atoms", ")", ")", "if", "self", ".", "distance_restrained_atoms", "is", "not", "None", ":", "pieces", ".", "append", "(", "'distance restrained for {} atom pairs'", ".", "format", "(", "len", "(", "self", ".", "distance_restrained_atoms", ")", ")", ")", "if", "pieces", ":", "status", "+=", "' [{}]'", ".", "format", "(", "', '", ".", "join", "(", "pieces", ")", ")", "logger", ".", "info", "(", "status", ")", "# Add forces", "self", ".", "apply_restraints", "(", ")", "self", ".", "apply_constraints", "(", ")", "if", "self", ".", "barostat", ":", "self", ".", "apply_barostat", "(", ")", "if", "self", ".", "minimization", ":", "if", "self", ".", "verbose", ":", "logger", ".", "info", "(", "' Minimizing...'", ")", "self", ".", "minimize", "(", ")", "uses_pbc", "=", "self", ".", "system", ".", "usesPeriodicBoundaryConditions", "(", ")", "if", "self", ".", "steps", ":", "# Stdout progress", "if", "self", ".", "report", "and", "self", ".", "progress_reporter", "not", "in", "self", ".", "simulation", ".", "reporters", ":", "self", ".", "simulation", ".", "reporters", ".", "append", "(", "self", ".", "progress_reporter", ")", "# Log report", "if", "self", ".", "report", "and", "self", ".", "log_reporter", "not", "in", "self", ".", "simulation", ".", "reporters", ":", "self", ".", "simulation", ".", "reporters", ".", "append", "(", "self", ".", "log_reporter", ")", "# Trajectory / movie files", "if", "self", ".", "trajectory", "and", "self", ".", "trajectory_reporter", "not", "in", "self", ".", "simulation", ".", "reporters", ":", "self", ".", "simulation", ".", "reporters", ".", "append", "(", "self", ".", "trajectory_reporter", ")", "# Checkpoint or restart files", "if", "self", ".", "restart", "and", "self", ".", "restart_reporter", "not", "in", "self", ".", "simulation", ".", "reporters", ":", "self", ".", "simulation", ".", "reporters", ".", "append", "(", "self", ".", "restart_reporter", ")", "# MD simulation", "if", "self", ".", "verbose", ":", "pbc", "=", "'PBC '", "if", "uses_pbc", "else", "''", "conditions", "=", "'NPT'", "if", "self", ".", "barostat", "else", "'NVT'", "logger", ".", "info", "(", "' Running {}MD for {} steps @ {}K, {}'", ".", "format", "(", "pbc", ",", "self", ".", "steps", ",", "self", ".", "temperature", ",", "conditions", ")", ")", "with", "self", ".", "handle_exceptions", "(", ")", ":", "self", ".", "simulate", "(", ")", "if", "self", ".", "save_state_at_end", ":", "path", "=", "self", ".", "new_filename", "(", "suffix", "=", "'.state'", ")", "self", ".", "simulation", ".", "saveState", "(", "path", ")", "# Save and return state", "state", "=", "self", ".", "simulation", ".", "context", ".", "getState", "(", "getPositions", "=", "True", ",", "getVelocities", "=", "True", ",", "enforcePeriodicBox", "=", "uses_pbc", ")", "return", "state", ".", "getPositions", "(", ")", ",", "state", ".", "getVelocities", "(", ")", ",", "state", ".", "getPeriodicBoxVectors", "(", ")" ]
Launch MD simulation, which may consist of: 1. Optional minimization 2. Actual MD simulation, with n steps. This method also handles reporters. Returns ------- positions, velocities : unit.Quantity([natoms, 3]) Position, velocity of each atom in the system box : unit.Quantity([1, 3]) Periodic conditions box vectors
[ "Launch", "MD", "simulation", "which", "may", "consist", "of", ":", "1", ".", "Optional", "minimization", "2", ".", "Actual", "MD", "simulation", "with", "n", "steps", "." ]
train
https://github.com/insilichem/ommprotocol/blob/7283fddba7203e5ac3542fdab41fc1279d3b444e/ommprotocol/md.py#L272-L352
insilichem/ommprotocol
ommprotocol/md.py
Stage.minimize
def minimize(self, tolerance=None, max_iterations=None): """ Minimize energy of the system until meeting `tolerance` or performing `max_iterations`. """ if tolerance is None: tolerance = self.minimization_tolerance if max_iterations is None: max_iterations = self.minimization_max_iterations self.simulation.minimizeEnergy(tolerance * u.kilojoules_per_mole, max_iterations)
python
def minimize(self, tolerance=None, max_iterations=None): """ Minimize energy of the system until meeting `tolerance` or performing `max_iterations`. """ if tolerance is None: tolerance = self.minimization_tolerance if max_iterations is None: max_iterations = self.minimization_max_iterations self.simulation.minimizeEnergy(tolerance * u.kilojoules_per_mole, max_iterations)
[ "def", "minimize", "(", "self", ",", "tolerance", "=", "None", ",", "max_iterations", "=", "None", ")", ":", "if", "tolerance", "is", "None", ":", "tolerance", "=", "self", ".", "minimization_tolerance", "if", "max_iterations", "is", "None", ":", "max_iterations", "=", "self", ".", "minimization_max_iterations", "self", ".", "simulation", ".", "minimizeEnergy", "(", "tolerance", "*", "u", ".", "kilojoules_per_mole", ",", "max_iterations", ")" ]
Minimize energy of the system until meeting `tolerance` or performing `max_iterations`.
[ "Minimize", "energy", "of", "the", "system", "until", "meeting", "tolerance", "or", "performing", "max_iterations", "." ]
train
https://github.com/insilichem/ommprotocol/blob/7283fddba7203e5ac3542fdab41fc1279d3b444e/ommprotocol/md.py#L354-L363
insilichem/ommprotocol
ommprotocol/md.py
Stage.simulate
def simulate(self, steps=None): """ Advance simulation n steps """ if steps is None: steps = self.steps self.simulation.step(steps)
python
def simulate(self, steps=None): """ Advance simulation n steps """ if steps is None: steps = self.steps self.simulation.step(steps)
[ "def", "simulate", "(", "self", ",", "steps", "=", "None", ")", ":", "if", "steps", "is", "None", ":", "steps", "=", "self", ".", "steps", "self", ".", "simulation", ".", "step", "(", "steps", ")" ]
Advance simulation n steps
[ "Advance", "simulation", "n", "steps" ]
train
https://github.com/insilichem/ommprotocol/blob/7283fddba7203e5ac3542fdab41fc1279d3b444e/ommprotocol/md.py#L365-L371
insilichem/ommprotocol
ommprotocol/md.py
Stage.restraint_force
def restraint_force(self, indices=None, strength=5.0): """ Force that restrains atoms to fix their positions, while allowing tiny movement to resolve severe clashes and so on. Returns ------- force : simtk.openmm.CustomExternalForce A custom force to restrain the selected atoms """ if self.system.usesPeriodicBoundaryConditions(): expression = 'k*periodicdistance(x, y, z, x0, y0, z0)^2' else: expression = 'k*((x-x0)^2 + (y-y0)^2 + (z-z0)^2)' force = mm.CustomExternalForce(expression) force.addGlobalParameter('k', strength*u.kilocalories_per_mole/u.angstroms**2) force.addPerParticleParameter('x0') force.addPerParticleParameter('y0') force.addPerParticleParameter('z0') positions = self.positions if self.positions is not None else self.handler.positions if indices is None: indices = range(self.handler.topology.getNumAtoms()) for i, index in enumerate(indices): force.addParticle(i, positions[index].value_in_unit(u.nanometers)) return force
python
def restraint_force(self, indices=None, strength=5.0): """ Force that restrains atoms to fix their positions, while allowing tiny movement to resolve severe clashes and so on. Returns ------- force : simtk.openmm.CustomExternalForce A custom force to restrain the selected atoms """ if self.system.usesPeriodicBoundaryConditions(): expression = 'k*periodicdistance(x, y, z, x0, y0, z0)^2' else: expression = 'k*((x-x0)^2 + (y-y0)^2 + (z-z0)^2)' force = mm.CustomExternalForce(expression) force.addGlobalParameter('k', strength*u.kilocalories_per_mole/u.angstroms**2) force.addPerParticleParameter('x0') force.addPerParticleParameter('y0') force.addPerParticleParameter('z0') positions = self.positions if self.positions is not None else self.handler.positions if indices is None: indices = range(self.handler.topology.getNumAtoms()) for i, index in enumerate(indices): force.addParticle(i, positions[index].value_in_unit(u.nanometers)) return force
[ "def", "restraint_force", "(", "self", ",", "indices", "=", "None", ",", "strength", "=", "5.0", ")", ":", "if", "self", ".", "system", ".", "usesPeriodicBoundaryConditions", "(", ")", ":", "expression", "=", "'k*periodicdistance(x, y, z, x0, y0, z0)^2'", "else", ":", "expression", "=", "'k*((x-x0)^2 + (y-y0)^2 + (z-z0)^2)'", "force", "=", "mm", ".", "CustomExternalForce", "(", "expression", ")", "force", ".", "addGlobalParameter", "(", "'k'", ",", "strength", "*", "u", ".", "kilocalories_per_mole", "/", "u", ".", "angstroms", "**", "2", ")", "force", ".", "addPerParticleParameter", "(", "'x0'", ")", "force", ".", "addPerParticleParameter", "(", "'y0'", ")", "force", ".", "addPerParticleParameter", "(", "'z0'", ")", "positions", "=", "self", ".", "positions", "if", "self", ".", "positions", "is", "not", "None", "else", "self", ".", "handler", ".", "positions", "if", "indices", "is", "None", ":", "indices", "=", "range", "(", "self", ".", "handler", ".", "topology", ".", "getNumAtoms", "(", ")", ")", "for", "i", ",", "index", "in", "enumerate", "(", "indices", ")", ":", "force", ".", "addParticle", "(", "i", ",", "positions", "[", "index", "]", ".", "value_in_unit", "(", "u", ".", "nanometers", ")", ")", "return", "force" ]
Force that restrains atoms to fix their positions, while allowing tiny movement to resolve severe clashes and so on. Returns ------- force : simtk.openmm.CustomExternalForce A custom force to restrain the selected atoms
[ "Force", "that", "restrains", "atoms", "to", "fix", "their", "positions", "while", "allowing", "tiny", "movement", "to", "resolve", "severe", "clashes", "and", "so", "on", "." ]
train
https://github.com/insilichem/ommprotocol/blob/7283fddba7203e5ac3542fdab41fc1279d3b444e/ommprotocol/md.py#L511-L535
insilichem/ommprotocol
ommprotocol/md.py
Stage.distance_restraint_force
def distance_restraint_force(self, atoms, distances, strengths): """ Parameters ---------- atoms : tuple of tuple of int or str Pair of atom indices to be restrained, with shape (n, 2), like ((a1, a2), (a3, a4)). Items can be str compatible with MDTraj DSL. distances : tuple of float Equilibrium distances for each pair strengths : tuple of float Force constant for each pair """ system = self.system force = mm.HarmonicBondForce() force.setUsesPeriodicBoundaryConditions(self.system.usesPeriodicBoundaryConditions()) for pair, distance, strength in zip(atoms, distances, strengths): indices = [] for atom in pair: if isinstance(atom, str): index = self.subset(atom) if len(index) != 1: raise ValueError('Distance restraint for selection `{}` returns != 1 atom!: {}' .format(atom, index)) indices.append(int(index[0])) elif isinstance(atom, (int, float)): indices.append(int(atom)) else: raise ValueError('Distance restraint atoms must be int or str DSL selections') if distance == 'current': pos = self.positions or system.positions distance = np.linalg.norm(pos[indices[0]] - pos[indices[1]]) force.addBond(indices[0], indices[1], distance*u.nanometers, strength*u.kilocalories_per_mole/u.angstroms**2) return force
python
def distance_restraint_force(self, atoms, distances, strengths): """ Parameters ---------- atoms : tuple of tuple of int or str Pair of atom indices to be restrained, with shape (n, 2), like ((a1, a2), (a3, a4)). Items can be str compatible with MDTraj DSL. distances : tuple of float Equilibrium distances for each pair strengths : tuple of float Force constant for each pair """ system = self.system force = mm.HarmonicBondForce() force.setUsesPeriodicBoundaryConditions(self.system.usesPeriodicBoundaryConditions()) for pair, distance, strength in zip(atoms, distances, strengths): indices = [] for atom in pair: if isinstance(atom, str): index = self.subset(atom) if len(index) != 1: raise ValueError('Distance restraint for selection `{}` returns != 1 atom!: {}' .format(atom, index)) indices.append(int(index[0])) elif isinstance(atom, (int, float)): indices.append(int(atom)) else: raise ValueError('Distance restraint atoms must be int or str DSL selections') if distance == 'current': pos = self.positions or system.positions distance = np.linalg.norm(pos[indices[0]] - pos[indices[1]]) force.addBond(indices[0], indices[1], distance*u.nanometers, strength*u.kilocalories_per_mole/u.angstroms**2) return force
[ "def", "distance_restraint_force", "(", "self", ",", "atoms", ",", "distances", ",", "strengths", ")", ":", "system", "=", "self", ".", "system", "force", "=", "mm", ".", "HarmonicBondForce", "(", ")", "force", ".", "setUsesPeriodicBoundaryConditions", "(", "self", ".", "system", ".", "usesPeriodicBoundaryConditions", "(", ")", ")", "for", "pair", ",", "distance", ",", "strength", "in", "zip", "(", "atoms", ",", "distances", ",", "strengths", ")", ":", "indices", "=", "[", "]", "for", "atom", "in", "pair", ":", "if", "isinstance", "(", "atom", ",", "str", ")", ":", "index", "=", "self", ".", "subset", "(", "atom", ")", "if", "len", "(", "index", ")", "!=", "1", ":", "raise", "ValueError", "(", "'Distance restraint for selection `{}` returns != 1 atom!: {}'", ".", "format", "(", "atom", ",", "index", ")", ")", "indices", ".", "append", "(", "int", "(", "index", "[", "0", "]", ")", ")", "elif", "isinstance", "(", "atom", ",", "(", "int", ",", "float", ")", ")", ":", "indices", ".", "append", "(", "int", "(", "atom", ")", ")", "else", ":", "raise", "ValueError", "(", "'Distance restraint atoms must be int or str DSL selections'", ")", "if", "distance", "==", "'current'", ":", "pos", "=", "self", ".", "positions", "or", "system", ".", "positions", "distance", "=", "np", ".", "linalg", ".", "norm", "(", "pos", "[", "indices", "[", "0", "]", "]", "-", "pos", "[", "indices", "[", "1", "]", "]", ")", "force", ".", "addBond", "(", "indices", "[", "0", "]", ",", "indices", "[", "1", "]", ",", "distance", "*", "u", ".", "nanometers", ",", "strength", "*", "u", ".", "kilocalories_per_mole", "/", "u", ".", "angstroms", "**", "2", ")", "return", "force" ]
Parameters ---------- atoms : tuple of tuple of int or str Pair of atom indices to be restrained, with shape (n, 2), like ((a1, a2), (a3, a4)). Items can be str compatible with MDTraj DSL. distances : tuple of float Equilibrium distances for each pair strengths : tuple of float Force constant for each pair
[ "Parameters", "----------", "atoms", ":", "tuple", "of", "tuple", "of", "int", "or", "str", "Pair", "of", "atom", "indices", "to", "be", "restrained", "with", "shape", "(", "n", "2", ")", "like", "((", "a1", "a2", ")", "(", "a3", "a4", "))", ".", "Items", "can", "be", "str", "compatible", "with", "MDTraj", "DSL", ".", "distances", ":", "tuple", "of", "float", "Equilibrium", "distances", "for", "each", "pair", "strengths", ":", "tuple", "of", "float", "Force", "constant", "for", "each", "pair" ]
train
https://github.com/insilichem/ommprotocol/blob/7283fddba7203e5ac3542fdab41fc1279d3b444e/ommprotocol/md.py#L537-L571
insilichem/ommprotocol
ommprotocol/md.py
Stage.subset
def subset(self, selector): """ Returns a list of atom indices corresponding to a MDTraj DSL query. Also will accept list of numbers, which will be coerced to int and returned. """ if isinstance(selector, (list, tuple)): return map(int, selector) selector = SELECTORS.get(selector, selector) mdtop = MDTrajTopology.from_openmm(self.handler.topology) return mdtop.select(selector)
python
def subset(self, selector): """ Returns a list of atom indices corresponding to a MDTraj DSL query. Also will accept list of numbers, which will be coerced to int and returned. """ if isinstance(selector, (list, tuple)): return map(int, selector) selector = SELECTORS.get(selector, selector) mdtop = MDTrajTopology.from_openmm(self.handler.topology) return mdtop.select(selector)
[ "def", "subset", "(", "self", ",", "selector", ")", ":", "if", "isinstance", "(", "selector", ",", "(", "list", ",", "tuple", ")", ")", ":", "return", "map", "(", "int", ",", "selector", ")", "selector", "=", "SELECTORS", ".", "get", "(", "selector", ",", "selector", ")", "mdtop", "=", "MDTrajTopology", ".", "from_openmm", "(", "self", ".", "handler", ".", "topology", ")", "return", "mdtop", ".", "select", "(", "selector", ")" ]
Returns a list of atom indices corresponding to a MDTraj DSL query. Also will accept list of numbers, which will be coerced to int and returned.
[ "Returns", "a", "list", "of", "atom", "indices", "corresponding", "to", "a", "MDTraj", "DSL", "query", ".", "Also", "will", "accept", "list", "of", "numbers", "which", "will", "be", "coerced", "to", "int", "and", "returned", "." ]
train
https://github.com/insilichem/ommprotocol/blob/7283fddba7203e5ac3542fdab41fc1279d3b444e/ommprotocol/md.py#L573-L583
insilichem/ommprotocol
ommprotocol/md.py
Stage.handle_exceptions
def handle_exceptions(self, verbose=True): """ Handle Ctrl+C and accidental exceptions and attempt to save the current state of the simulation """ try: yield except (KeyboardInterrupt, Exception) as ex: if not self.attempt_rescue: raise ex if isinstance(ex, KeyboardInterrupt): reraise = False answer = timed_input('\n\nDo you want to save current state? (y/N): ') if answer and answer.lower() not in ('y', 'yes'): if verbose: sys.exit('Ok, bye!') else: reraise = True logger.error('\n\nAn error occurred: %s', ex) if verbose: logger.info('Saving state...') try: self.backup_simulation() except Exception: if verbose: logger.error('FAILED :(') else: if verbose: logger.info('SUCCESS!') finally: if reraise: raise ex sys.exit()
python
def handle_exceptions(self, verbose=True): """ Handle Ctrl+C and accidental exceptions and attempt to save the current state of the simulation """ try: yield except (KeyboardInterrupt, Exception) as ex: if not self.attempt_rescue: raise ex if isinstance(ex, KeyboardInterrupt): reraise = False answer = timed_input('\n\nDo you want to save current state? (y/N): ') if answer and answer.lower() not in ('y', 'yes'): if verbose: sys.exit('Ok, bye!') else: reraise = True logger.error('\n\nAn error occurred: %s', ex) if verbose: logger.info('Saving state...') try: self.backup_simulation() except Exception: if verbose: logger.error('FAILED :(') else: if verbose: logger.info('SUCCESS!') finally: if reraise: raise ex sys.exit()
[ "def", "handle_exceptions", "(", "self", ",", "verbose", "=", "True", ")", ":", "try", ":", "yield", "except", "(", "KeyboardInterrupt", ",", "Exception", ")", "as", "ex", ":", "if", "not", "self", ".", "attempt_rescue", ":", "raise", "ex", "if", "isinstance", "(", "ex", ",", "KeyboardInterrupt", ")", ":", "reraise", "=", "False", "answer", "=", "timed_input", "(", "'\\n\\nDo you want to save current state? (y/N): '", ")", "if", "answer", "and", "answer", ".", "lower", "(", ")", "not", "in", "(", "'y'", ",", "'yes'", ")", ":", "if", "verbose", ":", "sys", ".", "exit", "(", "'Ok, bye!'", ")", "else", ":", "reraise", "=", "True", "logger", ".", "error", "(", "'\\n\\nAn error occurred: %s'", ",", "ex", ")", "if", "verbose", ":", "logger", ".", "info", "(", "'Saving state...'", ")", "try", ":", "self", ".", "backup_simulation", "(", ")", "except", "Exception", ":", "if", "verbose", ":", "logger", ".", "error", "(", "'FAILED :('", ")", "else", ":", "if", "verbose", ":", "logger", ".", "info", "(", "'SUCCESS!'", ")", "finally", ":", "if", "reraise", ":", "raise", "ex", "sys", ".", "exit", "(", ")" ]
Handle Ctrl+C and accidental exceptions and attempt to save the current state of the simulation
[ "Handle", "Ctrl", "+", "C", "and", "accidental", "exceptions", "and", "attempt", "to", "save", "the", "current", "state", "of", "the", "simulation" ]
train
https://github.com/insilichem/ommprotocol/blob/7283fddba7203e5ac3542fdab41fc1279d3b444e/ommprotocol/md.py#L694-L726
insilichem/ommprotocol
ommprotocol/md.py
Stage.backup_simulation
def backup_simulation(self): """ Creates an emergency report run, .state included """ path = self.new_filename(suffix='_emergency.state') self.simulation.saveState(path) uses_pbc = self.system.usesPeriodicBoundaryConditions() state_kw = dict(getPositions=True, getVelocities=True, getForces=True, enforcePeriodicBox=uses_pbc, getParameters=True, getEnergy=True) state = self.simulation.context.getState(**state_kw) for reporter in self.simulation.reporters: if not isinstance(reporter, app.StateDataReporter): reporter.report(self.simulation, state)
python
def backup_simulation(self): """ Creates an emergency report run, .state included """ path = self.new_filename(suffix='_emergency.state') self.simulation.saveState(path) uses_pbc = self.system.usesPeriodicBoundaryConditions() state_kw = dict(getPositions=True, getVelocities=True, getForces=True, enforcePeriodicBox=uses_pbc, getParameters=True, getEnergy=True) state = self.simulation.context.getState(**state_kw) for reporter in self.simulation.reporters: if not isinstance(reporter, app.StateDataReporter): reporter.report(self.simulation, state)
[ "def", "backup_simulation", "(", "self", ")", ":", "path", "=", "self", ".", "new_filename", "(", "suffix", "=", "'_emergency.state'", ")", "self", ".", "simulation", ".", "saveState", "(", "path", ")", "uses_pbc", "=", "self", ".", "system", ".", "usesPeriodicBoundaryConditions", "(", ")", "state_kw", "=", "dict", "(", "getPositions", "=", "True", ",", "getVelocities", "=", "True", ",", "getForces", "=", "True", ",", "enforcePeriodicBox", "=", "uses_pbc", ",", "getParameters", "=", "True", ",", "getEnergy", "=", "True", ")", "state", "=", "self", ".", "simulation", ".", "context", ".", "getState", "(", "*", "*", "state_kw", ")", "for", "reporter", "in", "self", ".", "simulation", ".", "reporters", ":", "if", "not", "isinstance", "(", "reporter", ",", "app", ".", "StateDataReporter", ")", ":", "reporter", ".", "report", "(", "self", ".", "simulation", ",", "state", ")" ]
Creates an emergency report run, .state included
[ "Creates", "an", "emergency", "report", "run", ".", "state", "included" ]
train
https://github.com/insilichem/ommprotocol/blob/7283fddba7203e5ac3542fdab41fc1279d3b444e/ommprotocol/md.py#L728-L741
insilichem/ommprotocol
ommprotocol/io.py
prepare_input
def prepare_input(argv=None): """ Get, parse and prepare input file. """ p = ArgumentParser(description='InsiliChem Ommprotocol: ' 'easy to deploy MD protocols for OpenMM') p.add_argument('input', metavar='INPUT FILE', type=extant_file, help='YAML input file') p.add_argument('--version', action='version', version='%(prog)s v{}'.format(__version__)) p.add_argument('-c', '--check', action='store_true', help='Validate input file only') args = p.parse_args(argv if argv else sys.argv[1:]) jinja_env = jinja2.Environment(trim_blocks=True, lstrip_blocks=True) # Load config file with open(args.input) as f: rendered = jinja_env.from_string(f.read()).render() cfg = yaml.load(rendered, Loader=YamlLoader) # Paths and dirs from .md import SYSTEM_OPTIONS cfg['_path'] = os.path.abspath(args.input) cfg['system_options'] = prepare_system_options(cfg, defaults=SYSTEM_OPTIONS) cfg['outputpath'] = sanitize_path_for_file(cfg.get('outputpath', '.'), args.input) if not args.check: with ignored_exceptions(OSError): os.makedirs(cfg['outputpath']) handler = prepare_handler(cfg) return handler, cfg, args
python
def prepare_input(argv=None): """ Get, parse and prepare input file. """ p = ArgumentParser(description='InsiliChem Ommprotocol: ' 'easy to deploy MD protocols for OpenMM') p.add_argument('input', metavar='INPUT FILE', type=extant_file, help='YAML input file') p.add_argument('--version', action='version', version='%(prog)s v{}'.format(__version__)) p.add_argument('-c', '--check', action='store_true', help='Validate input file only') args = p.parse_args(argv if argv else sys.argv[1:]) jinja_env = jinja2.Environment(trim_blocks=True, lstrip_blocks=True) # Load config file with open(args.input) as f: rendered = jinja_env.from_string(f.read()).render() cfg = yaml.load(rendered, Loader=YamlLoader) # Paths and dirs from .md import SYSTEM_OPTIONS cfg['_path'] = os.path.abspath(args.input) cfg['system_options'] = prepare_system_options(cfg, defaults=SYSTEM_OPTIONS) cfg['outputpath'] = sanitize_path_for_file(cfg.get('outputpath', '.'), args.input) if not args.check: with ignored_exceptions(OSError): os.makedirs(cfg['outputpath']) handler = prepare_handler(cfg) return handler, cfg, args
[ "def", "prepare_input", "(", "argv", "=", "None", ")", ":", "p", "=", "ArgumentParser", "(", "description", "=", "'InsiliChem Ommprotocol: '", "'easy to deploy MD protocols for OpenMM'", ")", "p", ".", "add_argument", "(", "'input'", ",", "metavar", "=", "'INPUT FILE'", ",", "type", "=", "extant_file", ",", "help", "=", "'YAML input file'", ")", "p", ".", "add_argument", "(", "'--version'", ",", "action", "=", "'version'", ",", "version", "=", "'%(prog)s v{}'", ".", "format", "(", "__version__", ")", ")", "p", ".", "add_argument", "(", "'-c'", ",", "'--check'", ",", "action", "=", "'store_true'", ",", "help", "=", "'Validate input file only'", ")", "args", "=", "p", ".", "parse_args", "(", "argv", "if", "argv", "else", "sys", ".", "argv", "[", "1", ":", "]", ")", "jinja_env", "=", "jinja2", ".", "Environment", "(", "trim_blocks", "=", "True", ",", "lstrip_blocks", "=", "True", ")", "# Load config file", "with", "open", "(", "args", ".", "input", ")", "as", "f", ":", "rendered", "=", "jinja_env", ".", "from_string", "(", "f", ".", "read", "(", ")", ")", ".", "render", "(", ")", "cfg", "=", "yaml", ".", "load", "(", "rendered", ",", "Loader", "=", "YamlLoader", ")", "# Paths and dirs", "from", ".", "md", "import", "SYSTEM_OPTIONS", "cfg", "[", "'_path'", "]", "=", "os", ".", "path", ".", "abspath", "(", "args", ".", "input", ")", "cfg", "[", "'system_options'", "]", "=", "prepare_system_options", "(", "cfg", ",", "defaults", "=", "SYSTEM_OPTIONS", ")", "cfg", "[", "'outputpath'", "]", "=", "sanitize_path_for_file", "(", "cfg", ".", "get", "(", "'outputpath'", ",", "'.'", ")", ",", "args", ".", "input", ")", "if", "not", "args", ".", "check", ":", "with", "ignored_exceptions", "(", "OSError", ")", ":", "os", ".", "makedirs", "(", "cfg", "[", "'outputpath'", "]", ")", "handler", "=", "prepare_handler", "(", "cfg", ")", "return", "handler", ",", "cfg", ",", "args" ]
Get, parse and prepare input file.
[ "Get", "parse", "and", "prepare", "input", "file", "." ]
train
https://github.com/insilichem/ommprotocol/blob/7283fddba7203e5ac3542fdab41fc1279d3b444e/ommprotocol/io.py#L883-L913
insilichem/ommprotocol
ommprotocol/io.py
prepare_handler
def prepare_handler(cfg): """ Load all files into single object. """ positions, velocities, box = None, None, None _path = cfg.get('_path', './') forcefield = cfg.pop('forcefield', None) topology_args = sanitize_args_for_file(cfg.pop('topology'), _path) if 'checkpoint' in cfg: restart_args = sanitize_args_for_file(cfg.pop('checkpoint'), _path) restart = Restart.load(*restart_args) positions = restart.positions velocities = restart.velocities box = restart.box if 'positions' in cfg: positions_args = sanitize_args_for_file(cfg.pop('positions'), _path) positions = Positions.load(*positions_args) box = BoxVectors.load(*positions_args) if 'velocities' in cfg: velocities_args = sanitize_args_for_file(cfg.pop('velocities'), _path) velocities = Velocities.load(*velocities_args) if 'box' in cfg: box_args = sanitize_args_for_file(cfg.pop('box'), _path) box = BoxVectors.load(*box_args) options = {} for key in 'positions velocities box forcefield'.split(): value = locals()[key] if value is not None: options[key] = value return SystemHandler.load(*topology_args, **options)
python
def prepare_handler(cfg): """ Load all files into single object. """ positions, velocities, box = None, None, None _path = cfg.get('_path', './') forcefield = cfg.pop('forcefield', None) topology_args = sanitize_args_for_file(cfg.pop('topology'), _path) if 'checkpoint' in cfg: restart_args = sanitize_args_for_file(cfg.pop('checkpoint'), _path) restart = Restart.load(*restart_args) positions = restart.positions velocities = restart.velocities box = restart.box if 'positions' in cfg: positions_args = sanitize_args_for_file(cfg.pop('positions'), _path) positions = Positions.load(*positions_args) box = BoxVectors.load(*positions_args) if 'velocities' in cfg: velocities_args = sanitize_args_for_file(cfg.pop('velocities'), _path) velocities = Velocities.load(*velocities_args) if 'box' in cfg: box_args = sanitize_args_for_file(cfg.pop('box'), _path) box = BoxVectors.load(*box_args) options = {} for key in 'positions velocities box forcefield'.split(): value = locals()[key] if value is not None: options[key] = value return SystemHandler.load(*topology_args, **options)
[ "def", "prepare_handler", "(", "cfg", ")", ":", "positions", ",", "velocities", ",", "box", "=", "None", ",", "None", ",", "None", "_path", "=", "cfg", ".", "get", "(", "'_path'", ",", "'./'", ")", "forcefield", "=", "cfg", ".", "pop", "(", "'forcefield'", ",", "None", ")", "topology_args", "=", "sanitize_args_for_file", "(", "cfg", ".", "pop", "(", "'topology'", ")", ",", "_path", ")", "if", "'checkpoint'", "in", "cfg", ":", "restart_args", "=", "sanitize_args_for_file", "(", "cfg", ".", "pop", "(", "'checkpoint'", ")", ",", "_path", ")", "restart", "=", "Restart", ".", "load", "(", "*", "restart_args", ")", "positions", "=", "restart", ".", "positions", "velocities", "=", "restart", ".", "velocities", "box", "=", "restart", ".", "box", "if", "'positions'", "in", "cfg", ":", "positions_args", "=", "sanitize_args_for_file", "(", "cfg", ".", "pop", "(", "'positions'", ")", ",", "_path", ")", "positions", "=", "Positions", ".", "load", "(", "*", "positions_args", ")", "box", "=", "BoxVectors", ".", "load", "(", "*", "positions_args", ")", "if", "'velocities'", "in", "cfg", ":", "velocities_args", "=", "sanitize_args_for_file", "(", "cfg", ".", "pop", "(", "'velocities'", ")", ",", "_path", ")", "velocities", "=", "Velocities", ".", "load", "(", "*", "velocities_args", ")", "if", "'box'", "in", "cfg", ":", "box_args", "=", "sanitize_args_for_file", "(", "cfg", ".", "pop", "(", "'box'", ")", ",", "_path", ")", "box", "=", "BoxVectors", ".", "load", "(", "*", "box_args", ")", "options", "=", "{", "}", "for", "key", "in", "'positions velocities box forcefield'", ".", "split", "(", ")", ":", "value", "=", "locals", "(", ")", "[", "key", "]", "if", "value", "is", "not", "None", ":", "options", "[", "key", "]", "=", "value", "return", "SystemHandler", ".", "load", "(", "*", "topology_args", ",", "*", "*", "options", ")" ]
Load all files into single object.
[ "Load", "all", "files", "into", "single", "object", "." ]
train
https://github.com/insilichem/ommprotocol/blob/7283fddba7203e5ac3542fdab41fc1279d3b444e/ommprotocol/io.py#L916-L951
insilichem/ommprotocol
ommprotocol/io.py
prepare_system_options
def prepare_system_options(cfg, defaults=None): """ Retrieve and delete (pop) system options from input configuration. """ d = {} if defaults is None else defaults.copy() if 'nonbondedMethod' in cfg: d['nonbondedMethod'] = warned_getattr(openmm_app, cfg.pop('nonbondedMethod'), None) if 'nonbondedCutoff' in cfg: d['nonbondedCutoff'] = cfg.pop('nonbondedCutoff') * u.nanometers if 'constraints' in cfg: d['constraints'] = warned_getattr(openmm_app, cfg.pop('constraints'), None) for key in ['rigidWater', 'ewaldErrorTolerance']: if key in cfg: d[key] = cfg.pop(key) if 'extra_system_options' in cfg: if 'implicitSolvent' in cfg['extra_system_options']: implicit_solvent = warned_getattr( openmm_app, cfg['extra_system_options']['implicitSolvent'], None) cfg['extra_system_options']['implicitSolvent'] = implicit_solvent d.update(cfg.pop('extra_system_options')) return d
python
def prepare_system_options(cfg, defaults=None): """ Retrieve and delete (pop) system options from input configuration. """ d = {} if defaults is None else defaults.copy() if 'nonbondedMethod' in cfg: d['nonbondedMethod'] = warned_getattr(openmm_app, cfg.pop('nonbondedMethod'), None) if 'nonbondedCutoff' in cfg: d['nonbondedCutoff'] = cfg.pop('nonbondedCutoff') * u.nanometers if 'constraints' in cfg: d['constraints'] = warned_getattr(openmm_app, cfg.pop('constraints'), None) for key in ['rigidWater', 'ewaldErrorTolerance']: if key in cfg: d[key] = cfg.pop(key) if 'extra_system_options' in cfg: if 'implicitSolvent' in cfg['extra_system_options']: implicit_solvent = warned_getattr( openmm_app, cfg['extra_system_options']['implicitSolvent'], None) cfg['extra_system_options']['implicitSolvent'] = implicit_solvent d.update(cfg.pop('extra_system_options')) return d
[ "def", "prepare_system_options", "(", "cfg", ",", "defaults", "=", "None", ")", ":", "d", "=", "{", "}", "if", "defaults", "is", "None", "else", "defaults", ".", "copy", "(", ")", "if", "'nonbondedMethod'", "in", "cfg", ":", "d", "[", "'nonbondedMethod'", "]", "=", "warned_getattr", "(", "openmm_app", ",", "cfg", ".", "pop", "(", "'nonbondedMethod'", ")", ",", "None", ")", "if", "'nonbondedCutoff'", "in", "cfg", ":", "d", "[", "'nonbondedCutoff'", "]", "=", "cfg", ".", "pop", "(", "'nonbondedCutoff'", ")", "*", "u", ".", "nanometers", "if", "'constraints'", "in", "cfg", ":", "d", "[", "'constraints'", "]", "=", "warned_getattr", "(", "openmm_app", ",", "cfg", ".", "pop", "(", "'constraints'", ")", ",", "None", ")", "for", "key", "in", "[", "'rigidWater'", ",", "'ewaldErrorTolerance'", "]", ":", "if", "key", "in", "cfg", ":", "d", "[", "key", "]", "=", "cfg", ".", "pop", "(", "key", ")", "if", "'extra_system_options'", "in", "cfg", ":", "if", "'implicitSolvent'", "in", "cfg", "[", "'extra_system_options'", "]", ":", "implicit_solvent", "=", "warned_getattr", "(", "openmm_app", ",", "cfg", "[", "'extra_system_options'", "]", "[", "'implicitSolvent'", "]", ",", "None", ")", "cfg", "[", "'extra_system_options'", "]", "[", "'implicitSolvent'", "]", "=", "implicit_solvent", "d", ".", "update", "(", "cfg", ".", "pop", "(", "'extra_system_options'", ")", ")", "return", "d" ]
Retrieve and delete (pop) system options from input configuration.
[ "Retrieve", "and", "delete", "(", "pop", ")", "system", "options", "from", "input", "configuration", "." ]
train
https://github.com/insilichem/ommprotocol/blob/7283fddba7203e5ac3542fdab41fc1279d3b444e/ommprotocol/io.py#L954-L974