def request_start(): content_type = request.headers.get('Accept') or '' real_ip = request.headers.get('X-Real-Ip') or '' Log.info(request.path+' '+format_args(request.args)\ +' '+real_ip\ +' '+content_type)
def __init__(self): if app.config['SQL_DRIVER'] == 'pymssql': engine = create_engine(r"mssql+pymssql://{0}:{1}@{2}:{3}/{4}".format( app.config['DATABASE_USER'], app.config['DATABASE_PASSWORD'], app.config['DATABASE_HOST'], app.config['DATABASE_PORT'], app.config['DATABASE_NAME'])) else: quoted = urllib.quote_plus('DRIVER={FreeTDS};Server=%s;Database=%s;UID=%s;PWD=%s;TDS_Version=8.0;CHARSET=UTF8;Port=1433;' %(app.config['DATABASE_HOST'], app.config['DATABASE_NAME'], app.config['DATABASE_USER'], app.config['DATABASE_PASSWORD'])) engine = create_engine('mssql+pyodbc:///?odbc_connect={}'.format(quoted), connect_args={'convert_unicode': True}) # create a Session Session = sessionmaker(bind=engine) try: self.session = Session() event.listen(Session, "after_transaction_create", self.session.execute('SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED')) Log.info('Connection Openned') except: Log.info('Can\'t create database session') raise
def installAPK(self, device_id=None, apk_full_path=None): """Performs the installation of an APK file""" if apk_full_path is None: Log.warn(self.__class__, 'The supplied path of apk is invalid') return command = 'install {apkpath}'.format(apkpath=apk_full_path) result = self.__execute_adb_cmd__(command) Log.info(self.__class__, result, device_id)
def uninstall_app(self, device_id=None, package_name=None): """Performs the uninstall of an application """ if package_name is None: Log.warn(self.__class__, 'The supplied PackageName is invalid') return command = "uninstall {package}".format(package=package_name) result = self.__execute_adb_cmd__(command, device_id) Log.info(self.__class__, result.decode())
def render(self, data, headers = {}, status_code = 200, raw = False): if request.headers['Accept'] == 'application/xml': if raw: data = data else: data = serialize(data, 'xml') response = Response(data, content_type='application/xml; charset=utf-8') elif request.headers['Accept'] == 'text/csv': if raw: data = data else: data = serialize(data, 'csv') response = Response(data, content_type='text/csv; charset=utf-8') # JSON or invalid Content-Type else : if raw: data = data else: if self.to_hal is not None and status_code == 200: if 'X-Total-Count' in headers: args = {'total' : headers['X-Total-Count']} else: args = {} data = self.to_hal(data, args = args) data = serialize(data, 'json') response = Response(data, content_type='application/hal+json; charset=utf-8') access_control_headers = "Content-Length, Content-Type, " access_control_headers += "Date, Server, " access_control_headers += "X-RateLimit-Limit, X-RateLimit-Remaining, X-RateLimit-Reset, Retry-After, " access_control_headers += "X-Total-Count" headers['Access-Control-Expose-Headers'] = access_control_headers response.headers.extend(headers) response.status_code = status_code real_ip = request.headers.get('X-Real-Ip') if real_ip == None: real_ip = '' Log.info(request.path+' '+real_ip+' '+str(status_code) + ' '+str(response.headers.get('Content-Length'))) return response
def enable_disable_app(self, device_id, package_name, app_state): """Enables/Disables a certain application/component """ if package_name is None: Log.warn(self.__class__, 'The supplied PackageName is invalid') return # Type checking if not isinstance(app_state, EzADB.State): raise TypeError('appState must be an instance of State Enum') command = "shell pm {state} {package}" \ .format(state="enable" if EzADB.State.ENABLED == app_state else "disable", package=package_name) result = self.__execute_adb_cmd__(command, device_id) Log.info(self.__class__, result.decode())
class log(): def createPath(self): """ Create the path of test folder. If the folder doesn't exist, it's created """ dia = time.strftime("%Y-%m-%d") # formato aaaa/mm/dd hora = time.strftime("%H%M%S") # formato 24 houras TestCase = self.__class__.__name__ horaAct = hora self.path = os.path.join(path_evidence, TestCase, dia, horaAct, '') if not os.path.exists(self.path): # si no existe el directorio lo crea os.makedirs(self.path) def createLog(self): """ Create the log of test. The log is created in the test folder """ self.createPath() TestCase = self.__class__.__name__ log_path = LOG_PATH.format(self.path, TestCase) self.log = Log(log_path) self.log = self.log.get_logger() self.log.info(MsgLog.MSG_CREATE_LOG.format(log_path))
def __del__(self): # close session after query executes self.session.close() Log.info('Database connection closed')
from tornado.httpserver import HTTPServer from tornado.ioloop import IOLoop from urls import * import argparse import logging from utils.Log import Log parser = argparse.ArgumentParser() parser.add_argument('--dev', action="store_true", default=False) app.config['PROPAGATE_EXCEPTIONS'] = True log = logging.getLogger('werkzeug') log.setLevel(logging.ERROR) if __name__ == '__main__': arguments = parser.parse_args() if arguments.dev: app.config['DEBUG'] = True Log.info("Running webserver in DEBUG mode") app.run(host=app.config['WEBSERVER_ADDR'], port=app.config['WEBSERVER_PORT']) else: Log.info("Running webserver in DEPLOYMENT mode") sockets = tornado.netutil.bind_sockets(app.config['WEBSERVER_PORT']) tornado.process.fork_processes(app.config['SUBPROCESS_NUMBER']) server = HTTPServer(WSGIContainer(app)) server.add_sockets(sockets) IOLoop.current().start()
def render(self, data, headers={}, status_code=200, raw=False): if not self.resolve_content(): data = {'message': 'invalid format', 'code': 55} status_code = 405 if self.content_type == 'xml': if raw: data = data else: data = serialize(data, 'xml') response = Response(data, content_type='application/xml; charset=utf-8') elif self.content_type == 'csv': if raw: data = data else: data = serialize(data, 'csv') resource_path = request.path.split("/") if resource_path[len(resource_path) - 1] != "": resource_type = resource_path[len(resource_path) - 1] else: resource_type = resource_path[len(resource_path) - 2] args_hash = md5hash(format_args(request.args)) headers[ "Content-Disposition"] = "attachment; filename=salicapi-%s-%s.csv" % ( resource_type, args_hash) response = Response(data, content_type='text/csv; charset=utf-8') # JSON or invalid Content-Type else: if raw: data = data else: if self.to_hal is not None and status_code == 200: if 'X-Total-Count' in headers: args = {'total': headers['X-Total-Count']} else: args = {} data = self.to_hal(data, args=args) data = serialize(data, 'json') response = Response( data, content_type='application/hal+json; charset=utf-8') access_control_headers = "Content-Length, Content-Type, " access_control_headers += "Date, Server, " access_control_headers += "X-RateLimit-Limit, X-RateLimit-Remaining, X-RateLimit-Reset, Retry-After, " access_control_headers += "X-Total-Count, " access_control_headers += "Content-Disposition" headers['Access-Control-Expose-Headers'] = access_control_headers response.headers.extend(headers) response.status_code = status_code real_ip = request.headers.get('X-Real-Ip') if real_ip == None: real_ip = '' Log.info(request.path + ' ' + real_ip + ' ' + str(status_code) + ' ' + str(response.headers.get('Content-Length'))) return response
def render(self, data, headers = {}, status_code = 200, raw = False): if not self.resolve_content(): data = {'message' : 'invalid format', 'code' : 55} status_code = 405 if self.content_type == 'xml': if raw: data = data else: data = serialize(data, 'xml') response = Response(data, content_type='application/xml; charset=utf-8') elif self.content_type == 'csv': if raw: data = data else: data = serialize(data, 'csv') resource_path = request.path.split("/") if resource_path[len(resource_path)-1] != "": resource_type = resource_path[len(resource_path)-1] else: resource_type = resource_path[len(resource_path)-2] args_hash = md5hash(format_args(request.args)) headers["Content-Disposition"] = "attachment; filename=salicapi-%s-%s.csv"%(resource_type, args_hash) response = Response(data, content_type='text/csv; charset=utf-8') # JSON or invalid Content-Type else : if raw: data = data else: if self.to_hal is not None and status_code == 200: if 'X-Total-Count' in headers: args = {'total' : headers['X-Total-Count']} else: args = {} data = self.to_hal(data, args = args) data = serialize(data, 'json') response = Response(data, content_type='application/hal+json; charset=utf-8') access_control_headers = "Content-Length, Content-Type, " access_control_headers += "Date, Server, " access_control_headers += "X-RateLimit-Limit, X-RateLimit-Remaining, X-RateLimit-Reset, Retry-After, " access_control_headers += "X-Total-Count, " access_control_headers += "Content-Disposition" headers['Access-Control-Expose-Headers'] = access_control_headers response.headers.extend(headers) response.status_code = status_code real_ip = request.headers.get('X-Real-Ip') if real_ip == None: real_ip = '' Log.info(request.path+' '+real_ip+' '+str(status_code) + ' '+str(response.headers.get('Content-Length'))) return response
class ResourceBase(Resource): # Rate limiting setup -------------------- if app.config['RATE_LIMITING_ACTIVE']: Log.info('Rate limiting active : %s' % (app.config['GLOBAL_RATE_LIMITS'])) decorators = [shared_limiter] else: Log.info('Rate limiting is turned off') # Caching setup -------------------- if app.config['CACHING_ACTIVE']: Log.info('Caching is active') else: app.config['CACHE_TYPE'] = 'null' Log.info('Caching is disabled') app.config['CACHE_NO_NULL_WARNING'] = True # register the cache instance and binds it on to your app app.cache = Cache(app) app.cache.clear() def __init__(self): self.to_hal = None def render(self, data, headers={}, status_code=200, raw=False): if not self.resolve_content(): data = {'message': 'invalid format', 'code': 55} status_code = 405 if self.content_type == 'xml': if raw: data = data else: data = serialize(data, 'xml') response = Response(data, content_type='application/xml; charset=utf-8') elif self.content_type == 'csv': if raw: data = data else: data = serialize(data, 'csv') resource_path = request.path.split("/") if resource_path[len(resource_path) - 1] != "": resource_type = resource_path[len(resource_path) - 1] else: resource_type = resource_path[len(resource_path) - 2] args_hash = md5hash(format_args(request.args)) headers[ "Content-Disposition"] = "attachment; filename=salicapi-%s-%s.csv" % ( resource_type, args_hash) response = Response(data, content_type='text/csv; charset=utf-8') # JSON or invalid Content-Type else: if raw: data = data else: if self.to_hal is not None and status_code == 200: if 'X-Total-Count' in headers: args = {'total': headers['X-Total-Count']} else: args = {} data = self.to_hal(data, args=args) data = serialize(data, 'json') response = Response( data, content_type='application/hal+json; charset=utf-8') access_control_headers = "Content-Length, Content-Type, " access_control_headers += "Date, Server, " access_control_headers += "X-RateLimit-Limit, X-RateLimit-Remaining, X-RateLimit-Reset, Retry-After, " access_control_headers += "X-Total-Count, " access_control_headers += "Content-Disposition" headers['Access-Control-Expose-Headers'] = access_control_headers response.headers.extend(headers) response.status_code = status_code real_ip = request.headers.get('X-Real-Ip') if real_ip == None: real_ip = '' Log.info(request.path + ' ' + real_ip + ' ' + str(status_code) + ' ' + str(response.headers.get('Content-Length'))) return response # Given a cgc/cpf/cnpj, makes sure it return only elements with exact match # Used to correct the use of SQL LIKE statement def get_unique(self, cgccpf, elements): exact_matches = [] for e in elements: if e['cgccpf'] == cgccpf: exact_matches.append(e) return exact_matches def get_last_offset(self, n_records, limit): if n_records % limit == 0: return (n_records / limit - 1) * limit else: return n_records - (n_records % limit) def resolve_content(self): # Content Type resolution if request.args.get('format') is not None: format = request.args.get('format') if format == 'json': self.content_type = 'json' return True elif format == 'xml': self.content_type = 'xml' return True elif format == 'csv': self.content_type = 'csv' return True else: self.content_type = 'json' return False else: if request.headers['Accept'] == 'application/xml': self.content_type = 'xml' return True elif request.headers['Accept'] == 'text/csv': self.content_type = 'csv' return True else: self.content_type = 'json' return True
from tornado.httpserver import HTTPServer from tornado.ioloop import IOLoop from urls import * import argparse import logging from utils.Log import Log parser = argparse.ArgumentParser() parser.add_argument('--dev', action="store_true", default=False) app.config['PROPAGATE_EXCEPTIONS'] = True log = logging.getLogger('werkzeug') log.setLevel(logging.ERROR) if __name__ == '__main__': arguments = parser.parse_args() if arguments.dev: app.config['DEBUG'] = True Log.info("Running webserver in DEBUG mode") app.run(host = app.config['WEBSERVER_ADDR'], port = app.config['WEBSERVER_PORT']) else: Log.info("Running webserver in DEPLOYMENT mode") sockets = tornado.netutil.bind_sockets(app.config['WEBSERVER_PORT']) tornado.process.fork_processes(app.config['SUBPROCESS_NUMBER']) server = HTTPServer(WSGIContainer(app)) server.add_sockets(sockets) IOLoop.current().start()
def pull_file(self, file_name, target_dir, device_id): """Pulls a specific file from the device""" command = "pull {file_path} {target_path}".format(file_path=file_name, target_path=target_dir) Log.info(self.__class__, command) return self.__execute_adb_cmd__(command, device_id, True)
from utils.Log import Log Log.info('haha')
from flask import Flask, render_template from utils.Log import Log app = Flask( __name__, template_folder='blog-vue-typescript-master/dist', static_folder='blog-vue-typescript-master/dist', static_url_path='', ) @app.route('/') def index(): return render_template('index.html') if __name__ == '__main__': Log.info('start run server') app.run( debug=True, port=7777, )