INSTRUCTION
stringlengths
1
46.3k
RESPONSE
stringlengths
75
80.2k
Get the full dict of maps {map_name: map_class}.
def get_maps(): """Get the full dict of maps {map_name: map_class}.""" maps = {} for mp in Map.all_subclasses(): if mp.filename: map_name = mp.__name__ if map_name in maps: raise DuplicateMapException("Duplicate map found: " + map_name) maps[map_name] = mp return maps
Get an instance of a map by name. Errors if the map doesn't exist.
def get(map_name): """Get an instance of a map by name. Errors if the map doesn't exist.""" if isinstance(map_name, Map): return map_name # Get the list of maps. This isn't at module scope to avoid problems of maps # being defined after this module is imported. maps = get_maps() map_class = maps.get(ma...
The full path to the map file: directory, filename and file ending.
def path(self): """The full path to the map file: directory, filename and file ending.""" if self.filename: map_path = os.path.join(self.directory, self.filename) if not map_path.endswith(".SC2Map"): map_path += ".SC2Map" return map_path
Return the map data.
def data(self, run_config): """Return the map data.""" try: return run_config.map_data(self.path) except (IOError, OSError) as e: # Catch both for python 2/3 compatibility. if self.download and hasattr(e, "filename"): logging.error("Error reading map '%s' from: %s", self.name, e.filenam...
Convert (width, height) or size -> point.Point.
def _to_point(dims): """Convert (width, height) or size -> point.Point.""" assert dims if isinstance(dims, (tuple, list)): if len(dims) != 2: raise ValueError( "A two element tuple or list is expected here, got {}.".format(dims)) else: width = int(dims[0]) height = int(dims[1]...
Creates an AgentInterfaceFormat object from keyword args. Convenient when using dictionaries or command-line arguments for config. Note that the feature_* and rgb_* properties define the respective spatial observation dimensions and accept: * None or 0 to disable that spatial observation. * A single...
def parse_agent_interface_format( feature_screen=None, feature_minimap=None, rgb_screen=None, rgb_minimap=None, action_space=None, camera_width_world_units=None, use_feature_units=False, use_raw_units=False, use_unit_counts=False, use_camera_position=False): """Creates an Agent...
Construct a Features object using data extracted from game info. Args: game_info: A `sc_pb.ResponseGameInfo` from the game. use_feature_units: Whether to include the feature unit observation. use_raw_units: Whether to include raw unit data in observations. This differs from feature_units because ...
def features_from_game_info( game_info, use_feature_units=False, use_raw_units=False, action_space=None, hide_specific_actions=True, use_unit_counts=False, use_camera_position=False): """Construct a Features object using data extracted from game info. Args: game_info: A `sc_pb.Respo...
Initialize ValidFunctions and set up the callbacks.
def _init_valid_functions(action_dimensions): """Initialize ValidFunctions and set up the callbacks.""" sizes = { "screen": tuple(int(i) for i in action_dimensions.screen), "screen2": tuple(int(i) for i in action_dimensions.screen), "minimap": tuple(int(i) for i in action_dimensions.minimap), } ...
Return a correctly shaped numpy array for this feature.
def unpack(self, obs): """Return a correctly shaped numpy array for this feature.""" planes = getattr(obs.feature_layer_data, self.layer_set) plane = getattr(planes, self.name) return self.unpack_layer(plane)
Return a correctly shaped numpy array given the feature layer bytes.
def unpack_layer(plane): """Return a correctly shaped numpy array given the feature layer bytes.""" size = point.Point.build(plane.size) if size == (0, 0): # New layer that isn't implemented in this SC2 version. return None data = np.frombuffer(plane.data, dtype=Feature.dtypes[plane.bits_per...
Return a correctly shaped numpy array given the image bytes.
def unpack_rgb_image(plane): """Return a correctly shaped numpy array given the image bytes.""" assert plane.bits_per_pixel == 24, "{} != 24".format(plane.bits_per_pixel) size = point.Point.build(plane.size) data = np.frombuffer(plane.data, dtype=np.uint8) return data.reshape(size.y, size.x, 3)
Update the camera transform based on the new camera center.
def _update_camera(self, camera_center): """Update the camera transform based on the new camera center.""" self._world_tl_to_world_camera_rel.offset = ( -self._world_to_world_tl.fwd_pt(camera_center) * self._world_tl_to_world_camera_rel.scale)
The observation spec for the SC2 environment. It's worth noting that the image-like observations are in y,x/row,column order which is different than the actions which are in x,y order. This is due to conflicting conventions, and to facilitate printing of the images. Returns: The dict of observat...
def observation_spec(self): """The observation spec for the SC2 environment. It's worth noting that the image-like observations are in y,x/row,column order which is different than the actions which are in x,y order. This is due to conflicting conventions, and to facilitate printing of the images. ...
Render some SC2 observations into something an agent can handle.
def transform_obs(self, obs): """Render some SC2 observations into something an agent can handle.""" empty = np.array([], dtype=np.int32).reshape((0, 7)) out = named_array.NamedDict({ # Fill out some that are sometimes empty. "single_select": empty, "multi_select": empty, "build_que...
Return the list of available action ids.
def available_actions(self, obs): """Return the list of available action ids.""" available_actions = set() hide_specific_actions = self._agent_interface_format.hide_specific_actions for i, func in six.iteritems(actions.FUNCTIONS_AVAILABLE): if func.avail_fn(obs): available_actions.add(i) ...
Tranform an agent-style action to one that SC2 can consume. Args: obs: a `sc_pb.Observation` from the previous frame. func_call: a `FunctionCall` to be turned into a `sc_pb.Action`. skip_available: If True, assume the action is available. This should only be used for testing or if you e...
def transform_action(self, obs, func_call, skip_available=False): """Tranform an agent-style action to one that SC2 can consume. Args: obs: a `sc_pb.Observation` from the previous frame. func_call: a `FunctionCall` to be turned into a `sc_pb.Action`. skip_available: If True, assume the action...
Transform an SC2-style action into an agent-style action. This should be the inverse of `transform_action`. Args: action: a `sc_pb.Action` to be transformed. Returns: A corresponding `actions.FunctionCall`. Raises: ValueError: if it doesn't know how to transform this action.
def reverse_action(self, action): """Transform an SC2-style action into an agent-style action. This should be the inverse of `transform_action`. Args: action: a `sc_pb.Action` to be transformed. Returns: A corresponding `actions.FunctionCall`. Raises: ValueError: if it doesn't ...
Mask should be a set of bools from comparison with a feature layer.
def _xy_locs(mask): """Mask should be a set of bools from comparison with a feature layer.""" y, x = mask.nonzero() return list(zip(x, y))
Run SC2 to play a game or a replay.
def main(unused_argv): """Run SC2 to play a game or a replay.""" stopwatch.sw.enabled = FLAGS.profile or FLAGS.trace stopwatch.sw.trace = FLAGS.trace if (FLAGS.map and FLAGS.replay) or (not FLAGS.map and not FLAGS.replay): sys.exit("Must supply either a map or replay.") if FLAGS.replay and not FLAGS.rep...
Wait for a proc to shut down, then terminate or kill it after `timeout`.
def _shutdown_proc(p, timeout): """Wait for a proc to shut down, then terminate or kill it after `timeout`.""" freq = 10 # how often to check per second for _ in range(1 + timeout * freq): ret = p.poll() if ret is not None: logging.info("Shutdown gracefully.") return ret time.sleep(1 / fr...
Shut down the game and clean up.
def close(self): """Shut down the game and clean up.""" if hasattr(self, "_controller") and self._controller: self._controller.quit() self._controller.close() self._controller = None self._shutdown() if hasattr(self, "_port") and self._port: portpicker.return_port(self._port) ...
Launch the process and return the process object.
def _launch(self, run_config, args, **kwargs): """Launch the process and return the process object.""" del kwargs try: with sw("popen"): return subprocess.Popen(args, cwd=run_config.cwd, env=run_config.env) except OSError: logging.exception("Failed to launch") raise SC2LaunchEr...
Terminate the sub-process.
def _shutdown(self): """Terminate the sub-process.""" if self._proc: ret = _shutdown_proc(self._proc, 3) logging.info("Shutdown with return code: %s", ret) self._proc = None
Retrieve static data from the game.
def get_data(): """Retrieve static data from the game.""" run_config = run_configs.get() with run_config.start(want_rgb=False) as controller: m = maps.get("Sequencer") # Arbitrary ladder map. create = sc_pb.RequestCreateGame(local_map=sc_pb.LocalMap( map_path=m.path, map_data=m.data(run_config))...
Generate a CSV of the abilities for easy commenting.
def generate_csv(data): """Generate a CSV of the abilities for easy commenting.""" print(",".join([ "ability_id", "link_name", "link_index", "button_name", "hotkey", "friendly_name", "remap_to", "mismatch", ])) for ability in sorted(six.itervalues(data.abilities),...
Generate the list of functions in actions.py.
def generate_py_abilities(data): """Generate the list of functions in actions.py.""" def print_action(func_id, name, func, ab_id, general_id): args = [func_id, '"%s"' % name, func, ab_id] if general_id: args.append(general_id) print(" Function.ability(%s)," % ", ".join(str(v) for v in args)) ...
Run the agent, connecting to a (remote) host started independently.
def agent(): """Run the agent, connecting to a (remote) host started independently.""" agent_module, agent_name = FLAGS.agent.rsplit(".", 1) agent_cls = getattr(importlib.import_module(agent_module), agent_name) logging.info("Starting agent:") with remote_sc2_env.RemoteSC2Env( map_name=FLAGS.map, ...
Run a host which expects one player to connect remotely.
def human(): """Run a host which expects one player to connect remotely.""" run_config = run_configs.get() map_inst = maps.get(FLAGS.map) if not FLAGS.rgb_screen_size or not FLAGS.rgb_minimap_size: logging.info("Use --rgb_screen_size and --rgb_minimap_size if you want rgb " "observations....
Standard deviation.
def dev(self): """Standard deviation.""" if self.num == 0: return 0 return math.sqrt(max(0, self.sum_sq / self.num - (self.sum / self.num)**2))
Decorate a function/method to check its timings. To use the function's name: @sw.decorate def func(): pass To name it explicitly: @sw.decorate("name") def random_func_name(): pass Args: name_or_func: the name or the function to decorate. Returns: I...
def decorate(self, name_or_func): """Decorate a function/method to check its timings. To use the function's name: @sw.decorate def func(): pass To name it explicitly: @sw.decorate("name") def random_func_name(): pass Args: name_or_func: the name or the fu...
Parse the output below to create a new StopWatch.
def parse(s): """Parse the output below to create a new StopWatch.""" stopwatch = StopWatch() for line in s.splitlines(): if line.strip(): parts = line.split(None) name = parts[0] if name != "%": # ie not the header line rest = (float(v) for v in parts[2:]) ...
Return a string representation of the timings.
def str(self, threshold=0.1): """Return a string representation of the timings.""" if not self._times: return "" total = sum(s.sum for k, s in six.iteritems(self._times) if "." not in k) table = [["", "% total", "sum", "avg", "dev", "min", "max", "num"]] for k, v in sorted(self._times.items())...
Generate the list of units in units.py.
def generate_py_units(data): """Generate the list of units in units.py.""" units = collections.defaultdict(list) for unit in sorted(data.units, key=lambda a: a.name): if unit.unit_id in static_data.UNIT_TYPES: units[unit.race].append(unit) def print_race(name, race): print("class %s(enum.IntEnum)...
Run a set of functions in parallel, returning their results. Make sure any function you pass exits with a reasonable timeout. If it doesn't return within the timeout or the result is ignored due an exception in a separate thread it will continue to stick around until it finishes, including blocking pro...
def run(self, funcs): """Run a set of functions in parallel, returning their results. Make sure any function you pass exits with a reasonable timeout. If it doesn't return within the timeout or the result is ignored due an exception in a separate thread it will continue to stick around until it finishe...
Converts a list of dicts from datamodel query results to google chart json data. :param xcol: The name of a string column to be used has X axis on chart :param ycols: A list with the names of series cols, that can be used as numeric :param labels: A d...
def dict_to_json(xcol, ycols, labels, value_columns): """ Converts a list of dicts from datamodel query results to google chart json data. :param xcol: The name of a string column to be used has X axis on chart :param ycols: A list with the names of series co...
Help function for SQLA filters, checks for dot notation on column names. If it exists, will join the query with the model from the first part of the field name. example: Contact.created_by: if created_by is a User model, it will be joined to the query.
def get_field_setup_query(query, model, column_name): """ Help function for SQLA filters, checks for dot notation on column names. If it exists, will join the query with the model from the first part of the field name. example: Contact.created_by: if created_by is a User...
Endpoint that renders an OpenApi spec for all views that belong to a certain version --- get: parameters: - in: path schema: type: string name: version responses: 200: description: Item from Model ...
def get(self, version): """ Endpoint that renders an OpenApi spec for all views that belong to a certain version --- get: parameters: - in: path schema: type: string name: version responses: 200: ...
Adds a permission to the backend, model permission :param name: name of the permission: 'can_add','can_edit' etc...
def add_permission(self, name): """ Adds a permission to the backend, model permission :param name: name of the permission: 'can_add','can_edit' etc... """ perm = self.find_permission(name) if perm is None: try: perm = ...
Adds a view or menu to the backend, model view_menu param name: name of the view menu to add
def add_view_menu(self, name): """ Adds a view or menu to the backend, model view_menu param name: name of the view menu to add """ view_menu = self.find_view_menu(name) if view_menu is None: try: view_menu = self.viewme...
Deletes a ViewMenu from the backend :param name: name of the ViewMenu
def del_view_menu(self, name): """ Deletes a ViewMenu from the backend :param name: name of the ViewMenu """ obj = self.find_view_menu(name) if obj: try: obj.delete() except Exception as e: l...
Finds and returns a PermissionView by names
def find_permission_view_menu(self, permission_name, view_menu_name): """ Finds and returns a PermissionView by names """ permission = self.find_permission(permission_name) view_menu = self.find_view_menu(view_menu_name) if permission and view_menu: return...
Adds a permission on a view or menu to the backend :param permission_name: name of the permission to add: 'can_add','can_edit' etc... :param view_menu_name: name of the view menu to add
def add_permission_view_menu(self, permission_name, view_menu_name): """ Adds a permission on a view or menu to the backend :param permission_name: name of the permission to add: 'can_add','can_edit' etc... :param view_menu_name: name of the v...
Add permission-ViewMenu object to Role :param role: The role object :param perm_view: The PermissionViewMenu object
def add_permission_role(self, role, perm_view): """ Add permission-ViewMenu object to Role :param role: The role object :param perm_view: The PermissionViewMenu object """ if perm_view not in role.permissions: try: ...
Remove permission-ViewMenu object to Role :param role: The role object :param perm_view: The PermissionViewMenu object
def del_permission_role(self, role, perm_view): """ Remove permission-ViewMenu object to Role :param role: The role object :param perm_view: The PermissionViewMenu object """ if perm_view in role.permissions: try: ...
modified: removing the '_cls' column added by Mongoengine to support mongodb document inheritance cf. http://docs.mongoengine.org/apireference.html#documents: "A Document subclass may be itself subclassed, to create a specialised version of the document that will be stored in the...
def get_columns_list(self): """ modified: removing the '_cls' column added by Mongoengine to support mongodb document inheritance cf. http://docs.mongoengine.org/apireference.html#documents: "A Document subclass may be itself subclassed, to create a specialised version of...
Returns the columns that can be ordered :param list_columns: optional list of columns name, if provided will use this list only.
def get_order_columns_list(self, list_columns=None): """ Returns the columns that can be ordered :param list_columns: optional list of columns name, if provided will use this list only. """ ret_lst = list() list_columns = list_columns or self.get_...
return a list of pk values from object list
def get_keys(self, lst): """ return a list of pk values from object list """ pk_name = self.get_pk_name() return [getattr(item, pk_name) for item in lst]
Use this decorator to map your custom Model properties to actual Model db properties. As an example:: class MyModel(Model): id = Column(Integer, primary_key=True) name = Column(String(50), unique = True, nullable=False) custom = Column(Integer(20)) ...
def renders(col_name): """ Use this decorator to map your custom Model properties to actual Model db properties. As an example:: class MyModel(Model): id = Column(Integer, primary_key=True) name = Column(String(50), unique = True, nullable=False) ...
Get Values: formats values for list template. returns [{'col_name':'col_value',....},{'col_name':'col_value',....}] :param lst: The list of item objects from query :param list_columns: The list of columns to include
def _get_values(self, lst, list_columns): """ Get Values: formats values for list template. returns [{'col_name':'col_value',....},{'col_name':'col_value',....}] :param lst: The list of item objects from query :param list_columns: ...
Get Values: formats values for list template. returns [{'col_name':'col_value',....},{'col_name':'col_value',....}] :param lst: The list of item objects from query :param list_columns: The list of columns to include
def get_values(self, lst, list_columns): """ Get Values: formats values for list template. returns [{'col_name':'col_value',....},{'col_name':'col_value',....}] :param lst: The list of item objects from query :param list_columns: T...
Converts list of objects from query to JSON
def get_values_json(self, lst, list_columns): """ Converts list of objects from query to JSON """ result = [] for item in self.get_values(lst, list_columns): for key, value in list(item.items()): if isinstance(value, datetime.datetime) or isinstanc...
return a list of pk values from object list
def get_keys(self, lst): """ return a list of pk values from object list """ pk_name = self.get_pk_name() if self.is_pk_composite(): return [[getattr(item, pk) for pk in pk_name] for item in lst] else: return [getattr(item, pk_name) for item in...
Method for sending the registration Email to the user
def send_email(self, register_user): """ Method for sending the registration Email to the user """ try: from flask_mail import Mail, Message except Exception: log.error("Install Flask-Mail to use User registration") return False mai...
Add a registration request for the user. :rtype : RegisterUser
def add_registration(self, username, first_name, last_name, email, password=""): """ Add a registration request for the user. :rtype : RegisterUser """ register_user = self.appbuilder.sm.add_register_user( username, first_name, last_name, email, password ...
Endpoint to expose an activation url, this url is sent to the user by email, when accessed the user is inserted and activated
def activation(self, activation_hash): """ Endpoint to expose an activation url, this url is sent to the user by email, when accessed the user is inserted and activated """ reg = self.appbuilder.sm.find_register_user(activation_hash) if not reg: ...
Hackish method to make use of oid.login_handler decorator.
def oid_login_handler(self, f, oid): """ Hackish method to make use of oid.login_handler decorator. """ if request.args.get("openid_complete") != u"yes": return f(False) consumer = Consumer(SessionWrapper(self), oid.store_factory()) openid_response = consu...
Process the Python data applied to this field and store the result. This will be called during form construction by the form's `kwargs` or `obj` argument. Converting ORM object to primary key for client form. :param value: The python object containing the value to process.
def process_data(self, value): """ Process the Python data applied to this field and store the result. This will be called during form construction by the form's `kwargs` or `obj` argument. Converting ORM object to primary key for client form. :param value: The python o...
Process data received over the wire from a form. This will be called during form construction with data supplied through the `formdata` argument. Converting primary key to ORM for server processing. :param valuelist: A list of strings to process.
def process_formdata(self, valuelist): """ Process data received over the wire from a form. This will be called during form construction with data supplied through the `formdata` argument. Converting primary key to ORM for server processing. :param valuelist: A list of ...
intantiates the processing class (Direct or Grouped) and returns it.
def get_group_by_class(self, definition): """ intantiates the processing class (Direct or Grouped) and returns it. """ group_by = definition["group"] series = definition["series"] if "formatter" in definition: formatter = {group_by: definition["formatter"]...
Get page arguments, returns a dictionary { <VIEW_NAME>: PAGE_NUMBER } Arguments are passed: page_<VIEW_NAME>=<PAGE_NUMBER>
def get_page_args(): """ Get page arguments, returns a dictionary { <VIEW_NAME>: PAGE_NUMBER } Arguments are passed: page_<VIEW_NAME>=<PAGE_NUMBER> """ pages = {} for arg in request.args: re_match = re.findall("page_(.*)", arg) if re_match: pages[re_...
Get page size arguments, returns an int { <VIEW_NAME>: PAGE_NUMBER } Arguments are passed: psize_<VIEW_NAME>=<PAGE_SIZE>
def get_page_size_args(): """ Get page size arguments, returns an int { <VIEW_NAME>: PAGE_NUMBER } Arguments are passed: psize_<VIEW_NAME>=<PAGE_SIZE> """ page_sizes = {} for arg in request.args: re_match = re.findall("psize_(.*)", arg) if re_match: ...
Get order arguments, return a dictionary { <VIEW_NAME>: (ORDER_COL, ORDER_DIRECTION) } Arguments are passed like: _oc_<VIEW_NAME>=<COL_NAME>&_od_<VIEW_NAME>='asc'|'desc'
def get_order_args(): """ Get order arguments, return a dictionary { <VIEW_NAME>: (ORDER_COL, ORDER_DIRECTION) } Arguments are passed like: _oc_<VIEW_NAME>=<COL_NAME>&_od_<VIEW_NAME>='asc'|'desc' """ orders = {} for arg in request.args: re_match = re.findall("_oc_(.*)",...
Creates ModelSchema marshmallow-sqlalchemy :param columns: a list of columns to mix :param model: Model :param class_mixin: a marshamallow Schema to mix :return: ModelSchema
def _meta_schema_factory(self, columns, model, class_mixin): """ Creates ModelSchema marshmallow-sqlalchemy :param columns: a list of columns to mix :param model: Model :param class_mixin: a marshamallow Schema to mix :return: ModelSchema """ _model =...
Creates a Marshmallow ModelSchema class :param columns: List with columns to include, if empty converts all on model :param model: Override Model to convert :param nested: Generate relation with nested schemas :return: ModelSchema object
def convert(self, columns, model=None, nested=True, enum_dump_by_name=False): """ Creates a Marshmallow ModelSchema class :param columns: List with columns to include, if empty converts all on model :param model: Override Model to convert :param nested: Generate relation wi...
Use this decorator to enable granular security permissions to your API methods (BaseApi and child classes). Permissions will be associated to a role, and roles are associated to users. allow_browser_login will accept signed cookies obtained from the normal MVC app:: class MyApi(Bas...
def protect(allow_browser_login=False): """ Use this decorator to enable granular security permissions to your API methods (BaseApi and child classes). Permissions will be associated to a role, and roles are associated to users. allow_browser_login will accept signed cookies obtaine...
Use this decorator to enable granular security permissions to your methods. Permissions will be associated to a role, and roles are associated to users. By default the permission's name is the methods name.
def has_access(f): """ Use this decorator to enable granular security permissions to your methods. Permissions will be associated to a role, and roles are associated to users. By default the permission's name is the methods name. """ if hasattr(f, '_permission_name'): permis...
Use this decorator to enable granular security permissions to your API methods. Permissions will be associated to a role, and roles are associated to users. By default the permission's name is the methods name. this will return a message and HTTP 401 is case of unauthorized access.
def has_access_api(f): """ Use this decorator to enable granular security permissions to your API methods. Permissions will be associated to a role, and roles are associated to users. By default the permission's name is the methods name. this will return a message and HTTP 401 is c...
Default function to return the current user oauth token from session cookie.
def _oauth_tokengetter(token=None): """ Default function to return the current user oauth token from session cookie. """ token = session.get("oauth") log.debug("Token Get: {0}".format(token)) return token
Override to implement your custom login manager instance :param app: Flask app
def create_login_manager(self, app) -> LoginManager: """ Override to implement your custom login manager instance :param app: Flask app """ lm = LoginManager(app) lm.login_view = "login" lm.user_loader(self.load_user) return lm
Override to implement your custom JWT manager instance :param app: Flask app
def create_jwt_manager(self, app) -> JWTManager: """ Override to implement your custom JWT manager instance :param app: Flask app """ jwt_manager = JWTManager() jwt_manager.init_app(app) jwt_manager.user_loader_callback_loader(self.load_user) retu...
Decorator function to be the OAuth user info getter for all the providers, receives provider and response return a dict with the information returned from the provider. The returned user info dict should have it's keys with the same name as the User Model. Us...
def oauth_user_info_getter(self, f): """ Decorator function to be the OAuth user info getter for all the providers, receives provider and response return a dict with the information returned from the provider. The returned user info dict should have it's keys with...
Returns the token_key name for the oauth provider if none is configured defaults to oauth_token this is configured using OAUTH_PROVIDERS and token_key key.
def get_oauth_token_key_name(self, provider): """ Returns the token_key name for the oauth provider if none is configured defaults to oauth_token this is configured using OAUTH_PROVIDERS and token_key key. """ for _provider in self.oauth_providers: ...
Returns the token_secret name for the oauth provider if none is configured defaults to oauth_secret this is configured using OAUTH_PROVIDERS and token_secret
def get_oauth_token_secret_name(self, provider): """ Returns the token_secret name for the oauth provider if none is configured defaults to oauth_secret this is configured using OAUTH_PROVIDERS and token_secret """ for _provider in self.oauth_providers: ...
Set the current session with OAuth user secrets
def set_oauth_session(self, provider, oauth_response): """ Set the current session with OAuth user secrets """ # Get this provider key names for token_key and token_secret token_key = self.appbuilder.sm.get_oauth_token_key_name(provider) token_secret = self.appbuilder...
Since there are different OAuth API's with different ways to retrieve user info
def get_oauth_user_info(self, provider, resp): """ Since there are different OAuth API's with different ways to retrieve user info """ # for GITHUB if provider == "github" or provider == "githublocal": me = self.appbuilder.sm.oauth_remotes[provider].ge...
Setups the DB, creates admin and public roles if they don't exist.
def create_db(self): """ Setups the DB, creates admin and public roles if they don't exist. """ self.add_role(self.auth_role_admin) self.add_role(self.auth_role_public) if self.count_users() == 0: log.warning(LOGMSG_WAR_SEC_NO_USER)
Change/Reset a user's password for authdb. Password will be hashed and saved. :param userid: the user.id to reset the password :param password: The clear text password to reset and save hashed on the db
def reset_password(self, userid, password): """ Change/Reset a user's password for authdb. Password will be hashed and saved. :param userid: the user.id to reset the password :param password: The clear text password to reset and sa...
Update authentication successful to user. :param user: The authenticated user model :param success: Default to true, if false increments fail_login_count on user model
def update_user_auth_stat(self, user, success=True): """ Update authentication successful to user. :param user: The authenticated user model :param success: Default to true, if false increments fail_login_count on user model """ ...
Method for authenticating user, auth db style :param username: The username or registered email address :param password: The password, will be tested against hashed password on db
def auth_user_db(self, username, password): """ Method for authenticating user, auth db style :param username: The username or registered email address :param password: The password, will be tested against hashed password on db """ ...
Searches LDAP for user, assumes ldap_search is set. :param ldap: The ldap module reference :param con: The ldap connection :param username: username to match with auth_ldap_uid_field :return: ldap object array
def _search_ldap(self, ldap, con, username): """ Searches LDAP for user, assumes ldap_search is set. :param ldap: The ldap module reference :param con: The ldap connection :param username: username to match with auth_ldap_uid_field :return: ldap objec...
If using AUTH_LDAP_BIND_USER bind this user before performing search :param ldap: The ldap module reference :param con: The ldap connection
def _bind_indirect_user(self, ldap, con): """ If using AUTH_LDAP_BIND_USER bind this user before performing search :param ldap: The ldap module reference :param con: The ldap connection """ indirect_user = self.auth_ldap_bind_user if indirect_user: ...
Private to bind/Authenticate a user. If AUTH_LDAP_BIND_USER exists then it will bind first with it, next will search the LDAP server using the username with UID and try to bind to it (OpenLDAP). If AUTH_LDAP_BIND_USER does not exit, will bind with username/password
def _bind_ldap(self, ldap, con, username, password): """ Private to bind/Authenticate a user. If AUTH_LDAP_BIND_USER exists then it will bind first with it, next will search the LDAP server using the username with UID and try to bind to it (OpenLDAP). ...
Method for authenticating user, auth LDAP style. depends on ldap module that is not mandatory requirement for F.A.B. :param username: The username :param password: The password
def auth_user_ldap(self, username, password): """ Method for authenticating user, auth LDAP style. depends on ldap module that is not mandatory requirement for F.A.B. :param username: The username :param password: The p...
OpenID user Authentication :param email: user's email to authenticate :type self: User model
def auth_user_oid(self, email): """ OpenID user Authentication :param email: user's email to authenticate :type self: User model """ user = self.find_user(email=email) if user is None or (not user.is_active): log.info(LOGMSG_WAR_SEC_LOGIN_...
REMOTE_USER user Authentication :param username: user's username for remote auth :type self: User model
def auth_user_remote_user(self, username): """ REMOTE_USER user Authentication :param username: user's username for remote auth :type self: User model """ user = self.find_user(username=username) # User does not exist, create one if auto user registr...
OAuth user Authentication :userinfo: dict with user information the keys have the same name as User model columns.
def auth_user_oauth(self, userinfo): """ OAuth user Authentication :userinfo: dict with user information the keys have the same name as User model columns. """ if "username" in userinfo: user = self.find_user(username=userinfo["username"]) ...
Check if view has public permissions :param permission_name: the permission: can_show, can_edit... :param view_name: the name of the class view (child of BaseView)
def is_item_public(self, permission_name, view_name): """ Check if view has public permissions :param permission_name: the permission: can_show, can_edit... :param view_name: the name of the class view (child of BaseView) """ p...
Check if current user or public has access to view or menu
def has_access(self, permission_name, view_name): """ Check if current user or public has access to view or menu """ if current_user.is_authenticated: return self._has_view_access(g.user, permission_name, view_name) elif current_user_jwt: return self._...
Returns all current user permissions on a certain view/resource :param view_name: The name of the view/resource/menu :return: (list) with permissions
def get_user_permissions_on_view(view_name): """ Returns all current user permissions on a certain view/resource :param view_name: The name of the view/resource/menu :return: (list) with permissions """ _ret = list() if current_user.is_authenticat...
Adds a permission on a view menu to the backend :param base_permissions: list of permissions from view (all exposed methods): 'can_add','can_edit' etc... :param view_menu: name of the view or menu to add
def add_permissions_view(self, base_permissions, view_menu): """ Adds a permission on a view menu to the backend :param base_permissions: list of permissions from view (all exposed methods): 'can_add','can_edit' etc... :param view_menu: ...
Adds menu_access to menu on permission_view_menu :param view_menu_name: The menu name
def add_permissions_menu(self, view_menu_name): """ Adds menu_access to menu on permission_view_menu :param view_menu_name: The menu name """ self.add_view_menu(view_menu_name) pv = self.find_permission_view_menu("menu_access", view_menu_name) ...
Will cleanup all unused permissions from the database :param baseviews: A list of BaseViews class :param menus: Menu class
def security_cleanup(self, baseviews, menus): """ Will cleanup all unused permissions from the database :param baseviews: A list of BaseViews class :param menus: Menu class """ viewsmenus = self.get_all_view_menu() roles = self.get_all_roles() ...
Send a greeting --- get: responses: 200: description: Greet the user content: application/json: schema: type: object properties: message: ...
def greeting2(self): """Send a greeting --- get: responses: 200: description: Greet the user content: application/json: schema: type: object properties: ...
Adds list of dicts :param data: list of dicts :return:
def rest_add_filters(self, data): """ Adds list of dicts :param data: list of dicts :return: """ for _filter in data: filter_class = map_args_filter.get(_filter["opr"], None) if filter_class: self.add_filter(_filter["col"], fil...
Creates a new filters class with active filters joined
def get_joined_filters(self, filters): """ Creates a new filters class with active filters joined """ retfilters = Filters(self.filter_converter, self.datamodel) retfilters.filters = self.filters + filters.filters retfilters.values = self.values + filters.values ...
Returns a copy of this object :return: A copy of self
def copy(self): """ Returns a copy of this object :return: A copy of self """ retfilters = Filters(self.filter_converter, self.datamodel) retfilters.filters = copy.copy(self.filters) retfilters.values = copy.copy(self.values) return retfilters
Returns the filter active FilterRelation cols
def get_relation_cols(self): """ Returns the filter active FilterRelation cols """ retlst = [] for flt, value in zip(self.filters, self.values): if isinstance(flt, FilterRelation) and value: retlst.append(flt.column_name) return retlst
Returns a list of tuples [(FILTER, value),(...,...),....]
def get_filters_values(self): """ Returns a list of tuples [(FILTER, value),(...,...),....] """ return [(flt, value) for flt, value in zip(self.filters, self.values)]
Returns the filtered value for a certain column :param column_name: The name of the column that we want the value from :return: the filter value of the column
def get_filter_value(self, column_name): """ Returns the filtered value for a certain column :param column_name: The name of the column that we want the value from :return: the filter value of the column """ for flt, value in zip(self.filters, self.values): ...
Finds a menu item by name and returns it. :param name: The menu item name.
def find(self, name, menu=None): """ Finds a menu item by name and returns it. :param name: The menu item name. """ menu = menu or self.menu for i in menu: if i.name == name: return i else: i...