code stringlengths 1 18.2k |
|---|
self.current.lane_name)) if self.current.lane_auto_sendoff: self.current.sendoff_current_user() self.current.flow_enabled = False if self.current.lane_auto_invite: self.current.invite_other_parties(self._get_possible_lane_owners()) return True |
def parse_workflow_messages(self): """ Transmits client message that defined in a workflow task's inputOutput extension .. code-block:: xml <bpmn2:extensionElements> <camunda:inputOutput> <camunda:inputParameter name="client_message"> <camunda:map> <camunda:entry key="title">Teşekkürler</camunda:entry> <camunda:entry k... |
def run_activity(self): """ runs the method that referenced from current task """ activity = self.current.activity if activity: if activity not in self.wf_activities: self._load_activity(activity) self.current.log.debug( "Calling Activity %s from %s" % (activity, self.wf_activities[activity])) self.wf_activities[self.c... |
def _import_object(self, path, look_for_cls_method): """ Imports the module that contains the referenced method. Args: path: python path of class/function look_for_cls_method (bool): If True, treat the last part of path as class method. Returns: Tuple. (class object, class name, method to be called) """ last_nth = 2 if... |
and path[-last_nth:][0] == path[-last_nth]: class_method = path[-last_nth:][1] else: class_method = None return getattr(module, class_name), class_name, class_method |
def _load_activity(self, activity): """ Iterates trough the all enabled `~zengine.settings.ACTIVITY_MODULES_IMPORT_PATHS` to find the given path. """ fpths = [] full_path = '' errors = [] paths = settings.ACTIVITY_MODULES_IMPORT_PATHS number_of_paths = len(paths) for index_no in range(number_of_paths): full_path = "%s.... |
%s(current).%s()" % (kls, cls_method)) self.wf_activities[activity] = lambda crnt: getattr(kls(crnt), cls_method)() else: self.wf_activities[activity] = kls return except (ImportError, AttributeError): fpths.append(full_path) errmsg = "{activity} not found under these paths:\n\n >>> {paths} \n\n" \ "Error Messages:\n {... |
def check_for_authentication(self): """ Checks current workflow against :py:data:`~zengine.settings.ANONYMOUS_WORKFLOWS` list. Raises: HTTPUnauthorized: if WF needs an authenticated user and current user isn't. """ auth_required = self.current.workflow_name not in settings.ANONYMOUS_WORKFLOWS if auth_required and not s... |
def check_for_lane_permission(self): """ One or more permissions can be associated with a lane of a workflow. In a similar way, a lane can be restricted with relation to other lanes of the workflow. This method called on lane changes and checks user has required permissions and relations. Raises: HTTPForbidden: if the ... |
Cache lane_data in app memory if self.current.lane_permission: log.debug("HAS LANE PERM: %s" % self.current.lane_permission) perm = self.current.lane_permission if not self.current.has_permission(perm): raise HTTPError(403, "You don't have required lane permission: %s" % perm) if self.current.lane_relations: context = ... |
ERR: %s %s" % (self.current.lane_relations, context)) raise HTTPError(403, "You aren't qualified for this lane: %s" % self.current.lane_relations) |
def check_for_permission(self): # TODO: Works but not beautiful, needs review! """ Checks if current user (or role) has the required permission for current workflow step. Raises: HTTPError: if user doesn't have required permissions. """ if self.current.task: lane = self.current.lane_id permission = "%s.%s.%s" % (self.c... |
and permission.startswith(tuple(settings.COMMON_WORKFLOWS)))): return # FIXME:needs hardening log.debug("REQUIRE PERM: %s" % permission) if not self.current.has_permission(permission): raise HTTPError(403, "You don't have required permission: %s" % permission) |
def handle_wf_finalization(self): """ Removes the ``token`` key from ``current.output`` if WF is over. """ if ((not self.current.flow_enabled or ( self.current.task_type.startswith('End') and not self.are_we_in_subprocess())) and 'token' in self.current.output): del self.current.output['token'] |
def from_rdkit_molecule(data): """ RDKit molecule object to MoleculeContainer converter """ m = MoleculeContainer() atoms, mapping = [], [] for a in data.GetAtoms(): atom = {'element': a.GetSymbol(), 'charge': a.GetFormalCharge()} atoms.append(atom) mapping.append(a.GetAtomMapNum()) isotope = a.GetIsotope() if isotope:... |
atom['y'] = y atom['z'] = z for atom, mapping in zip(atoms, mapping): a = m.add_atom(atom) if mapping: m.atom(a)._parsed_mapping = mapping for bond in data.GetBonds(): m.add_bond(bond.GetBeginAtomIdx() + 1, bond.GetEndAtomIdx() + 1, _rdkit_bond_map[bond.GetBondType()]) return m |
def to_rdkit_molecule(data): """ MoleculeContainer to RDKit molecule object converter """ mol = RWMol() conf = Conformer() mapping = {} is_3d = False for n, a in data.atoms(): ra = Atom(a.number) ra.SetAtomMapNum(n) if a.charge: ra.SetFormalCharge(a.charge) if a.isotope != a.common_isotope: ra.SetIsotope(a.isotope) if ... |
in data.bonds(): mol.AddBond(mapping[n], mapping[m], _bond_map[b.order]) mol.AddConformer(conf) SanitizeMol(mol) return mol |
def __dfs(self, start, weights, depth_limit): """ modified NX dfs """ adj = self._adj stack = [(start, depth_limit, iter(sorted(adj[start], key=weights)))] visited = {start} disconnected = defaultdict(list) edges = defaultdict(list) while stack: parent, depth_now, children = stack[-1] try: child = next(children) except... |
1, iter(sorted(front, key=weights)))) elif child not in disconnected: disconnected[parent].append(child) return visited, edges, disconnected |
def get_args_parser(): """Return a parser for command line options.""" parser = argparse.ArgumentParser( description='Marabunta: Migrating ants for Odoo') parser.add_argument('--migration-file', '-f', action=EnvDefault, envvar='MARABUNTA_MIGRATION_FILE', required=True, help='The yaml file containing the migration steps... |
database host") parser.add_argument('--mode', action=EnvDefault, envvar='MARABUNTA_MODE', required=False, help="Specify the mode in which we run the migration," "such as 'demo' or 'prod'. Additional operations " "of this mode will be executed after the main " "operations and the addons list of this mode " "will be merg... |
' 'time.') parser.add_argument('--force-version', required=False, default=os.environ.get('MARABUNTA_FORCE_VERSION'), help='Force upgrade of a version, even if it has ' 'already been applied.') group = parser.add_argument_group( title='Web', description='Configuration related to the internal web server, ' 'used to publi... |
to a custom html file to publish') return parser |
def from_parse_args(cls, args): """Constructor from command line args. :param args: parse command line arguments :type args: argparse.ArgumentParser """ return cls(args.migration_file, args.database, db_user=args.db_user, db_password=args.db_password, db_port=args.db_port, db_host=args.db_host, mode=args.mode, allow_se... |
def set_current(self, current): """ Creates some aliases for attributes of ``current``. Args: current: :attr:`~zengine.engine.WFCurrent` object. """ self.current = current self.input = current.input # self.req = current.request # self.resp = current.response self.output = current.output self.cmd = current.task_data['cm... |
def form_out(self, _form=None): """ Renders form. Applies form modifiers, then writes result to response payload. If supplied, given form object instance will be used instead of view's default ObjectForm. Args: _form (:py:attr:`~zengine.forms.json_form.JsonForm`): Form object to override `self.object_form` """ _form = ... |
def set_client_cmd(self, *args): """ Adds given cmd(s) to ``self.output['client_cmd']`` Args: *args: Client commands. """ self.client_cmd.update(args) self.output['client_cmd'] = list(self.client_cmd) |
def run(self): """ Creates new permissions. """ from pyoko.lib.utils import get_object_from_path from zengine.config import settings model = get_object_from_path(settings.PERMISSION_MODEL) perm_provider = get_object_from_path(settings.PERMISSION_PROVIDER) existing_perms = [] new_perms = [] for code, name, desc in perm_... |
except ObjectDoesNotExist: perm = model(description=desc, code=code, name=name) perm.key = code perm.save() new_perms.append(perm) # perm, new = model.objects.get_or_create({'description': desc}, code=code, name=name) # if new: # new_perms.append(perm) # else: # existing_perms.append(perm) report = "\n\n%s permission(s... |
self.manager.args.dry: SelectBoxCache.flush(model.__name__) report += 'Total %s perms exists.' % (len(existing_perms) + len(new_perms)) report = "\n + " + "\n + ".join([p.name or p.code for p in new_perms]) + report if self.manager.args.dry: print("\n~~~~~~~~~~~~~~ DRY RUN ~~~~~~~~~~~~~~\n") print(report + "\n") |
def run(self): """ Creates user, encrypts password. """ from zengine.models import User user = User(username=self.manager.args.username, superuser=self.manager.args.super) user.set_password(self.manager.args.password) user.save() print("New user created with ID: %s" % user.key) |
def run(self): """ Starts a development server for the zengine application """ print("Development server started on http://%s:%s. \n\nPress Ctrl+C to stop\n" % ( self.manager.args.addr, self.manager.args.port) ) if self.manager.args.server_type == 'falcon': self.run_with_falcon() elif self.manager.args.server_type == '... |
def run_with_tornado(self): """ runs the tornado/websockets based test server """ from zengine.tornado_server.server import runserver runserver(self.manager.args.addr, int(self.manager.args.port)) |
def run_with_falcon(self): """ runs the falcon/http based test server """ from wsgiref import simple_server from zengine.server import app httpd = simple_server.make_server(self.manager.args.addr, int(self.manager.args.port), app) httpd.serve_forever() |
def run(self): """ Starts a development server for the zengine application """ from zengine.wf_daemon import run_workers, Worker worker_count = int(self.manager.args.workers or 1) if not self.manager.args.daemonize: print("Starting worker(s)") if worker_count > 1 or self.manager.args.autoreload: run_workers(worker_coun... |
def _prepare_domain(mapping): """Prepare a helper dictionary for the domain to temporarily hold some information.""" # Parse the domain-directory mapping try: domain, dir = mapping.split(':') except ValueError: print("Please provide the sources in the form of '<domain>:<directory>'") sys.exit(1) try: default_language =... |
file to hold the `.pot` file for this domain handle, path = tempfile.mkstemp(prefix='zengine_i18n_', suffix='.pot') return (domain, { 'default': default_language, 'pot': path, 'source': dir, }) |
def _validate_domains(domains): """Check that all domains specified in the settings was provided in the options.""" missing = set(settings.TRANSLATION_DOMAINS.keys()) - set(domains.keys()) if missing: print('The following domains have been set in the configuration, ' 'but their sources were not provided, use the `--sou... |
def _extract_translations(self, domains): """Extract the translations into `.pot` files""" for domain, options in domains.items(): # Create the extractor extractor = babel_frontend.extract_messages() extractor.initialize_options() # The temporary location to write the `.pot` file extractor.output_file = options['pot'] ... |
for this domain are located extractor.input_paths = [options['source']] # Pass the metadata to the translator extractor.msgid_bugs_address = self.manager.args.contact extractor.copyright_holder = self.manager.args.copyright extractor.version = self.manager.args.version extractor.project = self.manager.args.project extr... |
def _init_update_po_files(self, domains): """Update or initialize the `.po` translation files""" for language in settings.TRANSLATIONS: for domain, options in domains.items(): if language == options['default']: continue # Default language of the domain doesn't need translations if os.path.isfile(_po_path(language, doma... |
domain, options['pot']) |
def _cleanup(self, domains): """Remove the temporary '.pot' files that were created for the domains.""" for option in domains.values(): try: os.remove(option['pot']) except (IOError, OSError): # It is not a problem if we can't actually remove the temporary file pass |
def run(self): """ read workflows, checks if it's updated, tries to update if there aren't any running instances of that wf """ from zengine.lib.cache import WFSpecNames if self.manager.args.clear: self._clear_models() return if self.manager.args.wf_path: paths = self.get_wf_from_path(self.manager.args.wf_path) else: p... |
def get_wf_from_path(self, path): """ load xml from given path Args: path: diagram path Returns: """ with open(path) as fp: content = fp.read() return [(os.path.basename(os.path.splitext(path)[0]), content), ] |
def get_workflows(self): """ Scans and loads all wf found under WORKFLOW_PACKAGES_PATHS Yields: XML content of diagram file """ for pth in settings.WORKFLOW_PACKAGES_PATHS: for f in glob.glob("%s/*.bpmn" % pth): with open(f) as fp: yield os.path.basename(os.path.splitext(f)[0]), fp.read() |
def check_migration_and_solr(self): """ The model or models are checked for migrations that need to be done. Solr is also checked. """ from pyoko.db.schema_update import SchemaUpdater from socket import error as socket_error from pyoko.conf import settings from importlib import import_module import_module(settings.MODE... |
as e: print(__(u"{0}Error not connected, open redis and rabbitmq{1}").format(CheckList.FAIL, CheckList.ENDC)) |
def check_redis(): """ Redis checks the connection It displays on the screen whether or not you have a connection. """ from pyoko.db.connection import cache from redis.exceptions import ConnectionError try: cache.ping() print(CheckList.OKGREEN + "{0}Redis is working{1}" + CheckList.ENDC) except ConnectionError as e: pr... |
def check_riak(): """ Riak checks the connection It displays on the screen whether or not you have a connection. """ from pyoko.db.connection import client from socket import error as socket_error try: if client.ping(): print(__(u"{0}Riak is working{1}").format(CheckList.OKGREEN, CheckList.ENDC)) else: print(__(u"{0}Ri... |
def check_mq_connection(self): """ RabbitMQ checks the connection It displays on the screen whether or not you have a connection. """ import pika from zengine.client_queue import BLOCKING_MQ_PARAMS from pika.exceptions import ProbableAuthenticationError, ConnectionClosed try: connection = pika.BlockingConnection(BLOCKI... |
ProbableAuthenticationError as e: print(__(u"{0}RabbitMQ username and password wrong{1}").format(CheckList.FAIL, CheckList.ENDC)) |
def check_encoding_and_env(): """ It brings the environment variables to the screen. The user checks to see if they are using the correct variables. """ import sys import os if sys.getfilesystemencoding() in ['utf-8', 'UTF-8']: print(__(u"{0}File system encoding correct{1}").format(CheckList.OKGREEN, CheckList.ENDC)) e... |
env.items(): if k in check_env_list: print(__(u"{0}{1} : {2}{3}").format(CheckList.BOLD, k, v, CheckList.ENDC)) |
def no_moves(position): """ Finds if the game is over. :type: position: Board :rtype: bool """ return position.no_moves(color.white) \ or position.no_moves(color.black) |
def is_checkmate(position, input_color): """ Finds if particular King is checkmated. :type: position: Board :type: input_color: Color :rtype: bool """ return position.no_moves(input_color) and \ position.get_king(input_color).in_check(position) |
def _paginate(self, current_page, query_set, per_page=10): """ Handles pagination of object listings. Args: current_page int: Current page number query_set (:class:`QuerySet<pyoko:pyoko.db.queryset.QuerySet>`): Object listing queryset. per_page int: Objects per page. Returns: QuerySet object, pagination data dict as a ... |
total_pages else 0) pagination_data = dict(page=current_page, total_pages=total_pages, total_objects=total_objects, per_page=current_per_page) query_set = query_set.set_params(rows=current_per_page, start=(current_page - 1) * per_page) return query_set, pagination_data |
def create_message(current): """ Creates a message for the given channel. .. code-block:: python # request: { 'view':'_zops_create_message', 'message': { 'channel': key, # of channel 'body': string, # message text., 'type': int, # zengine.messaging.model.MSG_TYPES, 'attachments': [{ 'description': string, # can be blan... |
key, # key of the message object, } """ msg = current.input['message'] msg_obj = Channel.add_message(msg['channel'], body=msg['body'], typ=msg['type'], sender=current.user, title=msg['title'], receiver=msg['receiver'] or None) current.output = { 'msg_key': msg_obj.key, 'status': 'Created', 'code': 201 } if 'attachment'... |
def show_channel(current, waited=False): """ Initial display of channel content. Returns channel description, members, no of members, last 20 messages etc. .. code-block:: python # request: { 'view':'_zops_show_channel', 'key': key, } # response: { 'channel_key': key, 'description': string, 'no_of_members': int, 'membe... |
current.output = {'key': current.input['key'], 'description': ch.description, 'name': sbs.name, 'actions': sbs.get_actions(), 'avatar_url': ch.get_avatar(current.user), 'no_of_members': len(ch.subscriber_set), 'member_list': [{'name': sb.user.full_name, 'is_online': sb.user.is_online(), 'avatar_url': sb.user.get_avatar... |
def channel_history(current): """ Get old messages for a channel. 20 messages per request .. code-block:: python # request: { 'view':'_zops_channel_history, 'channel_key': key, 'timestamp': datetime, # timestamp data of oldest shown message } # response: { 'messages': [MSG_DICT, ], 'status': 'OK', 'code': 200 } """ cur... |
like pyoko's __lt is broken # TODO: convert lte to lt and remove this block, when __lt filter fixed if current.output['messages']: current.output['messages'].pop(-1) |
def report_last_seen_message(current): """ Push timestamp of latest message of an ACTIVE channel. This view should be called with timestamp of latest message; - When user opens (clicks on) a channel. - Periodically (eg: setInterval for 15secs) while user staying in a channel. .. code-block:: python # request: { 'view':... |
""" sbs = Subscriber(current).objects.filter(channel_id=current.input['channel_key'], user_id=current.user_id)[0] sbs.last_seen_msg_time = current.input['timestamp'] sbs.save() current.output = { 'status': 'OK', 'code': 200} |
def list_channels(current): """ List channel memberships of current user .. code-block:: python # request: { 'view':'_zops_list_channels', } # response: { 'channels': [ {'name': string, # name of channel 'key': key, # key of channel 'unread': int, # unread message count 'type': int, # channel type, # 15: public channel... |
and only private channel which is "Notifications" 'read_only': boolean, # true if this is a read-only subscription to a broadcast channel # false if it's a public chat room 'actions':[('action name', 'view name'),] },] } """ current.output = { 'status': 'OK', 'code': 200, 'channels': []} for sbs in current.user.subscri... |
def unread_count(current): """ Number of unread messages for current user .. code-block:: python # request: { 'view':'_zops_unread_count', } # response: { 'status': 'OK', 'code': 200, 'notifications': int, 'messages': int, } """ unread_ntf = 0 unread_msg = 0 for sbs in current.user.subscriptions.objects.filter(is_visib... |
sbs.delete() current.output = { 'status': 'OK', 'code': 200, 'notifications': unread_ntf, 'messages': unread_msg } |
def get_notifications(current): """ Returns last N notifications for current user .. code-block:: python # request: { 'view':'_zops_unread_messages', 'amount': int, # Optional, defaults to 8 } # response: { 'status': 'OK', 'code': 200, 'notifications': [{'title':string, 'body': string, 'channel_key': key, 'type': int, ... |
datetime},], } """ current.output = { 'status': 'OK', 'code': 200, 'notifications': [], } amount = current.input.get('amount', 8) try: notif_sbs = current.user.subscriptions.objects.get(channel_id=current.user.prv_exchange) except MultipleObjectsReturned: # FIXME: This should not happen, log.exception("MULTIPLE PRV EXC... |
def create_channel(current): """ Create a public channel. Can be a broadcast channel or normal chat room. Chat room and broadcast distinction will be made at user subscription phase. .. code-block:: python # request: { 'view':'_zops_create_channel', 'name': string, 'description': string, } # response: { 'description': ... |
'key': key, # of just created channel } """ channel = Channel(name=current.input['name'], description=current.input['description'], owner=current.user, typ=15).save() with BlockSave(Subscriber): Subscriber.objects.get_or_create(user=channel.owner, channel=channel, can_manage=True, can_leave=False) current.input['key'] ... |
def add_members(current): """ Subscribe member(s) to a channel .. code-block:: python # request: { 'view':'_zops_add_members', 'channel_key': key, 'read_only': boolean, # true if this is a Broadcast channel, # false if it's a normal chat room 'members': [key, key], } # response: { 'existing': [key,], # existing members... |
read_only = current.input['read_only'] for member_key in current.input['members']: sb, new = Subscriber(current).objects.get_or_create(user_id=member_key, read_only=read_only, channel_id=current.input['channel_key']) if new: newly_added.append(member_key) else: existing.append(member_key) current.output = { 'existing':... |
def add_unit_to_channel(current): """ Subscribe users of a given unit to given channel JSON API: .. code-block:: python # request: { 'view':'_zops_add_unit_to_channel', 'unit_key': key, 'channel_key': key, 'read_only': boolean, # true if this is a Broadcast channel, # false if it's a normal chat room } # response: { 'e... |
read_only = current.input['read_only'] newly_added, existing = [], [] for member_key in UnitModel.get_user_keys(current, current.input['unit_key']): sb, new = Subscriber(current).objects.get_or_create(user_id=member_key, read_only=read_only, channel_id=current.input['channel_key']) if new: newly_added.append(member_key... |
def search_user(current): """ Search users for adding to a public room or creating one to one direct messaging .. code-block:: python # request: { 'view':'_zops_search_user', 'query': string, } # response: { 'results': [('full_name', 'key', 'avatar_url'), ], 'status': 'OK', 'code': 200 } """ current.output = { 'results... |
search_on() for user in qs: if user.key != current.user_id: current.output['results'].append((user.full_name, user.key, user.get_avatar_url())) |
def search_unit(current): """ Search on units for subscribing it's users to a channel .. code-block:: python # request: { 'view':'_zops_search_unit', 'query': string, } # response: { 'results': [('name', 'key'), ], 'status': 'OK', 'code': 200 } """ current.output = { 'results': [], 'status': 'OK', 'code': 201 } for use... |
def create_direct_channel(current): """ Create a One-To-One channel between current and selected user. .. code-block:: python # request: { 'view':'_zops_create_direct_channel', 'user_key': key, } # response: { 'description': string, 'no_of_members': int, 'member_list': [ {'name': string, 'is_online': bool, 'avatar_url'... |
current.input['user_key']) current.input['key'] = channel.key show_channel(current) current.output.update({ 'status': 'Created', 'code': 201 }) |
def find_message(current): """ Search in messages. If "channel_key" given, search will be limited to that channel, otherwise search will be performed on all of user's subscribed channels. .. code-block:: python # request: { 'view':'_zops_search_unit, 'channel_key': key, 'query': string, 'page': int, } # response: { 're... |
}, 'status': 'OK', 'code': 200 } """ current.output = { 'results': [], 'status': 'OK', 'code': 201 } query_set = Message(current).objects.search_on(['msg_title', 'body', 'url'], contains=current.input['query']) if current.input['channel_key']: query_set = query_set.filter(channel_id=current.input['channel_key']) else: ... |
def delete_channel(current): """ Delete a channel .. code-block:: python # request: { 'view':'_zops_delete_channel, 'channel_key': key, } # response: { 'status': 'OK', 'code': 200 } """ ch_key = current.input['channel_key'] ch = Channel(current).objects.get(owner_id=current.user_id, key=ch_key) ch.delete() Subscriber.o... |
def edit_channel(current): """ Update channel name or description .. code-block:: python # request: { 'view':'_zops_edit_channel, 'channel_key': key, 'name': string, 'description': string, } # response: { 'status': 'OK', 'code': 200 } """ ch = Channel(current).objects.get(owner_id=current.user_id, key=current.input['ch... |
def pin_channel(current): """ Pin a channel to top of channel list .. code-block:: python # request: { 'view':'_zops_pin_channel, 'channel_key': key, } # response: { 'status': 'OK', 'code': 200 } """ try: Subscriber(current).objects.filter(user_id=current.user_id, channel_id=current.input['channel_key']).update( pinned... |
def delete_message(current): """ Delete a message .. code-block:: python # request: { 'view':'_zops_delete_message, 'message_key': key, } # response: { 'key': key, 'status': 'OK', 'code': 200 } """ try: Message(current).objects.get(sender_id=current.user_id, key=current.input['key']).delete() current.output = {'status'... |
def edit_message(current): """ Edit a message a user own. .. code-block:: python # request: { 'view':'_zops_edit_message', 'message': { 'body': string, # message text 'key': key } } # response: { 'status': string, # 'OK' for success 'code': int, # 200 for success } """ current.output = {'status': 'OK', 'code': 200} in_... |
raise HTTPError(404, "") |
def flag_message(current): """ Flag inappropriate messages .. code-block:: python # request: { 'view':'_zops_flag_message', 'message_key': key, } # response: { ' 'status': 'Created', 'code': 201, } """ current.output = {'status': 'Created', 'code': 201} FlaggedMessage.objects.get_or_create(user_id=current.user_id, mess... |
def unflag_message(current): """ remove flag of a message .. code-block:: python # request: { 'view':'_zops_flag_message', 'key': key, } # response: { ' 'status': 'OK', 'code': 200, } """ current.output = {'status': 'OK', 'code': 200} FlaggedMessage(current).objects.filter(user_id=current.user_id, message_id=current.in... |
def get_message_actions(current): """ Returns applicable actions for current user for given message key .. code-block:: python # request: { 'view':'_zops_get_message_actions', 'key': key, } # response: { 'actions':[('name_string', 'cmd_string'),] 'status': string, # 'OK' for success 'code': int, # 200 for success } """... |
def add_to_favorites(current): """ Favorite a message .. code-block:: python # request: { 'view':'_zops_add_to_favorites, 'key': key, } # response: { 'status': 'Created', 'code': 201 'favorite_key': key } """ msg = Message.objects.get(current.input['key']) current.output = {'status': 'Created', 'code': 201} fav, new = ... |
def remove_from_favorites(current): """ Remove a message from favorites .. code-block:: python # request: { 'view':'_zops_remove_from_favorites, 'key': key, } # response: { 'status': 'OK', 'code': 200 } """ try: current.output = {'status': 'OK', 'code': 200} Favorite(current).objects.get(user_id=current.user_id, key=cu... |
def list_favorites(current): """ List user's favorites. If "channel_key" given, will return favorites belong to that channel. .. code-block:: python # request: { 'view':'_zops_list_favorites, 'channel_key': key, } # response: { 'status': 'OK', 'code': 200 'favorites':[{'key': key, 'channel_key': key, 'message_key': key... |
= query_set.filter(channel_id=current.input['channel_key']) current.output['favorites'] = [{ 'key': fav.key, 'channel_key': fav.channel.key, 'message_key': fav.message.key, 'message_summary': fav.summary, 'channel_name': fav.channel_name } for fav in query_set] |
def get_or_create_direct_channel(cls, initiator_key, receiver_key): """ Creates a direct messaging channel between two user Args: initiator: User, who want's to make first contact receiver: User, other party Returns: (Channel, receiver_name) """ existing = cls.objects.OR().filter( code_name='%s_%s' % (initiator_key, re... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.