def run_game(): # 初始化并创建一个屏幕对象 pygame.init() settings = Settings() settings.bg_color = (255, 255, 255) screen = pygame.display.set_mode(settings.screen_display) pygame.display.set_caption(settings.game_name) ship = Ship(screen, settings) bullets = Group() aliens = Group() gf.filled_aliens(settings, screen, ship, aliens) stats = GameStats(settings) btn_play_or_pause = Button(screen, 'PLAY') score_board_now = ScoreBoard(settings, screen, stats) while True: gf.check_event(settings, screen, ship, bullets, aliens, stats, btn_play_or_pause) if stats.game_active: ship.update() gf.update_bullets(settings, screen, ship, bullets, aliens, stats, score_board_now) gf.update_aliens(settings, stats, screen, ship, bullets, aliens) gf.update_screen(settings, screen, ship, bullets, aliens, stats, btn_play_or_pause, score_board_now)
def main(): parser = argparse.ArgumentParser(description='Train network.') parser.add_argument('--settings_file', help='Path to settings yaml', required=True) args = parser.parse_args() settings_filepath = args.settings_file settings = Settings(settings_filepath, generate_log=True) if settings.model_name == 'fb_sparse_vgg': trainer = FBSparseVGGModel(settings) elif settings.model_name == 'dense_vgg': trainer = DenseVGGModel(settings) elif settings.model_name == 'fb_sparse_object_det': trainer = SparseObjectDetModel(settings) elif settings.model_name == 'dense_object_det': trainer = DenseObjectDetModel(settings) else: raise ValueError( 'Model name %s specified in the settings file is not implemented' % settings.model_name) trainer.train()
def main(): parser = argparse.ArgumentParser(description='Evaluate network.') parser.add_argument('--settings_file', help='Path to settings yaml', required=True) parser.add_argument('--save_dir', help='Path to save location', required=True) parser.add_argument('--num_events', default=1, type=int) parser.add_argument('--num_samples', default=500, type=int) parser.add_argument('--representation', default="") parser.add_argument('--use_multiprocessing', help='If multiprocessing should be used', action='store_true') parser.add_argument('--compute_active_sites', help='If active sites should be calculated', action='store_true') args = parser.parse_args() settings_filepath = args.settings_file save_dir = args.save_dir settings = Settings(settings_filepath, generate_log=False) evaluator = FlopEvaluation(args, settings, save_dir=save_dir) evaluator.evaluateFLOP() evaluator.printLastStepFLOPs()
def sync_users_owners(event, context): settings = Settings() owners = Owners( repository.Users(settings.config.get("github")), Storage(settings.config), ) owners.sync()
def wrapper(*args, **kwargs): usvc = UserService() # get mapping settings = Settings() mapped_roles = flatten([ settings.RBAC_CONTROL[module] if module in settings.RBAC_CONTROL else None for module in module_names ]) # de-duplicate mapped_roles = list(set(mapped_roles)) # verify RBAC access control role_available = False for role in mapped_roles: if usvc.has_role(current_user, role): role_available = True # access control try: if role_available: return func(*args, **kwargs) else: current_app.logger.warning('Invalid access!!') abort(401) finally: pass
def list_accounts(event, context): settings = Settings() astngs = [] for k, v in settings.accounts.items(): if v.get("enabled", False): astngs.append(v) return Response.success(astngs)
def __init__(self, methodName="runTest"): super(TestModelInstances, self).__init__(methodName) self.settings = Settings() data = self.settings.accounts.get("engineering") self.account = Account(data, "frankfurt") self.model = Model( Provider(self.account, self.settings), Dispatcher(self.settings.config.get("sns")), )
def start_tagged_instances(event, context): current_hour = dt.datetime.today().hour try: settings = Settings() except Exception as error: logs.info("Handler", "Error getting settings {}".format(error.args[0])) return Response.error(error.args[0]) for account_name in settings.accounts: logs.info( "Handler", "Info: start_tagged_instances account {}".format(account_name), ) account_config = settings.accounts.get(account_name) if not account_config.get("enabled", False): logs.info( "Handler", "Info: start_tagged_instances account {} not enabled, skipping" .format(account_name), ) continue for region in account_config.get("regions"): logs.info( "Handler", "Info: start_tagged_instances region {}".format(region), ) try: _, instances = _build_instance_model(account_name, region, settings) except Exception as error: logs.info( "Handler", "Error: start_tagged_instances setup {}".format( error.args[0]), ) continue pass try: instances.start_tagged_instances([{ "Name": "tag:StartTime", "Values": [str(current_hour)] }]) except Exception as error: logs.info( "Handler", "Error: start_tagged_instances {}".format(error.args[0]), ) continue pass return Response.success("ok")
def __init__(self): # 국토교통부 API Key self.molit_api_key = Settings.return_molit_api_key() # 국토교통부_아파트 전월세 API URL self.molit_api_apartment_url = "http://openapi.molit.go.kr:8081/OpenAPI_ToolInstallPackage/service/rest/RTMSOBJSvc/getRTMSDataSvcAptRent" # 국토교통부_오피스텔 전월세 API URL self.molit_api_officetels_url = "http://openapi.molit.go.kr/OpenAPI_ToolInstallPackage/service/rest/RTMSOBJSvc/getRTMSDataSvcOffiRent" # 국토교통부_단독/다가구 전월세 API URL self.molit_api_family_url = "http://openapi.molit.go.kr:8081/OpenAPI_ToolInstallPackage/service/rest/RTMSOBJSvc/getRTMSDataSvcSHRent" # 국토교통부_연립다세대 전월세 API URL self.molit_api_alliance_url = "http://openapi.molit.go.kr:8081/OpenAPI_ToolInstallPackage/service/rest/RTMSOBJSvc/getRTMSDataSvcRHRent"
def create_all_roles(drop_existing=False): """ create all pre-defined roles """ from .database import db_trasaction from .models import RoleModel if drop_existing: RoleModel.query.delete() with db_trasaction() as txn: for role, desc in Settings().RBAC_ROLES.items(): txn.save_item(RoleModel(role, desc))
def terminate_tagged_instances(event, context): current_date = datetime.now().strftime("%d/%m/%Y") try: settings = Settings() except Exception as error: logs.info("Handler", "Error getting settings {}".format(error.args[0])) return Response.error(error.args[0]) for account_name in settings.accounts: account_config = settings.accounts.get(account_name) if not account_config.get("enabled", False): logs.info( "Handler", "Info: terminate_tagged_instances account {} not enabled, skipping" .format(account_name), ) continue for region in account_config.get("regions"): try: _, instances = _build_instance_model(account_name, region, settings) except Exception as error: logs.info( "Handler", "Error: terminate_tagged_instances setup {}".format( error.args[0]), ) continue pass try: instances.terminate_tagged_instances([ { "Name": "tag:TerminateDate", "Values": [str(current_date)], }, ]) except Exception as error: logs.info( "Handler", "Error: terminate_tagged_instances {}".format( error.args[0]), ) continue pass return Response.success("ok")
def info(event, context): storage = Storage(Settings().config) try: owners_list = storage.list_all_owners() except Exception as error: logs.info("Handler", "Error: list_all_owners {}".format(error.args[0])) return Response.error(error.args[0]) response = { "users": owners_list, "environments": ["test", "prod", "poc", "demo"], } return Response.success(response)
def user_loader(user_id): """ Given *user_id*, return the associated User object """ try: # get default language settings = Settings() lang = settings.get('BABEL_DEFAULT_LOCALE', None) timezone = settings.get('BABEL_DEFAULT_TIMEZONE', None) # user prefference support user = UserService().load_user(user_id) if hasattr(user, 'language'): lang = user.language if hasattr(user, 'timezone'): timezone = user.timezone # cache user language prefference into global variable if hasattr(g, 'user_info'): g.user_info['locale'] = lang g.user_info['timezone'] = timezone else: g.user_info = {'locale': lang, 'timezone': timezone} # cache config information if not hasattr(g, 'settings'): g.settings = settings # special case for confirm_email if request.path: include_inactive = allow_inactive_login(request.path) if include_inactive: return user return user if user and user.actived else None except SQLAlchemyError: return None
def _build_instance_model(account_name, region, settings=None): if settings is None: try: settings = Settings() except Exception as error: logs.info("Handler", "Error getting settings {}".format(error.args[0])) raise Exception("Error getting settings, {}".format(error.args[0])) account_map = settings.accounts.get(account_name) if not account_map.get("enabled", False): raise Exception("Error {} is set enabled: false".format(account_name)) account = Account(account_map, region) instances = Instances(Provider(account, settings), Dispatcher(settings.config.get("sns"))) return (account, instances)
class Core(object): pymframeversion = "3.0" settings = Settings() logger = None startTime = datetime.now() content = '' session = None usecgi = True form = None tplparam = {} _rendernl = None loggedin = False flash = None routing = None db = None def __init__(self): """ Initialsierung """ try: self.version = '1.0' os.environ["PYTHONIOENCODING"] = "utf-8" myLocale=locale.setlocale(category=locale.LC_ALL, locale=self.settings.locale) self.createDirectories() self.setLogger() self.loadCgiParameter() self.setWinBinMode() self.logger.info('START: "{}"'.format(self.path)) self.session = Session(self.logger) self.routing = Routing(self.logger,self.settings) self.currenttemplate = self.settings.defaulttemplate self.tplparam = { 'BODY' : '', 'APPNAME' : self.settings.appname, 'PATH' : self.path } self.connectDb() except Exception as ex: Emergency.stop(ex) def __del__(self): """ Zerstoeren des Hauptobjektes """ try: self.logger.info('END: "{}" wtc {}'.format(self.path,datetime.now() - self.startTime)) except: pass def setWinBinMode(self): """ Wenn Windows, verhalten von binaeren Dateien verbessern. """ try: # Windows needs stdio set for binary mode. import msvcrt msvcrt.setmode (0, os.O_BINARY) # stdin = 0 msvcrt.setmode (1, os.O_BINARY) # stdout = 1 self.logger.debug("Windows found, set binary mode") except ImportError: pass def createDirectories(self): """ Erzeugen notwendige Verzeichnisse in Datastore wenn nicht vorhanden. """ # -- LOG thepath = os.path.dirname(self.settings.logfile) distutils.dir_util.mkpath(thepath) # -- SESSION thepath = self.settings.sessionpath distutils.dir_util.mkpath(thepath) # -- DATABASE thepath = self.settings.dbpath distutils.dir_util.mkpath(thepath) def writelog(self,*args): """ Schreibt einen Fehlermeldung auf stderr """ import sys print(' '.join([str(a) for a in args]),file=sys.stderr) def connectDb(self): """ Verbinden mit Datenbank Wenn dbfilename angegeben """ self.db = Database('sqlite',self.settings.sqlitefilename) self.db.user = self.session.getAttribute(self.settings.authenvar) self.db.settings = self.settings self.db.logger = self.logger self.db.cgiparam = self.cgiparam self.db.writelog = self.writelog def setLoggerOn(self,level=10): self.logger.setLevel(level) def setLoggerOff(self,level=20): self.logger.setLevel(level) def setLogger(self): """ Definition logging """ self.logger = logging.getLogger("") self.logger.setLevel(self.settings.loglevel) fh = logging.FileHandler(self.settings.logfile) formatter = logging.Formatter("%(asctime)s - %(levelname)-6s - %(process)08d:[%(module)s.%(funcName)s] %(message)s") fh.setFormatter(formatter) self.logger.addHandler(fh) def handleLogin(self): """ Behandelt Anmeldeverfahren Es wird geprueft, ob schon ein Benutzer eingeloggt ist. Des erfogt durch das versuchte Lesen einer Sessionvariabel (gewoehnlich "user") ist diese Vorhanden bzw. nicht Leer, gilt der Benutzer als angemeldet. """ aVar = self.session.getAttribute(self.settings.authenvar) self.loggedin = False if not aVar: self.currenttemplate = self.settings.logintemplate self.logger.debug("Not logged in, Login-Mask activated.") return self.loggedin = True self.logger.debug('Loged in as: "{}"'.format(aVar)) def setFlash(self,txt): """ Setzen der Flashvariable Der Text in flash wird dem Template uebergeben ${FLASH} und kann wird dort angezeigt. @param txt Flash Text """ self.flash = txt def getEntry(self,path=None,strict=True,secure=True): """ Liefert einen Eintrag im Routingverzeihnis basierend auf Pfad @param path Pfad auf eintrag, wird keiener angegeben,so wird der aktuelle Pfad verwendet @param strict Vorgabewert gesetzt wird False uebergeben, so wird kein Fehler erzeugt, wenn nicht gefunden. @param secure Ueberprueft, ob beim Eitrag die Rechte ueberprueft werden soll. """ path = path or self.path inxEntry = self.routing.findEntry(path) entry = self.routing.entries[inxEntry] if strict and entry is None: sEntries = "Path-tree\n"+"\n".join([x.get('path','') for x in self.routing.entries]) msg = 'Es konnte kein Routingeintrag "{}" gefunden werden.\n{}'.format(path,sEntries) self.logger.debug(msg) Emergency.stop(msg) # Wenn nicht eingeloggt keine Pruefung durchfuehren if self.loggedin: if secure and self.checkRights(entry): return entry else: Emergency.stop("Kein Recht, die Funktion {}/{} aufzurufen".format(entry.get('path'),entry.get('controller'))) else: return entry def prepareController(self): """ Vorbereiten des Controller. Abstrakte Methode, diese kann in options/mframe.py ueberschrieben weden Setzen von Methoden und Vorgabewert HINT: Die Standards werden im creator des Controllers gesetzt. """ pass def checkRights(self,entry): """ Prueft ob der Benutzer eines der uebergebene Rechte besitzt Die Pruefung unterbleibt wenn: * der Eintrag keinen Rechteeintrag hat * kein Loggin stattgefunden hat HINT: Es sind "negative" Rechte moeglich. ist in rights ein Recht mit einem vorlaufenden Minuszeit behaftet z.B.: "-admin" so wird falsch zurueckgeliefert, wenn das recht fuer den aktuellen Benutzer gefunden wird. Beispiel rights: develop,-admin userRights: "admin,user" Falsch da -admin in userRights vorhanden ist. """ if not self.session.isLoggedin(): self.logger.debug('Not logged in, we leave checkRights') return False # Ist Eintrag Public (z.B. Authen) if entry.get('public'): return True rights = entry.get('rights') if rights is None: self.logger.debug('Rights are net set (None), we leave checkRights') return True self.logger.debug('Entryrights: {}'.format(repr(rights))) found = False userRights = self.session.getAttribute('rights') self.logger.debug('Userrights: {}'.format(repr(userRights))) # wurden Rechte gesetzt if rights is not None or rights==[]: if isinstance(rights,str): rights = rights.split(',') for right in rights: if right.startswith('-'): right = right[1:] if right in userRights: self.logger.debug('Negative righths found: {} is forbidden'.format(right)) return False else: if right in (userRights or []): found = True else: # Wenn keine Rechte im Eintrag # auf jeden Fall anzeigen found = True self.logger.debug('Result is "{}"'.format(found)) return found def releaseController(self,entry): """ Erzeugen des Controller, @param entry Routing Eintrags Object HINT: der Path wird nach Spezialfunktionen gescannt + *goback Muss im Entry eine Option redirekt haben. Es wird redirect auf den angegebnen Pfad durchgefuehrt """ controllerName = entry.get('controller') if controllerName is None: self.logger.debug('Path: "{}" controller not decleared, we leave'.format(entry.get('path'))) self.controller = Controller(self) return self.logger.debug("entrypath: {} controller: {}".format(entry.get('path'),controllerName)) sControllerPath = entry.get('path','').replace('/','.') sControllerPath = sControllerPath.lower() if sControllerPath.startswith('.'): sControllerPath = sControllerPath[1:] if sControllerPath == '': sControllerFile = 'mvc.controller.{}'.format(controllerName) else: sControllerFile = 'mvc.controller.{}.{}'.format(sControllerPath,controllerName) sControllerFile = self.settings.base+'/'+sControllerFile.replace('.','/')+'.py' sControllerFile = os.path.realpath(sControllerFile) if not os.path.isfile(sControllerFile): msg = 'Keinen Controller Datei {} gefunden'.format(sControllerFile) self.logger.debug(msg) self.content = msg Emergency.stop(msg) return if sControllerPath == '': sCommand = "from mvc.controller.{0} import {0}".format(controllerName) else: sCommand = "from mvc.controller.{0}.{1} import {1}".format(sControllerPath,controllerName) self.logger.debug('Import Controller over "{}"'.format(sCommand)) try: exec(sCommand) except Exception as ex: msg = 'Fehler bei Import des Controller "{}": "{}"'.format(sCommand,ex) self.content = msg self.logger.debug(msg) Emergency.stop(msg) self.controller = None sCommand = "{}(self)".format(controllerName) self.logger.debug('Build controller by sentence: "{}"'.format(sCommand)) try: self.controller = eval(sCommand) except Exception as ex: msg = 'Controller "{}" kann nicht initialiert werden; Meldung: "{}"'.format(sCommand,ex) self.content = msg self.logger.debug(msg) Emergency.stop(msg) self.prepareController() try: self.controller.get() except Exception as ex: msg = 'Fehler bei get() des Controller "{}": "{}" Abbruch'.format(controllerName,ex) self.logger.debug(msg) self.logger.debug(self.content) self.controller.status == self.controller.FAILED Emergency.stop(msg) def work(self): """ In der CGI Variable path wir der gewuenschte Pfad auf den Controller uebergeben. Diese wird ausgwertet und in der Routingtabelle nachgeschlagen. In der Routingtabelle wird der Controllername vermerkt und ausgefuehrt. """ redirectDeep=self.settings.maxredirects # Redirect Loop while FOREVER: entry = self.getEntry() for redirectcnt in range(0,redirectDeep-1): if entry.get('redirect') is None: break self.path = entry.get('redirect') entry = self.getEntry() else: Emergency.stop('Die Redirectfunktion durch Entry "{}" verursacht einen Zirkelbezug.'.format(self.path)) self.logger.debug('Entry "{}" gefunden'.format(entry.get('path','-- not found --'))) # Wenn bei Controller kein Login notwendig if entry.get('public'): self.logger.debug('path "{}" ist public - keine Autentifizierung notwendig'.format(self.path)) else: # Wenn noch nicht eingeloggt, dann loginmaske aufrufen self.handleLogin() if not self.loggedin: self.currenttemplate = self.settings.logintemplate break self.logger.debug('We are goin to execute Controller "{}"'.format(entry.get('controller'))) # absicherung gegen endlosloop redirectDeep -= 1 self.logger.debug('Redirectid: "{}"'.format(redirectDeep)) if redirectDeep < 1: self.logger.debug("Zu viele Redirects") Emergency.stop("Es sind zu viele Redirects hintereinader aufgerufen worden!") self.releaseController(entry) if self.controller.redirect is None: self.logger.debug('Controller is executed, no redirect found') break self.path = self.controller.redirect self.logger.debug('Redirect detected "{}"'.format(self.path)) entry = self.getEntry() else: self.content += controller.content def render(self,value): """ fuegt text dem Contentnbuffer hinzu @param text String mit inhalt """ self.content += value if self._rendernl: self.content += self._rendernl @staticmethod def getCgiParameter(param,nvl=''): """ Liefert den Inhalt eines CGI Parmeters basierend auf den QUERY_STRINGS @param param Name des CGI Parameters @param nvl Null-Value wird zurueckgeliefert, wenn der Parameter nicht vorhanden ist. Vorgabewert '' HINT: Es wird nur das 1. Vorkommen des Parameters ausgewertet! """ query_string = os.environ['QUERY_STRING'] parsed = parse_qs(query_string) retval = parsed.get(param) if retval is None: return None else: return retval[0] def loadCgiParameter(self): """ Laed den Inhalt des CGI in Abhaengigkeit des Flags usecgi. usecgi True: Es wird die Lib cgi verwendet False: Es wird QUERY_STRING verwendet HINT: In bestimmten Situationen z.B. wenn im HTTP Body nur daten uebertragen werden. verhaelt sich das CGI Modul so, dass es einen Ausnahmebedingung wirft. Der Flag usecgi ermoeglicht das Abschalten des Moduls. Die CGI Parameter werden aus dem URL extrahiert und so verspeichert, dass sie mit der Methode cgiparam wiedergewonnen werden koennen. """ if self.usecgi: self.form=FieldStorage(keep_blank_values=1) self.path = self.cgiparam(name='path',nvl='/') else: # Form inhalte holen qs = self.query_string parsed = parse_qs(qs) self.form = dict() for key in parsed.keys(): for val in parsed.get(key): self.form[key] = val try: self.path=parsed.get('path')[0] except: self.form = {'path':'/root'} self.path = self.cgiparam('path','/root') def getParsedQueryString(self): """ Liefert den geparsten Query String """ return cgi.parse_qs(self.query_string) def cgiparam(self,name=None,nvl='',noneifnotused=False): """ Liefert aus dem CGI einen benannten Parameter @param name Name des Cgiparmeters @param nvl NullValue wird geliefert, wenn der Parameter nicht uebergeben wurde HINT: Es wird geprueft, ob self.form ein Dict oder FieldStorage ist. Je nach Type wird der Inhalt geliefert. """ if self.form is None: self.logger.debug('Form not defined, nvl returnd') return nvl # Wurde Spezielle CGI Verarbeitung gewuenscht if isinstance(self.form,dict): return self.form.get(name,nvl) # wenn Parameter nicht definiert # null-value zurueckgeben if name not in self.form: if noneifnotused: return None else: return nvl value = self.form.getvalue(name) if value is None: value = nvl else: if isinstance(value,list): try: value = value[0] except: value = nvl auxValue = value if name != 'password' else '*' * len(value) self.logger.debug('Get from CGI: "{}"="{}"'.format(name,auxValue)) return value def defaultTemplateParameter(self): """ Setzen der Parameter fuer Templates """ self.tplparam['BODY'] = self.content self.tplparam['FLASH'] = (self.flash or '').replace('"', r'\"') self.tplparam['PYMFRAMEVERSION'] = self.pymframeversion self.tplparam['USER'] = self.session.getAttribute(self.settings.authenvar) self.tplparam['RIGHTS'] = repr(self.session.getAttribute('rights')) self.tplparam['MENU'] = self.routing.getMenu(self.path,self.checkRights) self.tplparam['PATH'] = self.path def setTemplateParameter(self,name,value): """ Fuegt der Standard Parmeterliste einen Eintrag hinzug oder aendert diesen. @param name Name des Parameters @param value Inhalt """ self.tplparam[name] = value def disableGoback(self): """ Deaktiviert den Zurueckbutton """ self.routing.gobacktext = None # # ######## Core ROUTINES ############################################ # def setup(self): """ Initialisieren Abstrakte Methode, diese kann in options/mframe.py ueberschrieben werden """ pass def onInit(self): """ Abstrakte Mehtode wird in options/mframe.py aufgerufen """ pass def afterWork(self): """ Abstrakte Mehtode wird in options/mframe.py aufgerufen """ pass def onDone(self): """ Abstrakte Mehtode wird in options/mframe.py aufgerufen """ pass def build(self): """ Startet die Verarbeitung. @param onInit Hook bevor die Bearbeitung beginnt @param onClose Nachbearbeitung """ self.logger.debug("run") self.onInit() self.work() self.afterWork() template = Templateengine(self.currenttemplate) template.readTemplateFile() contenttype = self.settings.contenttype self.defaultTemplateParameter() try: self.content = template.get(self.tplparam) except Exception as ex: Emergency.stop(ex) self.onDone() self.logger.debug("done") def write(self): """ Gibt den gesamten Response auf stdout aus """ self.session.cookies['with_max_age'] = 'expires in {} minutes'.format(self.settings.sessionlifetime) sys.stdout.flush() sys.stdout.write(self.session.cookies.output(self.session.cookies)) sys.stdout.write('\n') sys.stdout.write(self.settings.contenttype) sys.stdout.write('\n') sys.stdout.buffer.write(self.content.encode('utf-8')) sys.stdout.write('\n') sys.stdout.flush()
class Session(object): config = Settings() sid = None cookies = None logger = None sFilename = None attributes = None # Liefert ein Cookie oder None wenn nicht vorhanden getCookie = lambda self,c : \ self.cookies.get(c).value if self.cookies.get(c) is not None \ else None def __init__(self, logger): # Ist Cookie SID vorhanden? # # @param logger Loggerobjekt # self.logger = logger webserver = os.environ.get('SERVER_SOFTWARE', '') self.cookies = Cookies.SimpleCookie(os.environ.get('HTTP_COOKIE', '')) self.sid = self.getCookie('sid') if self.sid is None: self.sid = str(uuid.uuid4()) self.logger.debug('No Cookie sid, create it sid={}'.format( self.sid)) else: self.logger.debug('Found cookie sid={}'.format(self.sid)) self.removeZoobies() self.sFilename = "{}/{}.ses".format(self.config.sessionpath, self.sid) self.logger.debug('SFile: "{}"'.format(self.sFilename)) # erzeugen Sessionfile wenn nicht vorhanden if not os.path.isfile(self.sFilename): with open(self.sFilename, 'w') as fSession: self.attributes = dict() self.attributes['sid'] = self.sid json.dump(self.attributes, fSession) self.logger.debug("Create empty sessionfile {}".format( self.sFilename)) # Hole Attribute with open(self.sFilename, 'r') as fSession: self.attributes = json.load(fSession) if self.sid != self.getAttribute('sid'): Emergency.stop('Session ID is not equal cookie-id') self.cookies['sid'] = self.sid self.logger.debug("Attributes: {}".format(json.dumps(self.attributes))) def isLoggedin(self): """ Testet ob schon ein login stattgefunden hat. Dies ist gegeben, wenn das Attribute (normalerweise "user") gesetzt worden ist. """ retval = self.getAttribute(self.config.authenvar) return retval def removeZoobies(self): """ Loeschen aller Sessionfiels, deren Lebenszeit abgelaufen ist Die Lebenszeit wird aus Config entnommen """ path = self.config.sessionpath lifetime = self.config.sessionlifetime erasedate = datetime.now() - timedelta(minutes=lifetime) self.logger.debug("Lifetime:{} Erasedate:{}".format( lifetime, erasedate)) # Alle Dateien pruefen for sFile in os.listdir(path): sFile = os.path.join(path, sFile) if not os.path.isfile(sFile): continue fn, ext = os.path.splitext(sFile) if not ext.startswith('.ses'): continue # Dateizeit fdt = datetime.fromtimestamp(os.stat(sFile).st_mtime) # Pruefen ob zu loeschen if fdt < erasedate: os.remove(sFile) self.logger.debug("Remove Sessionfile: {} {} {}".format( sFile, fdt, erasedate)) def removeSession(self): """ Entfernt akutelle Session """ if self.sid is None: return sFilename = "{}/{}.ses".format(self.config.sessionpath, self.sid) if os.path.isfile(self.sFilename): os.remove(sFilename) self.sFilename = None self.attributes['user'] = '' self.attributes['sid'] = '' self.logger.debug('Remove sessionfile "{}"'.format(sFilename)) def setAttribute(self, aname, avalue): """ Setzen von Cookie Attribute """ #with open(self.sFilename,'r') as fSession: # self.attributes = json.load(fSession) self.attributes[aname] = avalue with open(self.sFilename, 'w') as fSession: json.dump(self.attributes, fSession) self.logger.debug('Set Sessionattribute {}="{}"'.format(aname, avalue)) def getAttribute(self, aname): """ Liefert den Inhalt eines Attributes von Session @param aname Name des Attributes @return Attribute oder None """ # Wenn keine Attribute dann Session nachladen if not isinstance(self.attributes, dict): with open(self.sFilename, 'r') as fSession: self.attributes = json.load(fSession) self.logger.debug('Get Sessionattribute {}="{}"'.format( aname, self.attributes.get(aname, ''))) return self.attributes.get(aname, None) @staticmethod def purge(self): """ Loescht alle Sessionfiels """ for sFile in os.scandir(self.config.sessionpath): if os.path.isfile(sFile): os.remove(sFile) self.logger.debug("removed sessionfiles in {self.config.sessionpath}")
def run(config, debug): global _settings, _logger programExecTime = time.time() outData = [] _settings = Settings(config) if debug == True: _logger = sys.stdout.write elif type(debug) == str: try: logFile = open(debug, "a") _logger = logFile.write except Exception as e: print('\nCannot open log file. Debug flag ignored. Error: ' + str(e)) try: startTime = time.time() loginStatus = login() if not (loginStatus): loginResponse = Response('sasping login request', 'fail', message='Failed to login.') else: loginResponse = Response('sasping login request', 'success') except requests.exceptions.Timeout as err: loginResponse = Response('sasping login request', 'fail', message='Request timeout') loginResponse.setTime(startTime, time.time() - startTime) loginResponse.setProgramExecTime(programExecTime) if loginResponse.status == 'fail': return [dict(loginResponse)] # get request to do sas security check # this request is not logged to csv file try: _session.get( _settings.get('hostUrl') + Test(_settings.get('applications')[0]['tests'][0]).get('execPath')) except requests.exceptions.RequestException: raise RuntimeError('SAS security check request failed') finally: outData.append(dict(loginResponse.setProgramExecTime(programExecTime))) applications = _settings.get('applications') for app in applications: for test in [Test(testConfig) for testConfig in app['tests']]: try: startTime = time.time() response = call(test) except requests.exceptions.Timeout: response = Response(test.get('id'), 'fail', message='Request timeout') except requests.exceptions.ConnectionError: response = Response(test.get('id'), 'fail', message='Name or service not known') except requests.exceptions.RequestException as e: response = Response(test.get('id'), 'fail', message=str(e)) response.setTime(startTime, time.time() - startTime) response.setAppName(app['name']) outData.append( dict(response.setProgramExecTime(programExecTime))) try: logFile.close() finally: return outData
from jose import jwt from fastapi import (APIRouter, HTTPException, status, Depends) from fastapi.security import OAuth2PasswordRequestForm from services.auth import Auth from config.settings import Settings from models import users from models.auth import LoginModel settings = Settings() auth_router = APIRouter() @auth_router.post('/register') async def register(form_data: users.CreateUser): if await users.UserModel.get_or_none(email=form_data.email) is not None: raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail='User with this email already exists') user = await users.UserModel.create(email=form_data.email, hashed_password=Auth.get_password_hash( form_data.password)) confirmation = Auth.get_confirmation_token(user.id) user.confirmation = confirmation['jti'] print(confirmation['token']) await user.save() return await users.User_Pydantic.from_tortoise_orm(user)
def __init__(self): self.geocoder_api_url = "http://api.vworld.kr/req/address" self.geocoder_api_key = Settings.return_geocoder_api_key()
def __init__(self): self.kakao_geocoder_api_url = "https://dapi.kakao.com/v2/local/search/address.json" self.kakao_geocoder_api_key = Settings.return_kakao_api_key()