本文整理汇总了Python中execjs.compile函数的典型用法代码示例。如果您正苦于以下问题:Python compile函数的具体用法?Python compile怎么用?Python compile使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了compile函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: calculate_interest_and_credit
def calculate_interest_and_credit(price, first_payment, credit_length, no_insurance, no_confirmation, variation):
js_calc_filename = 'kreddb/js/creditcalc/calculator.js'
py_start_token = '// py_start'
py_end_token = '// py_end'
js_calc_filepath = finders.find(js_calc_filename)
with open(js_calc_filepath) as js_calc_file:
js_calc = js_calc_file.read()
py_start = js_calc.index(py_start_token) + len(py_start_token)
py_end = js_calc.index(py_end_token)
js_context = execjs.compile(js_calc[py_start:py_end])
interest = js_context.call(
'recalculate_interest',
price,
first_payment,
credit_length,
no_insurance,
no_confirmation,
variation
)
credit = js_context.call(
'calculate_credit',
price,
first_payment,
credit_length,
interest
)
return int(float(credit['total']) / (credit_length * 30))
示例2: __parse_token
def __parse_token(self, html_str):
pattern = re.compile('\\$\\$_=.*~\\[\\];.*\"\"\\)\\(\\)\\)\\(\\);')
match = pattern.search(html_str)
if not match:
raise "Can't find obfuscated token data."
obfuscated = match.group()
ctx = execjs.compile("""
function getToken() {
var token = null;
localStorage = {
setItem: function(key, value) {
if (key === 'gv-token')
token=value
}
};
""" +
obfuscated +
"""
return token;
}"""
)
self.__token_value = ctx.call('getToken')
示例3: buildBundle
def buildBundle(self, rebuild=None):
""" Builds CommonJS bundle """
rebuild = self._rebuild_bundle if rebuild is None else rebuild
if not os.path.exists(os.path.dirname(self._js_bundle)):
os.makedirs(os.path.dirname(self._js_bundle))
js_bundle_ts = os.path.getmtime(self._js_bundle) if os.path.exists(self._js_bundle) else 0
css_bundle_ts = os.path.getmtime(self._css_bundle) if os.path.exists(self._css_bundle) else 0
js_files_max_ts = max([os.path.getmtime(filename) for filename in self._scripts.values()]) if self._scripts else 0
css_files_max_ts = max([os.path.getmtime(filename) for filename in self._styles.values()]) if self._styles else 0
with open(os.path.join(os.path.dirname(__file__), 'CommonMixin.js')) as file:
ctx = execjs.compile(file.read())
if self._scripts and (js_files_max_ts>js_bundle_ts or rebuild):
files = list(self._scripts.items())
try:
ctx.call('bundle_scripts', self._js_bundle, self._requires, files, self._debug)
except execjs.RuntimeError as exc:
raise RuntimeError('execjs.RuntimeError: {0}'.format(exc.args[0].decode('utf8')))
logging.warning("Rebuilded: '{0}'.".format(self._js_bundle))
if self._styles and (css_files_max_ts>css_bundle_ts or rebuild):
files = list(self._styles.values())
try:
ctx.call('bundle_styles', self._css_bundle, files, self._debug)
except execjs.RuntimeError as exc:
raise RuntimeError('execjs.RuntimeError: {0}'.format(exc.args[0].decode('utf8')))
logging.warning("Rebuilded: '{0}'.".format(self._css_bundle))
示例4: std_encode
def std_encode(s):
import base64
import execjs
ctx = execjs.compile("""
btoa = function (input) {
var chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';
var str = String(input);
for (
// initialize result and counter
var block, charCode, idx = 0, map = chars, output = '';
// if the next str index does not exist:
// change the mapping table to "="
// check if d has no fractional digits
str.charAt(idx | 0) || (map = '=', idx % 1);
// "8 - idx % 1 * 8" generates the sequence 2, 4, 6, 8
output += map.charAt(63 & block >> 8 - idx % 1 * 8)
) {
charCode = str.charCodeAt(idx += 3/4);
if (charCode > 0xFF) {
throw new Error("'btoa' failed: The string to be encoded contains characters outside of the Latin1 range.");
}
block = block << 8 | charCode;
}
return output;
}
""")
temp = ctx.call("encodeURIComponent", s)
return ctx.call("btoa", temp)
示例5: create_gid
def create_gid(self):
temp = execjs.compile('''function create_gid() {
return "xxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,
function(c) {var r = Math.random() * 16 | 0,v = c == "x" ? r : (r & 3 | 8);
return v.toString(16);})}''')
self.gid = temp.call('create_gid')
return self.gid
示例6: buildBundle
def buildBundle(self, rebuild=None):
""" Builds CommonJS bundle and prepare it for server page prerendering. """
# scans all templates and registers all found components
template_path = self.settings.get('template_path')
if os.path.exists(template_path) and os.path.isdir(template_path):
for dirname, _, filelist in os.walk(template_path):
for filename in filelist:
filename = os.path.join(dirname, filename)
with open(filename) as file:
for alias in re.findall(self._RE, file.read()):
if alias not in self._scripts:
try:
name = alias.split('.')[-1]
module = importlib.import_module('.'.join(alias.split('.')[:-1]))
component = getattr(module, name)
if component:
self.registerComponent(component)
else:
raise
except:
raise ValueError("Component: {0} is not found.".format(alias))
CommonMixin.buildBundle(self, rebuild)
if os.path.exists(self._js_bundle):
with open(self._js_bundle) as file:
bundle = file.read()
with open(os.path.join(os.path.dirname(__file__), 'ReactMixin.js')) as file:
self._ctx = execjs.compile(bundle+file.read());
if self.settings.get('debug'):
for filename in self._styles.values():
tornado.autoreload.watch(filename)
for filename in self._scripts.values():
tornado.autoreload.watch(filename)
示例7: retrieve
def retrieve(palabra):
buffer = BytesIO()
#change to use `requests'
c = pycurl.Curl()
address = 'http://lema.rae.es/drae/srv/search?'
palabra_enc = urllib.parse.urlencode({'key':palabra})
c.setopt(c.URL, address+palabra_enc)
c.setopt(c.WRITEDATA, buffer)
c.perform()
body = buffer.getvalue()
l = body.decode().split("<script>")[1].split("</script>")[1].replace('<script type="text/javascript">', '').replace('document.forms[0].elements[1].value=', 'return ')
ctx = execjs.compile(l)
chall = ctx.call("challenge")
pdata = "&".join(body.decode().split("<body")[1].replace("/>", "\n").split("\n")[1:-1]).replace('<input type="hidden" name="', '').replace('" value="', '=').replace('"','').replace('TS014dfc77_cr=', 'TS014dfc77_cr=' + urllib.parse.quote_plus(chall))
buffer = BytesIO()
c = pycurl.Curl()
c.setopt(c.URL, address+palabra_enc)
c.setopt(c.WRITEDATA, buffer)
c.setopt(pycurl.HTTPHEADER, ["Referer: http://lema.rae.es/drae/srv/search?key=hola",
"Cache-Control: max-age=0",
"Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8",
"Origin: http://lema.rae.es",
"User-Agent: Mozilla/5.0 (X11; Linux i686) AppleWebKit/537.36 (KHTML, like Gecko) Ubuntu Chromium/39.0.2171.65 Chrome/39.0.2171.65 Safari/537.36"
])
c.setopt(c.POSTFIELDS, pdata)
c.perform()
body = buffer.getvalue().decode()
return body
示例8: get_globals_from_js
def get_globals_from_js(javascript, js_var_names):
ctx = execjs.compile(javascript)
extracted_vars = {}
for js_var_name in js_var_names:
extracted_vars[js_var_name] = ctx.eval(js_var_name)
return extracted_vars
示例9: fix_javascript
def fix_javascript(url, content):
""" 中南文交所的幺蛾子
假定至少安装过node
"""
import execjs
try:
if 'znypjy' in url:
text = content.decode('gb18030', 'ignore')
m = re.compile('(function.*?;})window.location').search(text)
if m:
script = m.group(1)
code = execjs.compile(script).call('decoder')
content = session.get(
url + '?' + code, timeout=(5, 10)).content
elif 'xhcae' in url:
text = content.decode('gb18030', 'ignore')
m = re.compile(
'/notice/\w+/\?WebShieldSessionVerify=\w+').search(text)
if m:
url = m.group(0)
content = session.get(
'http://www.xhcae.com' + url, timeout=(5, 10)).content
except:
log.exception('')
return content
示例10: __init__
def __init__(self,path):
try:
self.javascript = execjs.compile(open(path).read())
except:
self.pyv8 = False
else:
self.pyv8 = True
示例11: __init__
def __init__(self):
self.tkk = get_tkk() #从服务器获取TKK
self.ctx = execjs.compile("""
function b(a, b) {
for (var d = 0; d < b.length - 2; d += 3) {
var c = b.charAt(d + 2),
c = "a" <= c ? c.charCodeAt(0) - 87 : Number(c),
c = "+" == b.charAt(d + 1) ? a >>> c : a << c;
a = "+" == b.charAt(d) ? a + c & 4294967295 : a ^ c
}
return a
}
function tk(a,TKK) {
for (var e = TKK.split("."), h = Number(e[0]) || 0, g = [], d = 0, f = 0; f < a.length; f++) {
var c = a.charCodeAt(f);
128 > c ? g[d++] = c : (2048 > c ? g[d++] = c >> 6 | 192 : (55296 == (c & 64512) && f + 1 < a.length && 56320 == (a.charCodeAt(f + 1) & 64512) ? (c = 65536 + ((c & 1023) << 10) + (a.charCodeAt(++f) & 1023), g[d++] = c >> 18 | 240, g[d++] = c >> 12 & 63 | 128) : g[d++] = c >> 12 | 224, g[d++] = c >> 6 & 63 | 128), g[d++] = c & 63 | 128)
}
a = h;
for (d = 0; d < g.length; d++) a += g[d], a = b(a, "+-a^+6");
a = b(a, "+-3^+b+-f");
a ^= Number(e[1]) || 0;
0 > a && (a = (a & 2147483647) + 2147483648);
a %= 1E6;
return a.toString() + "." + (a ^ h)
}
""")
示例12: getimgurls
def getimgurls(html, url):
sFiles = re.search('sFiles="([^"]+)"', html).group(1)
sPath = re.search('sPath="([^"]+)"', html).group(1)
viewhtm = grabhtml("http://www.iibq.com/script/viewhtm.js")
env = """
window = {
"eval": eval,
"parseInt": parseInt,
"String": String,
"RegExp": RegExp
};
location = {
"hostname": "www.iibq.com"
};
"""
unsuan = partial(
execjs.compile(
env + re.search(r'(.+?)var cuImg', viewhtm, re.DOTALL).group(1)
).call,
"unsuan"
)
arrFiles = unsuan(sFiles).split("|")
ds = grabhtml("http://www.iibq.com/script/ds.js")
SLUrl = re.search('sDS = "([^"]+)"', ds).group(1).split("^")[0].split("|")[1]
return [SLUrl + sPath + f for f in arrFiles]
示例13: __init__
def __init__(self, username, password):
"""
:param username: username (student id)
:param password: password (default: birthday - yyyymmdd)
"""
self._username = username
self._password = password
self._s = requests.Session()
self._s.headers.update({
'Content-Type': 'application/x-www-form-urlencoded',
'Referer': 'http://zyfw.bnu.edu.cn'
})
self._lt = ''
self._execution = ''
self._info = {}
self._select_info = {}
self._grade_info = {}
self._table_parser = TableHTMLParser()
self._result_parser = ResultHTMLParser()
self._evaluate_parser = EvaluateHTMLParser()
# des js
with open('des.js', 'r', encoding='utf8') as f:
self._des = execjs.compile(f.read())
示例14: __setup
def __setup(self):
global src
if not src:
for js in ['compiler', 'handlebars', 'ember-template-compiler']:
src += resource_string(__name__, 'js/{0}.js'.format(js))
self.ctx = execjs.compile(src)
示例15: getimgurl
def getimgurl(html, url, page):
if url not in cache:
key = search(r'id="dm5_key".+?<script[^>]+?>\s*eval(.+?)</script>', html, DOTALL)
if key:
key = eval(key.group(1)).split(";")[1]
key = search(r"=(.+)$", key).group(1)
key = eval(key)
else:
key = ""
length = search("DM5_IMAGE_COUNT=(\d+);", html).group(1)
cid = search("DM5_CID=(\d+);", html).group(1)
funs = []
for p in range(1, int(length) + 1):
fun_url = urljoin(url, "chapterfun.ashx?cid={}&page={}&language=1&key={}>k=6".format(cid, p, key))
funs.append(fun_url)
cache[url] = funs
# Grab cookies?
grabhtml(funs[0], referer=url)
if page - 1 >= len(cache[url]):
del cache[url]
raise LastPageError
fun_url = cache[url][page - 1]
text = grabhtml(fun_url, referer=url)
d = compile(text).eval("(typeof (hd_c) != 'undefined' && hd_c.length > 0 && typeof (isrevtt) != 'undefined') ? hd_c : d")
return d[0]