Best Python code snippet using autopy
auth.py
Source:auth.py
1# coding=utf-82import re3import hmac4import time5import traceback6import requests7from functools import wraps8# from flask.ext.babel import gettext as _9from flask import g, session, redirect, current_app, request, render_template, jsonify10__author__ = 'Feng Lu'11token_re = re.compile(r"\??\b_token=\w+&?")12def res_json(code, data, message, success, **kwargs):13 res = jsonify(14 code=code,15 data=data,16 message=message,17 success=success,18 **kwargs19 )20 if str(code) in ["200", "401", "403"]:21 res.status_code = code22 return res23class PermissionDeniedException(Exception):24 def __init__(self, permissions):25 super(Exception, self).__init__('permissions %(perm)s required', perm=' or '.join(permissions))26class Auth(object):27 @classmethod28 def required(cls, permissions, error_resp_type="json"):29 if not (isinstance(permissions, list) or isinstance(permissions, tuple)):30 permissions = [permissions, ]31 if "super.admin" not in permissions:32 permissions.append("super.admin")33 def wrap(func):34 @wraps(func)35 def inner_wrap(*args, **kwargs):36 if hasattr(g, 'user'):37 if any(map(lambda x: x in permissions, g.user['permissions'])):38 return func(*args, **kwargs)39 if len(permissions) == 0:40 return func(*args, **kwargs)41 msg = u"没ææé访é®: %s" % func.__name__42 if error_resp_type == "json":43 return res_json(**{"code": 403, "data": "", "message": (msg), "success": False})44 elif error_resp_type == "html":45 return render_template("common/fail.html", message=msg)46 else:47 return res_json(**{"code": 403, "data": "", "message": (msg), "success": False})48 return inner_wrap49 return wrap50 @classmethod51 def allow(cls, permissions):52 if not (isinstance(permissions, list) or isinstance(permissions, tuple)):53 permissions = [permissions, ]54 if "super.admin" not in permissions:55 permissions.append("super.admin")56 if not hasattr(g, 'user'):57 return False58 if any(map(lambda x: x in permissions, g.user['permissions'])) or len(permissions) == 0:59 return True60 return False61 @classmethod62 def load_user(cls):63 if not current_app.config.get('SSO_ENABLE'):64 g.user = current_app.config.get("LOCAL_USER")65 return66 if request.values.get("_token"):67 session["user_token"] = request.values.get("_token")68 if session.get('user_token'):69 url = '%s/account/user_info.json?token=%s&secret=%s&app=%d' % (70 current_app.config.get('SSO_URL'),71 session.get('user_token'),72 current_app.config.get('SSO_APP_SECRET'),73 current_app.config.get('SSO_APP_ID')74 )75 try:76 req = requests.get(url)77 resp = req.json()78 if resp['code'] == 200:79 g.user = resp["data"]80 if token_re.findall(request.url):81 return redirect(token_re.sub("", request.url))82 elif resp['code'] == 403:83 return render_template("include/fail.html", message=resp["message"])84 else:85 return redirect('/account/login?redirect=%s' % (token_re.sub("", request.url)))86 except Exception as e:87 return redirect('/account/login?redirect=%s' % (token_re.sub("", request.url)))88 else:89 return redirect('/account/login?redirect=%s' % (token_re.sub("", request.url)))90 @classmethod91 def load_api(cls):92 """93 """94 if not current_app.config.get('SSO_ENABLE'):95 g.user = current_app.config.get("LOCAL_USER")96 return97 # å¿
é¡»è¦æä¾ä¸ä¸ªå¤´åæ°98 secretid = request.headers.get("x-secretid")99 timestamp = request.headers.get("x-timestamp")100 signature = request.headers.get("x-signature")101 if secretid and timestamp and signature:102 serv_timestamp = time.strftime('%s', time.localtime())103 delta = abs(int(serv_timestamp) - int(timestamp))104 if delta > 60:105 return jsonify(106 {"retcode": -1,107 "msg": "The timestamp you provide is difference to server up to 60s, please check your system time",108 "result": "", "type": "str"})109 url = '%s/account/secret/%s' % (current_app.config.get('SSO_URL'), secretid)110 try:111 req = requests.get(url)112 resp = req.json()113 if resp['status'] == 200:114 secret = resp["secret"]115 query_keys = request.values.keys()116 query_keys.sort()117 query = []118 for key in query_keys:119 query.append("%s=%s" % (key, request.values[key]))120 body = '&'.join(query)121 # çæç¾å122 serv_signature = hmac.new(str(secret["key"]), body).hexdigest()123 if serv_signature != signature:124 return jsonify({"retcode": -1, "msg": "x-signature is incrrect! ", "result": "", "type": "str"})125 g.user = resp126 if token_re.findall(request.url):127 return redirect(token_re.sub("", request.url))128 else:129 return jsonify({"retcode": -1, "msg": resp.get("message"), "result": "", "type": "str"})130 except Exception as e:131 current_app.logger.error(traceback.format_exc())132 return jsonify({"retcode": -1, "msg": e.message, "result": "", "type": "str"})133 else:134 return jsonify(135 {"retcode": -1, "msg": "x-secretid,x-timestamp and x-signature in headers is required", "result": "",...
__init__.py
Source:__init__.py
1# -*- coding: utf-8 -*-2# @Time : 2016/12/4 ä¸å1:313# @Author : Zhixin Piao, Shengjia Yan, Ruiming Wang4# @Email : piaozhx@seu.edu.cn, sjyan@seu.edu.cn, wangruiming@seu.edu.cn5import new6import re as libre7from REtoNFA import NFA, NFAManager8from NFAtoDFA import DFAmanager9class Re_Token:10 def __init__(self, lexer, re):11 self.lexer = lexer12 self.func = None13 self.re = re14 self.name = re15 def extends(self):16 _method = None17 if self.func is not None:18 func = 'def callBack(self):\n'19 for code in self.func.split('\n'):20 func += '\t' + code + '\n'21 exec func + '_method = callBack'22 self.__dict__['callBack'] = new.instancemethod(_method, self, None)23 self.callBack()24class Token:25 def __init__(self, name, value=''):26 self.name = name27 if value == '':28 self.value = name29 else:30 self.value = value31class Lex:32 # åå§å33 def __init__(self, path):34 self.lineno = 035 self.keywords = {}36 with open(path, 'r') as f:37 self.parserLexFile(f.read())38 # 读ålexæ件信æ¯39 def parserLexFile(self, content):40 # å®ä¹åºï¼è§ååºï¼ç¨æ·å®ä¹ä»£ç åº41 (define, rule, user) = content.split('%%')42 # å®ä¹åºæ°æ®è¯»å43 temp_token = {}44 define = define.replace('\t', ' ')45 defines = [d for d in define.split('\n') if d != '']46 for d in defines:47 token_name = d[:d.index(' ')]48 token_re = d[d.index('['):d.rindex(']') + 1]49 temp_token[token_name] = token_re50 # è§ååºæ°æ®è¯»å51 tokenArr = self.ReTokenArr = []52 rules = [r for r in rule.split('\n') if r != '']53 code_flag = False54 code = ''55 cur_Token = None56 for r in rules:57 # print r58 if code_flag:59 if r.find('}') != -1:60 code_flag = False61 cur_Token.func = code[:-1]62 tokenArr.append(cur_Token)63 code = ''64 else:65 code += r.strip() + '\n'66 elif r.find('"') != -1:67 token_re = r[r.index('"') + 1:r.rindex('"')]68 tokenArr.append(Re_Token(self, token_re))69 elif r.find('{') == -1:70 token_re = r.strip()71 tokenArr.append(Re_Token(self, token_re))72 else:73 token_re = r[:r.rindex('{')].strip()74 cur_Token = Re_Token(self, token_re)75 code_flag = True76 # æ¿æ¢å®ä¹åºæ£è§è¡¨è¾¾å¼77 for token in tokenArr:78 for k, v in temp_token.iteritems():79 token.re = token.re.replace('{' + k + '}', v)80 token.extends()81 print u'lexæ°æ®è¯»åå®æï¼æ£å¨è¿è¡Re->NFA'82 self.ReToNFA()83 # ç¨æ·å®ä¹ä»£ç åº84 pass85 # 解ææ£è§è¡¨è¾¾å¼86 def ReToNFA(self):87 nfaManager = NFAManager()88 nfaArr = []89 for token in self.ReTokenArr:90 token.re = token.re.replace('\\n', '\n').replace('\\t', '\t').replace('\\r', '\r')91 if token.re == '(' or token.re == ')' or token.re == '*':92 token.re = "\\" + token.re93 # print token.re94 if libre.match(r'[a-z]+', token.re):95 self.keywords[token.re] = token.re96 else:97 nfaArr.append(nfaManager.feed(token.re, token.name))98 self.nfa = nfaManager.merge(nfaArr)99 self.nfa.draw()100 print u'Re->NFAå®æï¼æ£å¨æ§è¡NFA->DFA'101 self.NFAtoDFA()102 def NFAtoDFA(self):103 nfa = self.nfa104 self.dfacreator = DFAmanager(nfa.dic, nfa.getInfo())105 self.dfacreator.creatDFA()106 self.dfacreator.draw()107 print u'NFA->DFAå®æï¼æ£å¨è¯»åæ°æ®'108 def feedCode(self, code_path):109 with open(code_path, 'r') as f:110 res = self.dfacreator.judgeString(f.read(), self.keywords)111 TokenArr = []112 for r in res:113 if r['category'] == 'IGNORE':114 continue115 print r116 if r['category'] == 'NUMBER':117 TokenArr.append(Token(r['category'], int(r['mention'])))118 else:119 TokenArr.append(Token(r['category'], r['mention']))120 return TokenArr121 def getTerminals(self):122 terminals = []123 for s in self.ReTokenArr:124 if s.name == 'IGNORE':125 continue126 terminals.append(s.name)...
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!