desc
stringlengths
3
26.7k
decl
stringlengths
11
7.89k
bodies
stringlengths
8
553k
'Map a search query to it\'s short-hand URL, using Tag prefixes if there is exactly one tag in the search terms or we have tag context. >>> urlmap.url_search([\'foo\', \'bar\', \'baz\']) \'/search/?q=foo%20bar%20baz\' >>> urlmap.url_search([\'foo\', \'tag:Inbox\', \'wtf\'], output=\'json\') \'/in/inbox/as.json?q=foo%20...
def url_search(self, search_terms, tag=None, output=''):
tags = ((tag and [tag]) or [t for t in search_terms if (t.startswith('tag:') or t.startswith('in:'))]) if (len(tags) == 1): prefix = self.url_tag(tags[0].replace('tag:', '').replace('in:', '')) search_terms = [t for t in search_terms if ((t not in tags) and (t.replace('tag:', '').replace('in:', ...
'Return the full versioned URL for a command'
def canonical_url(self, cls):
return ('/api/%s/%s/' % ((cls.API_VERSION or self.API_VERSIONS[(-1)]), cls.SYNOPSIS[2]))
'Return the full user-facing URL for a command'
def ui_url(self, cls):
return ('/%s/' % cls.SYNOPSIS[2])
'Return the UI context URL for a command'
def context_url(self, cls):
return ('/%s/' % (cls.UI_CONTEXT or cls.SYNOPSIS[2]))
'Describe the current URL map as markdown'
def map_as_markdown(self, prefix=None):
api_version = self.API_VERSIONS[(-1)] text = [] def cmds(method): return sorted([(c.SYNOPSIS[2], c) for c in self._api_commands(method, strict=True)]) text.extend([('# Mailpile URL map (autogenerated by %s)' % __file__), '', '\n'.join([line.strip() for line in UrlMap.__doc__.st...
'Prints the current URL map to stdout in markdown'
def print_map_markdown(self):
print self.map_as_markdown()
'Initializes a new Cron instance. Note that the thread will not be started automatically, so you need to call start() manually. Keyword arguments: name -- The name of the Cron instance session -- Currently unused'
def __init__(self, schedule, name=None, session=None):
threading.Thread.__init__(self) self.ALIVE = False self.daemon = mailpile.util.TESTING self.name = name self.session = session self.last_run = time.time() self.running = 'Idle' self.schedule = schedule self.sleep = 10 self.lock = WorkerLock()
'Add a task to the cron worker queue Keyword arguments: name -- The name of the task to add interval -- The interval (in seconds) of the task task -- A task function'
def add_task(self, name, interval, task):
with self.lock: if (name in self.schedule): last = self.schedule[name][3] status = self.schedule[name][4] elif (interval == (24 * 3600)): hr = (3600 * datetime.datetime.now().hour) last = ((time.time() - hr) + random.randint(3600, (7 * 3600))) ...
'Recalculate the maximum sleep delay. This shall be called from a lock zone only'
def __recalculateSleep(self):
for i in range(2, 61): filteredTasks = [True for task in self.schedule.values() if ((int(task[1]) % i) != 0)] if (len(filteredTasks) == 0): self.sleep = i
'Cancel a task in the current Cron instance. If a task with the given name does not exist, ignore the request. Keyword arguments: name -- The name of the task to cancel'
def cancel_task(self, name):
if (name in self.schedule): with self.lock: del self.schedule[name] self.__recalculateSleep()
'Thread main function for a Cron instance.'
def run(self):
play_nice(19) self.ALIVE = True while (self.ALIVE and (not mailpile.util.QUITTING)): tasksToBeExecuted = [] now = time.time() with self.lock: for task_spec in self.schedule.values(): (name, interval, task, last, status) = task_spec if ((las...
'Send a signal to the current Cron instance to stop operation. Keyword arguments: join -- If this is True, this method will wait until the Cron thread exits.'
def quit(self, session=None, join=True):
self.ALIVE = False if (join and (not self.daemon) and self.isAlive()): self.join()
'Quote values so they can be safely represented in a VCard. >>> print VCardLine.Quote(\'Comma, semicolon; backslash\ newline\n\') Comma\, semicolon\; backslash\\ newline\n'
@classmethod def Quote(self, text):
return unicode(''.join([self.QUOTE_MAP.get(c, c) for c in text]))
'Parse a single line, respecting to the VCard (RFC6350) quoting. >>> VCardLine.ParseLine(\'foo:val;ue\') (u\'foo\', [], u\'val;ue\') >>> VCardLine.ParseLine(\'foo;BAR;\\baz:value\') (u\'foo\', [(u\'bar\', None), (u\'\\baz\', None)], u\'value\') >>> VCardLine.ParseLine(\'FOO;bar=comma\,semicolon\;\' ... ...
@classmethod def ParseLine(self, text):
def parse_quoted(char, state, parsed, name, attrs): pair = ('\\' + char) parsed = (parsed[:(-1)] + self.QUOTE_RMAP.get(pair, pair)) return (parse_char, state, parsed, name, attrs) def parse_char(char, state, parsed, name, attrs): if (char == '\\'): parsed += char ...
'Remove one or more lines from the VCard. >>> vc = SimpleVCard(VCardLine(name=\'fn\', value=\'Houdini\')) >>> vc.remove(vc.get(\'fn\').line_id) 1 >>> vc.get(\'fn\') Traceback (most recent call last): IndexError: ...'
def remove(self, *line_ids):
removed = 0 with self._lock: for index in range(0, len(self._lines)): vcl = self._lines[index] if (vcl and (vcl.line_id in line_ids)): if (self._lines[index].name in self.UNREMOVABLE): raise ValueError(('Cannot remove %s from VCard'...
'Remove one or more lines from the VCard. >>> vc = SimpleVCard(VCardLine(name=\'fn\', value=\'Houdini\')) >>> vc.remove_all(\'fn\') >>> vc.get(\'fn\') Traceback (most recent call last): IndexError: ...'
def remove_all(self, name):
self.remove(*[line.line_id for line in self.get_all(name)])
'Add one or more lines to a VCard. >>> vc = SimpleVCard() >>> vc.add(VCardLine(name=\'fn\', value=\'Bjarni\')) >>> vc.get(\'fn\').value u\'Bjarni\' Line types are checked against VCard 4.0 for validity. >>> vc.add(VCardLine(name=\'evil\', value=\'Bjarni\')) Traceback (most recent call last): ValueError: Not allowed on ...
def add(self, *vcls, **kwargs):
(src_pid, pidmap, version, is_new) = self._handle_pidmap_args(**kwargs) for vcl in vcls: with self._lock: if (not vcl.name): continue cardinality = self._cardinality(vcl) count = len([l for l in self._lines if (l and (l.name == vcl.name))]) ...
'Modify one line of a VCard. >>> vc = SimpleVCard(VCardLine(name=\'fn\', value=\'Bjarni\')) >>> vc.get(\'fn\').value u\'Bjarni\' >>> vc.set_line(vc.get(\'fn\').line_id, ... VCardLine(name=\'fn\', value=\'Dude\')) >>> vc.get(\'fn\').value u\'Dude\''
def set_line(self, ln, vcl, **kwargs):
if (not ((ln > 0) and (ln <= len(self._lines)))): raise ValueError((_('Line number %s is out of range') % ln)) (src_pid, pidmap, version, is_new) = self._handle_pidmap_args(**kwargs) if ((src_pid is not None) and (vcl.name not in self.UNREMOVABLE) and ('pid' not in vcl)): v...
'Return a dictionary representing the CLIENTPIDMAP, grouping VCard lines by data sources. >>> vc = SimpleVCard(VCardLine(name=\'fn\', value=\'Bjarni\', pid=\'1.2\'), ... VCardLine(name=\'clientpidmap\', ... value=\'1;thisisauid\')) >>> vc.get_clientpidmap()[\'thisisauid\'][\'...
def get_clientpidmap(self):
cpm = {} for pm in self.get_all('clientpidmap'): (pid, guid) = pm.value.split(';') pid = int(pid) cpm[guid] = cpm[pid] = {'pid': pid, 'lines': []} for vcl in self.as_lines(): if ('pid' in vcl): pv = [v.strip().split('.', 1) for v in vcl['pid'].split(',')] ...
'Fetch the pidmap, src_pid and version for a given src_id, optionally creating new CLIENTPIDMAP entries on demand.'
def get_pidmap(self, src_id, create=False):
with self._lock: cpm = self.get_clientpidmap() pidmap = cpm.get(src_id, False) if pidmap: src_pid = pidmap['pid'] is_new = False elif create: pids = [p['pid'] for p in cpm.values()] src_pid = None for pid in range(1, self.MA...
'Merge a set of VCard lines from a given source into this card. >>> vc = SimpleVCard(VCardLine(name=\'fn\', value=\'Bjarni\', pid=\'1.2\'), ... VCardLine(name=\'email\', value=\'bre@foo\', t=\'1\'), ... VCardLine(name=\'email\', value=\'bre@bar\', t=\'2\'), ... VCardLi...
def merge(self, src_id, lines):
if (not lines): return lines = [l for l in lines if (not (l.name in self.UNREMOVABLE))] changes = 0 with self._lock: (src_pid, pidmap, version, is_new) = self.get_pidmap(src_id, create=True) if is_new: changes += 1 lines.sort(key=(lambda k: (k.name, k.value)))...
'This method returns the VCard data in its native format. Note: the output is a string of bytes, not unicode characters. >>> print SimpleVCard().as_vCard() BEGIN:VCARD VERSION:4.0 FN:Anonymous END:VCARD'
def as_vCard(self):
for key in self.VCARD4_REQUIRED: with self._lock: if (not self.get_all(key)): default = self.VCARD4_KEYS[key][2] self._lines[:0] = [VCardLine(name=key, value=default)] with self._lock: self._sort_lines() return '\n'.join(((['BEGIN:VCARD'] + [l....
'Load VCard lines from a file on disk or data in memory.'
def load(self, filename=None, data=None, config=None):
if data: pass elif filename: from mailpile.crypto.streamer import DecryptingStreamer self.filename = (filename or self.filename) with open(self.filename, 'rb') as fd: with DecryptingStreamer(fd, mep_key=self.decryption_key_func(), name=('VCard/load(%s)' % self.filenam...
'This method will choose a from address from the available profiles, using the given config and lists of addresses as a guideline. An address is chosen by assigning each potential from address a cumulative score, where scores express roughly the following preferences. 1. If one of the profiles\' e-mail addresses is pre...
def choose_from_address(vcards, *args, **kwargs):
fa_list = vcards.choose_from_addresses(*args, **kwargs) return ((fa_list and fa_list[0]) or None)
'Brokers should register themselves with priorities as follows: - 1000-1999: Content-agnostic raw connections - 3000-3999: Secure network layers: VPNs, Tor, I2P, ... - 5000-5999: Proxies required to reach the wider Internet - 7000-7999: Protocol enhancments (non-security related) - 9000-9999: Security-related protocol ...
def register_broker(self, priority, cb):
self.brokers.append((priority, cb(master=self))) self.brokers.sort() self.brokers.reverse()
'Open mailboxes or connect to the remote mail source.'
def open(self):
raise NotImplemented(('Please override open in %s' % self))
'Close mailboxes or disconnect from the remote mail source.'
def close(self):
raise NotImplemented(('Please override open in %s' % self))
'For the default sync_mail routine, report if mailbox changed.'
def _has_mailbox_changed(self, mbx, state):
raise NotImplemented(('Please override _has_mailbox_changed in %s' % self))
'For the default sync_mail routine, note mailbox was rescanned.'
def _mark_mailbox_rescanned(self, mbx, state):
raise NotImplemented(('Please override _mark_mailbox_rescanned in %s' % self))
'Iterates through all the mailboxes and scans if necessary.'
def sync_mail(self):
config = self.session.config self._last_rescan_count = rescanned = errors = 0 self._last_rescan_completed = False self._last_rescan_failed = False self._interrupt = None batch = min((self._loop_count * 20), self.RESCAN_BATCH_SIZE) errors = rescanned = 0 all_completed = True ostate = ...
'This converts a path to a tag name.'
def _path_to_tagname(self, path):
parts = self._mailbox_path_split(path) parts = [p for p in parts if (not re.match(self.BORING_FOLDER_RE, p))] if (not parts): return _('Unnamed') tagname = self._strip_file_extension(parts.pop((-1))) while (tagname[:1] == '.'): tagname = tagname[1:] return re.sub(self.TAGNAME_STR...
'Make sure a tagname really is unused, unless we have a parent'
def _unique_tag_name(self, tagname):
if self.my_config.discovery.parent_tag: return tagname (tagnameN, count) = (tagname, 2) while self.session.config.get_tags(tagnameN): tagnameN = ('%s (%s)' % (tagname, count)) count += 1 return tagnameN
'Convert a path to a unique tag name.'
def _create_tag_name(self, path):
return self._unique_tag_name(self._path_to_tagname(path))
'Walks the IMAP path recursively and returns a list of all found mailboxes.'
def _walk_mailbox_path(self, conn, prefix):
mboxes = [] subtrees = [] max_mailboxes = (5 + self.my_config.discovery.max_mailboxes) try: (ok, data) = self.timed_imap(conn.list, prefix, '%') while (ok and (len(data) >= 3)): ((flags, sep, path), data[:3]) = (data[:3], []) flags = [f.lower() for f in flags] ...
'Read line from remote.'
def readline(self):
line = self.file.readline((imaplib._MAXLINE + 1)) if (len(line) > imaplib._MAXLINE): raise self.abort(('got more than %d bytes' % imaplib._MAXLINE)) return line
'A non-optimal implementation of a regex filter'
def _regex_replace(self, s, find, replace):
return re.sub(find, replace, s)
'Hex encodes some characters for use in JavaScript strings. Lightly inspired from https://github.com/django/django/blame/ebc773ada3e4f40cf5084268387b873d7fe22e8b/django/utils/html.py#L63'
def _escapejs(self, value):
for (bad, good) in self._JS_ESCAPES: value = value.replace(bad, good) return self._safe(value)
'Replaces by <br /> Inspired from http://jinja.pocoo.org/docs/dev/api/#custom-filters'
@classmethod def _to_br(self, text):
result = '<br />'.join((p for p in self._TEXT_LINEBREAK_RE.split(escape(text)))) return Markup(result)
'Render file path as a cooked unicode string'
def __unicode__(self, errors='strict'):
raw_fp = self.alias(self.raw_fp) try: return raw_fp.decode('utf-8', errors) except (UnicodeDecodeError, UnicodeEncodeError): return (raw_fp.encode('base64').strip() + '=!')
'Render file path as a cooked string'
def __str__(self):
return unicode(self).encode('utf-8')
'Lossy, user-friendly representation of this path.'
def display(self):
return self.__unicode__('replace')
'Lossy, user-friendly representation of path\'s base name.'
def display_basename(self):
return posixpath.basename(self.__unicode__('replace'))
'This exposes at the root local mailboxes which would not be listed otherwise, because their path falls outside of the user\'s home directory.'
def _discover_local_mailboxes(self):
user_home = os.path.expanduser('~') for (mbx_id, path, ms) in self.config.get_mailboxes(): path = FilePath(path) if ((path.raw_fp[:4] != 'src:') and (not vfs.abspath(path).startswith(user_home))): path = FilePath(os.path.normpath(path.raw_fp)) if (not [e for e in self.ent...
'Returns just a single contact, based on data from the config.'
def get_vcards(self):
if (not self.config.active): return [] return [MailpileVCard(VCardLine(name='fn', value=self.config.name), VCardLine(name='email', value=self.config.email))]
'Return object data in easily serializable format'
@property def serialize(self):
return {'id': self.id, 'holder': self.holder, 'holder_url': self.holder_url, 'licence': self.licence, 'licence_url': self.licence_url, 'year': self.year, 'logo': self.logo}
'Return object data in easily serializeable format'
@property def serialize(self):
return {'id': self.id, 'name': self.name, 'description': self.description, 'title': self.title, 'url': self.url, 'place': self.place, 'language': self.language}
'Returns True if ticket has already placed orders. Else False.'
def has_order_tickets(self):
from app.api.helpers.db import get_count orders = Order.id.in_(OrderTicket.query.with_entities(OrderTicket.order_id).filter_by(ticket_id=self.id).all()) count = get_count(Order.query.filter(orders).filter((Order.status != 'deleted'))) return bool((count > 0))
'Returns True if ticket has already placed orders. Else False.'
def has_completed_order_tickets(self):
order_tickets = OrderTicket.query.filter_by(ticket_id=self.id) count = 0 for order_ticket in order_tickets: order = Order.query.filter_by(id=order_ticket.order_id).first() if ((order.status == 'completed') or (order.status == 'placed')): count += 1 return bool((count > 0))
'Return list of Tags in CSV.'
def tags_csv(self):
tag_names = [tag.name for tag in self.tags] return ','.join(tag_names)
'Return object data in easily serializeable format'
@property def serialize(self):
data = {'id': self.id, 'name': self.name, 'quantity': self.quantity, 'position': self.position, 'type': self.type, 'description_visibility': self.is_description_visible, 'description': self.description, 'price': self.price, 'sales_start_date': (self.sales_starts_at.strftime('%m/%d/%Y') if self.sales_starts_at else ...
'Return object data in easily serializeable format'
@property def serialize(self):
return {'id': self.id, 'announcement': self.announcement, 'starts_at': (self.starts_at.strftime('%Y-%m-%dT%H:%M:%S%Z') if self.starts_at else ''), 'ends_at': (self.ends_at.strftime('%Y-%m-%dT%H:%M:%S%Z') if self.ends_at else ''), 'privacy': self.privacy, 'hash': self.hash}
'Return object data in easily serializable format'
@property def serialize(self):
return {'id': self.id, 'identifier': self.identifier, 'quantity': self.quantity, 'amount': self.amount, 'address': self.address, 'state': self.state, 'zipcode': self.zipcode, 'country': self.country, 'transaction_id': self.transaction_id, 'paid_via': self.paid_via, 'payment_mode': self.payment_mode, 'brand': self.b...
'Return object data in easily serializeable format'
@property def serialize(self):
return {'id': self.id, 'name': self.name, 'floor': self.floor}
'Return object data in easily serializable format'
@property def serialize(self):
return {'id': self.id, 'firstname': self.firstname, 'lastname': self.lastname, 'email': self.email, 'city': self.city, 'address': self.address, 'state': self.state, 'country': self.country}
'Return object data in easily serializeable format'
@property def serialize(self):
return {'id': self.id, 'name': self.name, 'slug': self.slug, 'event_topic_id': self.event_topic_id}
'Return object data in easily serializeable format'
@property def serialize(self):
return {'id': self.id, 'name': self.name, 'length': self.length}
'Return object data in easily serializable format'
@property def serialize(self):
return {'id': self.id, 'type': self.type, 'full_width': self.full_width, 'full_height': self.full_height, 'full_aspect': self.full_aspect, 'full_quality': self.full_quality, 'icon_width': self.icon_width, 'icon_height': self.icon_height, 'icon_aspect': self.icon_aspect, 'icon_quality': self.icon_quality, 'thumbnail...
'Return object data in easily serializeable format'
@property def serialize(self):
return {'id': self.id, 'name': self.name, 'link': self.link}
'Hybrid property for password :return:'
@hybrid_property def password(self):
return self._password
'Setter for _password, saves hashed password, salt and reset_password string :param password: :return:'
@password.setter def password(self, password):
salt = generate_random_salt() self._password = generate_password_hash(password, salt) hash_ = random.getrandbits(128) self.reset_password = str(hash_) self.salt = salt
'Hybrid property for email :return:'
@hybrid_property def email(self):
return self._email
'Setter for _email, set user to \'not verified\' if email is updated :param email: :return:'
@email.setter def email(self, email):
if (self._email != email): self._email = email self.is_verified = False
'Checks if User can publish an event'
def can_publish_event(self):
perm = UserPermission.query.filter_by(name='publish_event').first() if (not perm): return self.is_verified return perm.unverified_user
'Checks if User can create an event'
def can_create_event(self):
perm = UserPermission.query.filter_by(name='create_event').first() if (not perm): return self.is_verified if (self.is_verified is False): return perm.unverified_user return True
'Checks if user has any of the Roles at an Event. Exclude Attendee Role.'
def has_role(self, event_id):
attendee_role = Role.query.filter_by(name=ATTENDEE).first() uer = UER.query.filter((UER.user == self), (UER.event_id == event_id), (UER.role != attendee_role)).first() if (uer is None): return False else: return True
'Checks if a user has a particular Role at an Event.'
def _is_role(self, role_name, event_id):
role = Role.query.filter_by(name=role_name).first() uer = UER.query.filter_by(user=self, event_id=event_id, role=role).first() if (not uer): return False else: return True
'Check if a user has a Custom System Role assigned. `role_id` is id of a `CustomSysRole` instance.'
def is_sys_role(self, role_id):
role = UserSystemRole.query.filter_by(user=self, role_id=role_id).first() return bool(role)
'Check if the user is assigned a Custom Role or not This checks if there is an entry containing the current user in the `user_system_roles` table returns panel name if exists otherwise false'
def first_access_panel(self):
custom_role = UserSystemRole.query.filter_by(user=self).first() if (not custom_role): return False perm = PanelPermission.query.filter_by(role_id=custom_role.role_id, can_access=True).first() if (not perm): return False return perm.panel_name
'Check if user can access an Admin Panel'
def can_access_panel(self, panel_name):
if self.is_staff: return True custom_sys_roles = UserSystemRole.query.filter_by(user=self) for custom_role in custom_sys_roles: if custom_role.role.can_access(panel_name): return True return False
'Get unread notifications with titles, humanized receiving time and Mark-as-read links.'
def get_unread_notifs(self):
notifs = [] unread_notifs = Notification.query.filter_by(user=self, is_read=False).order_by(desc(Notification.received_at)) for notif in unread_notifs: notifs.append({'title': notif.title, 'received_at': humanize.naturaltime((datetime.now(pytz.utc) - notif.received_at)), 'mark_read': url_for('notifi...
'Return object data in easily serializeable format'
@property def serialize(self):
return {'version': [{'id': self.id, 'event_id': self.event_id, 'event_ver': self.event_ver, 'sessions_ver': self.sessions_ver, 'speakers_ver': self.speakers_ver, 'tracks_ver': self.tracks_ver, 'sponsors_ver': self.sponsors_ver, 'microlocations_ver': self.microlocations_ver}]}
'Return object data in easily serializeable format'
@property def serialize(self):
session_data = [{'title': session.title, 'id': session.id} for session in self.sessions] return {'id': self.id, 'name': self.name, 'photo': self.photo, 'thumbnail': self.thumbnail, 'small': self.small, 'icon': self.icon, 'short_biography': self.short_biography, 'long_biography': self.long_biography, 'speaking_e...
'Return object data in easily serializable format'
@property def serialize(self):
return {'id': self.id, 'code': self.code, 'discount_url': self.discount_url, 'value': self.value, 'type': self.type, 'tickets_number': self.tickets_number, 'min_quantity': self.min_quantity, 'max_quantity': self.max_quantity, 'used_for': self.used_for, 'valid_from': self.valid_from, 'valid_till': self.valid_till, '...
'Return object data in easily serializable format'
@property def serialize(self):
return {'id': self.id, 'code': self.code, 'access_url': self.access_url, 'tickets_number': self.tickets_number, 'min_quantity': self.min_quantity, 'max_quantity': self.max_quantity, 'used_for': self.used_for, 'valid_from': self.valid_from, 'valid_till': self.valid_till, 'event_id': self.event_id, 'is_active': self....
'Return object data in easily serializable format'
@property def serialize(self):
return {'id': self.id, 'stripe_secret_key': self.stripe_secret_key, 'stripe_refresh_token': self.stripe_refresh_token, 'stripe_publishable_key': self.stripe_publishable_key, 'stripe_user_id': self.stripe_user_id, 'stripe_email': self.stripe_email}
'returns organizer of an event'
def get_organizer(self):
for role in self.roles: if (role.role.name == ORGANIZER): return role.user return None
'does user have role other than attendee'
def has_staff_access(self, user_id):
for _ in self.roles: if (_.user_id == (login.current_user.id if (not user_id) else int(user_id))): if (_.role.name != ATTENDEE): return True return False
'returns only roles which are staff i.e. not attendee'
def get_staff_roles(self):
return [role for role in self.roles if (role.role.name != ATTENDEE)]
'Return object data in easily serializeable format'
@property def serialize(self):
return {'id': self.id, 'user_id': self.user_id, 'session_id': self.session_id}
'Return object data in easily serializeable format'
@property def serialize(self):
return {'id': self.id, 'action': self.action, 'mail_status': self.mail_status, 'notification_status': self.notification_status, 'user_control_status': self.user_control_status}
'Return object data in easily serializable format'
@property def serialize(self):
return {'id': self.id, 'name': self.name, 'url': self.url, 'thumbnail': self.thumbnail, 'copyright': self.copyright, 'origin': self.origin}
'Return object data in easily serializable format'
@property def serialize(self):
return {'id': self.id, 'country': self.country, 'name': self.name, 'rate': self.rate, 'tax_id': self.tax_id, 'should_send_invoice': self.should_send_invoice, 'registered_company': self.registered_company, 'address': self.address, 'city': self.city, 'state': self.state, 'zip': self.zip, 'invoice_footer': self.invoic...
'Return object data in easily serializeable format'
@property def serialize(self):
return {'id': self.id, 'field_identifier': self.field_identifier, 'form': self.form, 'type': self.type, 'is_required': self.is_required, 'is_included': self.is_included, 'is_fixed': self.is_fixed}
'Return object data in easily serializeable format'
@property def serialize(self):
return {'id': self.id, 'name': self.name, 'slug': self.slug}
'Return object data in easily serializeable format'
@property def serialize(self):
return {'id': self.id, 'name': self.name, 'url': self.url, 'logo_url': self.logo_url, 'level': self.level, 'type': self.type, 'description': self.description}
'Return object data in easily serializeable format'
@property def serialize(self):
return {'id': self.id, 'name': self.name, 'slug': self.slug}
'query method for role invites list :param view_kwargs: :return:'
def query(self, view_kwargs):
query_ = self.session.query(RoleInvite) query_ = event_query(self, query_, view_kwargs) return query_
'Method to edit object :param role_invite: :param data: :param view_kwargs: :return:'
def before_update_object(self, role_invite, data, view_kwargs):
user = User.query.filter_by(email=role_invite.email).first() if user: if (not has_access('is_user_itself', id=user.id)): raise UnprocessableEntity({'source': ''}, 'Only users can edit their own status') if ((not user) and (not has_access('is_organizer', event_id=role_in...
'before post method for checking required relationship :param args: :param kwargs: :param data: :return:'
def before_post(self, args, kwargs, data):
require_relationship(['event'], data) if (not has_access('is_coorganizer', event_id=data['event'])): raise ForbiddenException({'source': ''}, 'Co-organizer access is required.')
'method to query Ticket tags based on different params :param view_kwargs: :return:'
def query(self, view_kwargs):
query_ = self.session.query(TicketTag) if view_kwargs.get('ticket_id'): ticket = safe_query(self, Ticket, 'id', view_kwargs['ticket_id'], 'ticket_id') query_ = query_.join(ticket_tags_table).filter_by(ticket_id=ticket.id) query_ = event_query(self, query_, view_kwargs) return query_
'Initialize a jsonapi ErrorResponse Object :param dict source: the source of the error :param str detail: the detail of the error'
def __init__(self, source, detail, title=None, status=None):
self.source = source self.detail = detail if (title is not None): self.title = title if (status is not None): self.status = status
':return: a jsonapi compliant response object'
def respond(self):
dict_ = self.to_dict() return make_response(json.dumps(jsonapi_errors([dict_])), self.status, self.headers)
':return: Dict from details of the object'
def to_dict(self):
return {'status': self.status, 'source': self.source, 'title': self.title, 'detail': self.detail}
'Execute task code with given arguments.'
def __call__(self, *args, **kwargs):
call = (lambda : super(RequestContextTask, self).__call__(*args, **kwargs)) context = kwargs.pop(self.CONTEXT_ARG_NAME, None) gl = kwargs.pop(self.GLOBALS_ARG_NAME, {}) if ((context is None) or has_request_context()): return call() with app.test_request_context(**context): for i in g...
'Includes all the information about current Flask request context as an additional argument to the task.'
def _include_request_context(self, kwargs):
if (not has_request_context()): return context = {'path': request.path, 'base_url': request.url_root, 'method': request.method, 'headers': dict(request.headers)} if ('?' in request.url): context['query_string'] = request.url[(request.url.find('?') + 1):] kwargs[self.CONTEXT_ARG_NAME] = c...
'Send email if session accepted or rejected'
def after_update_object(self, session, data, view_kwargs):
if (('state' in data) and ((session.state == 'accepted') or (session.state == 'rejected'))): speakers = session.speakers for speaker in speakers: frontend_url = get_settings()['frontend_url'] link = '{}/events/{}/sessions/{}'.format(frontend_url, session.event_id, session.id)...
'query method for Notifications list :param view_kwargs: :return:'
def query(self, view_kwargs):
query_ = self.session.query(EmailNotification) if view_kwargs.get('id'): user = safe_query(self, User, 'id', view_kwargs['id'], 'id') query_ = query_.join(User).filter((User.id == user.id)) return query_
'query method for Sponsor List :param view_kwargs: :return:'
def query(self, view_kwargs):
query_ = self.session.query(Sponsor) query_ = event_query(self, query_, view_kwargs) return query_
'query method for Session Type List :param view_kwargs: :return:'
def query(self, view_kwargs):
query_ = self.session.query(SessionType) query_ = event_query(self, query_, view_kwargs) return query_
'before get method for session type detail :param data: :param view_kwargs: :return:'
def before_get_object(self, view_kwargs):
if view_kwargs.get('session_id'): session = safe_query(self, Session, 'id', view_kwargs['session_id'], 'session_id') if session.session_type_id: view_kwargs['id'] = session.session_type_id else: view_kwargs['id'] = None