INSTRUCTION
stringlengths
1
8.43k
RESPONSE
stringlengths
75
104k
Fill this surface using the contents of a numpy array.
def blit_np_array(self, array): """Fill this surface using the contents of a numpy array.""" with sw("make_surface"): raw_surface = pygame.surfarray.make_surface(array.transpose([1, 0, 2])) with sw("draw"): pygame.transform.scale(raw_surface, self.surf.get_size(), self.surf)
Write to the screen in font. size relative coordinates.
def write_screen(self, font, color, screen_pos, text, align="left", valign="top"): """Write to the screen in font.size relative coordinates.""" pos = point.Point(*screen_pos) * point.Point(0.75, 1) * font.get_linesize() text_surf = font.render(str(text), True, color) rect = text_surf....
Given an Action return the right spatial action.
def action_spatial(self, action): """Given an Action, return the right spatial action.""" if self.surf.surf_type & SurfType.FEATURE: return action.action_feature_layer elif self.surf.surf_type & SurfType.RGB: return action.action_render else: assert self.surf.surf_type & (SurfType.RGB ...
Take the game info and the static data needed to set up the game.
def init(self, game_info, static_data): """Take the game info and the static data needed to set up the game. This must be called before render or get_actions for each game or restart. Args: game_info: A `sc_pb.ResponseGameInfo` object for this game. static_data: A `StaticData` object for this ...
Initialize the pygame window and lay out the surfaces.
def init_window(self): """Initialize the pygame window and lay out the surfaces.""" if platform.system() == "Windows": # Enable DPI awareness on Windows to give the correct window size. ctypes.windll.user32.SetProcessDPIAware() # pytype: disable=module-attr pygame.init() if self._desktop_...
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) if self._feature_screen_px: camera_radius...
Return a MousePos filled with the world position and surf it hit.
def get_mouse_pos(self, window_pos=None): """Return a MousePos filled with the world position and surf it hit.""" window_pos = window_pos or pygame.mouse.get_pos() # +0.5 to center the point on the middle of the pixel. window_pt = point.Point(*window_pos) + 0.5 for surf in reversed(self._surfaces): ...
Get actions from the UI apply to controller and return an ActionCmd.
def get_actions(self, run_config, controller): """Get actions from the UI, apply to controller, and return an ActionCmd.""" if not self._initialized: return ActionCmd.STEP for event in pygame.event.get(): ctrl = pygame.key.get_mods() & pygame.KMOD_CTRL shift = pygame.key.get_mods() & pyga...
Return a sc_pb. Action with the camera movement filled.
def camera_action(self, mouse_pos): """Return a `sc_pb.Action` with the camera movement filled.""" action = sc_pb.Action() action_spatial = mouse_pos.action_spatial(action) mouse_pos.obs_pos.assign_to(action_spatial.camera_move.center_minimap) return action
Return a sc_pb. Action with the camera movement filled.
def camera_action_raw(self, world_pos): """Return a `sc_pb.Action` with the camera movement filled.""" action = sc_pb.Action() world_pos.assign_to(action.action_raw.camera_move.center_world_space) return action
Return a sc_pb. Action with the selection filled.
def select_action(self, pos1, pos2, ctrl, shift): """Return a `sc_pb.Action` with the selection filled.""" assert pos1.surf.surf_type == pos2.surf.surf_type assert pos1.surf.world_to_obs == pos2.surf.world_to_obs action = sc_pb.Action() action_spatial = pos1.action_spatial(action) if pos1.worl...
Select an idle worker.
def select_idle_worker(self, ctrl, shift): """Select an idle worker.""" action = sc_pb.Action() mod = sc_ui.ActionSelectIdleWorker if ctrl: select_worker = mod.AddAll if shift else mod.All else: select_worker = mod.Add if shift else mod.Set action.action_ui.select_idle_worker.type = ...
Select the entire army.
def select_army(self, shift): """Select the entire army.""" action = sc_pb.Action() action.action_ui.select_army.selection_add = shift return action
Select all warp gates.
def select_warp_gates(self, shift): """Select all warp gates.""" action = sc_pb.Action() action.action_ui.select_warp_gates.selection_add = shift return action
Select all larva.
def select_larva(self): """Select all larva.""" action = sc_pb.Action() action.action_ui.select_larva.SetInParent() # Adds the empty proto field. return action
Act on a control group selecting setting etc.
def control_group(self, control_group_id, ctrl, shift, alt): """Act on a control group, selecting, setting, etc.""" action = sc_pb.Action() select = action.action_ui.control_group mod = sc_ui.ActionControlGroup if not ctrl and not shift and not alt: select.action = mod.Recall elif ctrl an...
Return a sc_pb. Action filled with the cmd and appropriate target.
def unit_action(self, cmd, pos, shift): """Return a `sc_pb.Action` filled with the cmd and appropriate target.""" action = sc_pb.Action() if pos: action_spatial = pos.action_spatial(action) unit_command = action_spatial.unit_command unit_command.ability_id = cmd.ability_id unit_comma...
Return the list of abilities filtered by fn.
def _abilities(self, fn=None): """Return the list of abilities filtered by `fn`.""" out = {} for cmd in self._obs.observation.abilities: ability = _Ability(cmd, self._static_data.abilities) if not fn or fn(ability): out[ability.ability_id] = ability return list(out.values())
A generator of visible units and their positions as Point s sorted.
def _visible_units(self): """A generator of visible units and their positions as `Point`s, sorted.""" # Sort the units by elevation, then owned (eg refinery) above world (ie 16) # (eg geiser), small above big, and otherwise arbitrary but stable. for u in sorted(self._obs.observation.raw_data.units, ...
Return the list of units that intersect the rect.
def _units_in_area(self, rect): """Return the list of units that intersect the rect.""" player_id = self._obs.observation.player_common.player_id return [u for u, p in self._visible_units() if rect.intersects_circle(p, u.radius) and u.owner == player_id]
Get a length limited unit name for drawing units.
def get_unit_name(self, surf, name, radius): """Get a length limited unit name for drawing units.""" key = (name, radius) if key not in self._name_lengths: max_len = surf.world_to_surf.fwd_dist(radius * 1.6) for i in range(len(name)): if self._font_small.size(name[:i + 1])[0] > max_len: ...
Draw the units and buildings.
def draw_units(self, surf): """Draw the units and buildings.""" for u, p in self._visible_units(): if self._camera.intersects_circle(p, u.radius): fraction_damage = clamp((u.health_max - u.health) / (u.health_max or 1), 0, 1) surf.draw_circle(colors.PLAYER_A...
Draw the selection rectange.
def draw_selection(self, surf): """Draw the selection rectange.""" select_start = self._select_start # Cache to avoid a race condition. if select_start: mouse_pos = self.get_mouse_pos() if (mouse_pos and mouse_pos.surf.surf_type & SurfType.SCREEN and mouse_pos.surf.surf_type == select...
Draw the build target.
def draw_build_target(self, surf): """Draw the build target.""" round_half = lambda v, cond: round(v - 0.5) + 0.5 if cond else round(v) queued_action = self._queued_action if queued_action: radius = queued_action.footprint_radius if radius: pos = self.get_mouse_pos() if pos:...
Draw the overlay describing resources.
def draw_overlay(self, surf): """Draw the overlay describing resources.""" obs = self._obs.observation player = obs.player_common surf.write_screen( self._font_large, colors.green, (0.2, 0.2), "Minerals: %s, Vespene: %s, Food: %s / %s" % ( player.minerals, player.vespene, pla...
Draw the help dialog.
def draw_help(self, surf): """Draw the help dialog.""" if not self._help: return def write(loc, text): surf.write_screen(self._font_large, colors.black, loc, text) surf.surf.fill(colors.white * 0.8) write((1, 1), "Shortcuts:") max_len = max(len(s) for s, _ in self.shortcuts) f...
Draw the list of available commands.
def draw_commands(self, surf): """Draw the list of available commands.""" past_abilities = {act.ability for act in self._past_actions if act.ability} for y, cmd in enumerate(sorted(self._abilities( lambda c: c.name != "Smart"), key=lambda c: c.name), start=2): if self._queued_action and cmd ==...
Draw the unit selection or build queue.
def draw_panel(self, surf): """Draw the unit selection or build queue.""" left = -12 # How far from the right border def unit_name(unit_type): return self._static_data.units.get(unit_type, "<unknown>") def write(loc, text, color=colors.yellow): surf.write_screen(self._font_large, color, ...
Draw the actions so that they can be inspected for accuracy.
def draw_actions(self): """Draw the actions so that they can be inspected for accuracy.""" now = time.time() for act in self._past_actions: if act.pos and now < act.deadline: remain = (act.deadline - now) / (act.deadline - act.time) if isinstance(act.pos, point.Point): size =...
Keep a list of the past actions so they can be drawn.
def prepare_actions(self, obs): """Keep a list of the past actions so they can be drawn.""" now = time.time() while self._past_actions and self._past_actions[0].deadline < now: self._past_actions.pop(0) def add_act(ability_id, color, pos, timeout=1): if ability_id: ability = self._s...
Draw the base map.
def draw_base_map(self, surf): """Draw the base map.""" hmap_feature = features.SCREEN_FEATURES.height_map hmap = hmap_feature.unpack(self._obs.observation) if not hmap.any(): hmap = hmap + 100 # pylint: disable=g-no-augmented-assignment hmap_color = hmap_feature.color(hmap) creep_featur...
Draw the minimap.
def draw_mini_map(self, surf): """Draw the minimap.""" if (self._render_rgb and self._obs.observation.HasField("render_data") and self._obs.observation.render_data.HasField("minimap")): # Draw the rendered version. surf.blit_np_array(features.Feature.unpack_rgb_image( self._obs.obs...
Draw the rendered pixels.
def draw_rendered_map(self, surf): """Draw the rendered pixels.""" surf.blit_np_array(features.Feature.unpack_rgb_image( self._obs.observation.render_data.map))
Draw the screen area.
def draw_screen(self, surf): """Draw the screen area.""" # surf.fill(colors.black) if (self._render_rgb and self._obs.observation.HasField("render_data") and self._obs.observation.render_data.HasField("map")): self.draw_rendered_map(surf) else: self.draw_base_map(surf) self.dra...
Draw a feature layer.
def draw_feature_layer(self, surf, feature): """Draw a feature layer.""" layer = feature.unpack(self._obs.observation) if layer is not None: surf.blit_np_array(feature.color(layer)) else: # Ignore layers that aren't in this version of SC2. surf.surf.fill(colors.black)
Push an observation onto the queue to be rendered.
def render(self, obs): """Push an observation onto the queue to be rendered.""" if not self._initialized: return now = time.time() self._game_times.append( (now - self._last_time, max(1, obs.observation.game_loop - self._obs.observation.game_loop))) self._last_time = now s...
A render loop that pulls observations off the queue to render.
def render_thread(self): """A render loop that pulls observations off the queue to render.""" obs = True while obs: # Send something falsy through the queue to shut down. obs = self._obs_queue.get() if obs: for alert in obs.observation.alerts: self._alerts[sc_pb.Alert.Name(ale...
Render a frame given an observation.
def render_obs(self, obs): """Render a frame given an observation.""" start_time = time.time() self._obs = obs self.check_valid_queued_action() self._update_camera(point.Point.build( self._obs.observation.raw_data.player.camera)) for surf in self._surfaces: # Render that surface. ...
Run loop that gets observations renders them and sends back actions.
def run(self, run_config, controller, max_game_steps=0, max_episodes=0, game_steps_per_episode=0, save_replay=False): """Run loop that gets observations, renders them, and sends back actions.""" is_replay = (controller.status == remote_controller.Status.in_replay) total_game_steps = 0 start_ti...
A context manager that translates websocket errors into ConnectionError.
def catch_websocket_connection_errors(): """A context manager that translates websocket errors into ConnectionError.""" try: yield except websocket.WebSocketConnectionClosedException: raise ConnectionError("Connection already closed. SC2 probably crashed. " "Check the error log."...
Read a Response do some validation and return it.
def read(self): """Read a Response, do some validation, and return it.""" if FLAGS.sc2_verbose_protocol: self._log(" Reading response ".center(60, "-")) start = time.time() response = self._read() if FLAGS.sc2_verbose_protocol: self._log(" %0.1f msec\n" % (1000 * (time.time() - start))...
Write a Request.
def write(self, request): """Write a Request.""" if FLAGS.sc2_verbose_protocol: self._log(" Writing request ".center(60, "-") + "\n") self._log_packet(request) self._write(request)
Create and send a specific request and return the response.
def send(self, **kwargs): """Create and send a specific request, and return the response. For example: send(ping=sc_pb.RequestPing()) => sc_pb.ResponsePing Args: **kwargs: A single kwarg with the name and value to fill in to Request. Returns: The Response corresponding to your request. ...
r Log a string. It flushes but doesn t append \ n so do that yourself.
def _log(self, s): r"""Log a string. It flushes but doesn't append \n, so do that yourself.""" # TODO(tewalds): Should this be using logging.info instead? How to see them # outside of google infrastructure? sys.stderr.write(s) sys.stderr.flush()
Actually read the response and parse it returning a Response.
def _read(self): """Actually read the response and parse it, returning a Response.""" with sw("read_response"): with catch_websocket_connection_errors(): response_str = self._sock.recv() if not response_str: raise ProtocolError("Got an empty response from SC2.") response = sc_pb.Resp...
Actually serialize and write the request.
def _write(self, request): """Actually serialize and write the request.""" with sw("serialize_request"): request_str = request.SerializeToString() with sw("write_request"): with catch_websocket_connection_errors(): self._sock.send(request_str)
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.
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.
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)
Initialize the camera ( especially for feature_units ).
def init_camera( self, feature_dimensions, map_size, camera_width_world_units): """Initialize the camera (especially for feature_units). This is called in the constructor and may be called repeatedly after `Features` is constructed, since it deals with rescaling coordinates and not changing envir...
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.
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.
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.
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.
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.
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.
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...
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 content: application/ json: schema: type: object 404: $ref: #/ components/ responses/ 404 500: $ref: #/ components/ respons...
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: ...
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.
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...
Adds a permission to the backend model permission
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
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
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
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
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 same collection. To facilitate this be...
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
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::
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.... } ]
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.... } ]
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...