本文整理汇总了Python中mailpile.urlmap.UrlMap类的典型用法代码示例。如果您正苦于以下问题:Python UrlMap类的具体用法?Python UrlMap怎么用?Python UrlMap使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了UrlMap类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: as_dict
def as_dict(self):
from mailpile.urlmap import UrlMap
um = UrlMap(self.session)
rv = {
'command': self.command_name,
'state': {
'command_url': um.ui_url(self.command_obj),
'context_url': um.context_url(self.command_obj),
'query_args': self.command_obj.state_as_query_args(),
'cache_id': self.command_obj.cache_id(),
'context': self.command_obj.context or ''
},
'status': self.status,
'message': self.message,
'result': self.result,
'event_id': self.command_obj.event.event_id,
'elapsed': '%.3f' % self.session.ui.time_elapsed,
}
csrf_token = self.session.ui.html_variables.get('csrf_token')
if csrf_token:
rv['state']['csrf_token'] = csrf_token
if self.error_info:
rv['error'] = self.error_info
for ui_key in [k for k in self.command_obj.data.keys()
if k.startswith('ui_')]:
rv[ui_key] = self.command_obj.data[ui_key][0]
ev = self.command_obj.event
if ev and ev.data.get('password_needed'):
rv['password_needed'] = ev.private_data['password_needed']
return rv
示例2: command
def command(self, save=True, auto=False):
res = {
'api_methods': [],
'javascript_classes': [],
'css_files': []
}
if self.args:
# Short-circuit if we're serving templates...
return self._success(_('Serving up API content'), result=res)
session, config = self.session, self.session.config
urlmap = UrlMap(session)
for method in ('GET', 'POST', 'UPDATE', 'DELETE'):
for cmd in urlmap._api_commands(method, strict=True):
cmdinfo = {
"url": cmd.SYNOPSIS[2],
"method": method
}
if hasattr(cmd, 'HTTP_QUERY_VARS'):
cmdinfo["query_vars"] = cmd.HTTP_QUERY_VARS
if hasattr(cmd, 'HTTP_POST_VARS'):
cmdinfo["post_vars"] = cmd.HTTP_POST_VARS
if hasattr(cmd, 'HTTP_OPTIONAL_VARS'):
cmdinfo["optional_vars"] = cmd.OPTIONAL_VARS
res['api_methods'].append(cmdinfo)
created_js = []
for cls, filename in sorted(list(
config.plugins.get_js_classes().iteritems())):
try:
parts = cls.split('.')[:-1]
for i in range(1, len(parts)):
parent = '.'.join(parts[:i+1])
if parent not in created_js:
res['javascript_classes'].append({
'classname': parent,
'code': ''
})
created_js.append(parent)
with open(filename, 'rb') as fd:
res['javascript_classes'].append({
'classname': cls,
'code': fd.read().decode('utf-8')
})
created_js.append(cls)
except (OSError, IOError, UnicodeDecodeError):
self._ignore_exception()
for cls, filename in sorted(list(
config.plugins.get_css_files().iteritems())):
try:
with open(filename, 'rb') as fd:
res['css_files'].append({
'classname': cls,
'css': fd.read().decode('utf-8')
})
except (OSError, IOError, UnicodeDecodeError):
self._ignore_exception()
return self._success(_('Generated Javascript API'), result=res)
示例3: command
def command(self, save=True, auto=False):
session, config = self.session, self.session.config
urlmap = UrlMap(session)
res = {"api_methods": [], "javascript_classes": [], "css_files": []}
for method in ("GET", "POST", "UPDATE", "DELETE"):
for cmd in urlmap._api_commands(method, strict=True):
cmdinfo = {"url": cmd.SYNOPSIS[2], "method": method}
if hasattr(cmd, "HTTP_QUERY_VARS"):
cmdinfo["query_vars"] = cmd.HTTP_QUERY_VARS
if hasattr(cmd, "HTTP_POST_VARS"):
cmdinfo["post_vars"] = cmd.HTTP_POST_VARS
if hasattr(cmd, "HTTP_OPTIONAL_VARS"):
cmdinfo["optional_vars"] = cmd.OPTIONAL_VARS
res["api_methods"].append(cmdinfo)
for cls, filename in config.plugins.get_js_classes().iteritems():
try:
with open(filename, "rb") as fd:
res["javascript_classes"].append({"classname": cls, "code": fd.read().decode("utf-8")})
except (OSError, IOError, UnicodeDecodeError):
self._ignore_exception()
for cls, filename in config.plugins.get_css_files().iteritems():
try:
with open(filename, "rb") as fd:
res["css_files"].append({"classname": cls, "css": fd.read().decode("utf-8")})
except (OSError, IOError, UnicodeDecodeError):
self._ignore_exception()
return res
示例4: as_dict
def as_dict(self):
from mailpile.urlmap import UrlMap
um = UrlMap(self.session)
rv = {
"command": self.command_name,
"state": {
"command_url": um.ui_url(self.command_obj),
"context_url": um.context_url(self.command_obj),
"query_args": self.command_obj.state_as_query_args(),
"cache_id": self.command_obj.cache_id(),
"context": self.command_obj.context or "",
},
"status": self.status,
"message": self.message,
"result": self.result,
"event_id": self.command_obj.event.event_id,
"elapsed": "%.3f" % self.session.ui.time_elapsed,
}
csrf_token = self.session.ui.html_variables.get("csrf_token")
if csrf_token:
rv["state"]["csrf_token"] = csrf_token
if self.error_info:
rv["error"] = self.error_info
for ui_key in [k for k in self.command_obj.data.keys() if k.startswith("ui_")]:
rv[ui_key] = self.command_obj.data[ui_key][0]
ev = self.command_obj.event
if ev and ev.data.get("password_needed"):
rv["password_needed"] = ev.private_data["password_needed"]
return rv
示例5: command
def command(self, save=True, auto=False):
session, config = self.session, self.session.config
urlmap = UrlMap(session)
res = {
'api_methods': [],
'javascript_classes': [],
'css_files': []
}
for method in ('GET', 'POST', 'UPDATE', 'DELETE'):
for cmd in urlmap._api_commands(method, strict=True):
cmdinfo = {
"url": cmd.SYNOPSIS[2],
"method": method
}
if hasattr(cmd, 'HTTP_QUERY_VARS'):
cmdinfo["query_vars"] = cmd.HTTP_QUERY_VARS
if hasattr(cmd, 'HTTP_POST_VARS'):
cmdinfo["post_vars"] = cmd.HTTP_POST_VARS
if hasattr(cmd, 'HTTP_OPTIONAL_VARS'):
cmdinfo["optional_vars"] = cmd.OPTIONAL_VARS
res['api_methods'].append(cmdinfo)
for cls, filename in config.plugins.get_js_classes().iteritems():
try:
with open(filename, 'rb') as fd:
res['javascript_classes'].append({
'classname': cls,
'code': fd.read().decode('utf-8')
})
except (OSError, IOError, UnicodeDecodeError):
self._ignore_exception()
for cls, filename in config.plugins.get_css_files().iteritems():
try:
with open(filename, 'rb') as fd:
res['css_files'].append({
'classname': cls,
'css': fd.read().decode('utf-8')
})
except (OSError, IOError, UnicodeDecodeError):
self._ignore_exception()
return res
示例6: command
def command(self, save=True, auto=False):
res = {"api_methods": [], "javascript_classes": [], "css_files": []}
if self.args:
# Short-circuit if we're serving templates...
return self._success(_("Serving up API content"), result=res)
session, config = self.session, self.session.config
urlmap = UrlMap(session)
for method in ("GET", "POST", "UPDATE", "DELETE"):
for cmd in urlmap._api_commands(method, strict=True):
cmdinfo = {"url": cmd.SYNOPSIS[2], "method": method}
if hasattr(cmd, "HTTP_QUERY_VARS"):
cmdinfo["query_vars"] = cmd.HTTP_QUERY_VARS
if hasattr(cmd, "HTTP_POST_VARS"):
cmdinfo["post_vars"] = cmd.HTTP_POST_VARS
if hasattr(cmd, "HTTP_OPTIONAL_VARS"):
cmdinfo["optional_vars"] = cmd.OPTIONAL_VARS
res["api_methods"].append(cmdinfo)
created_js = []
for cls, filename in sorted(list(config.plugins.get_js_classes().iteritems())):
try:
parts = cls.split(".")[:-1]
for i in range(1, len(parts)):
parent = ".".join(parts[: i + 1])
if parent not in created_js:
res["javascript_classes"].append({"classname": parent, "code": ""})
created_js.append(parent)
with open(filename, "rb") as fd:
res["javascript_classes"].append({"classname": cls, "code": fd.read().decode("utf-8")})
created_js.append(cls)
except (OSError, IOError, UnicodeDecodeError):
self._ignore_exception()
for cls, filename in sorted(list(config.plugins.get_css_files().iteritems())):
try:
with open(filename, "rb") as fd:
res["css_files"].append({"classname": cls, "css": fd.read().decode("utf-8")})
except (OSError, IOError, UnicodeDecodeError):
self._ignore_exception()
return self._success(_("Generated Javascript API"), result=res)
示例7: as_dict
def as_dict(self):
from mailpile.urlmap import UrlMap
rv = {
"command": self.command_name,
"state": {
"command_url": UrlMap.ui_url(self.command_obj),
"context_url": UrlMap.context_url(self.command_obj),
"query_args": self.command_obj.state_as_query_args(),
},
"status": self.status,
"message": self.message,
"result": self.result,
"elapsed": "%.3f" % self.session.ui.time_elapsed,
}
if self.error_info:
rv["error"] = self.error_info
for ui_key in [k for k in self.kwargs.keys() if k.startswith("ui_")]:
rv[ui_key] = self.kwargs[ui_key]
return rv
示例8: _explain_msg_summary
def _explain_msg_summary(self, info):
msg_ts = long(info[6], 36)
days_ago = (time.time() - msg_ts) / (24*3600)
msg_date = datetime.date.fromtimestamp(msg_ts)
date = '%4.4d-%2.2d-%2.2d' % (msg_date.year, msg_date.month, msg_date.day)
urlmap = UrlMap(self.session)
expl = {
'idx': info[0],
'id': info[1],
'from': info[2],
'to': info[3],
'subject': info[4],
'snippet': info[5],
'timestamp': msg_ts,
'date': date,
'friendly_date': _friendly_date(days_ago, date),
'tag_ids': info[7],
'url': urlmap.url_thread(info[0])
}
if info[8]:
expl['editing_url'] = urlmap.url_compose(info[0])
return expl
示例9: _explain_msg_summary
def _explain_msg_summary(self, info):
msg_ts = long(info[6], 36)
days_ago = (time.time() - msg_ts) / (24*3600)
msg_date = datetime.datetime.fromtimestamp(msg_ts)
date = msg_date.strftime("%Y-%m-%d")
urlmap = UrlMap(self.session)
expl = {
'mid': info[0],
'id': info[1],
'from': info[2],
'to': info[3],
'subject': info[4],
'snippet': info[5],
'timestamp': msg_ts,
'shorttime': msg_date.strftime("%H:%M"),
'date': date,
'tag_ids': info[7],
'url': urlmap.url_thread(info[0])
}
if info[8]:
expl['editing_url'] = urlmap.url_edit(info[0])
return expl
示例10: _explain_msg_summary
def _explain_msg_summary(self, info):
msg_ts = long(info[6], 36)
days_ago = (time.time() - msg_ts) / (24 * 3600)
msg_date = datetime.datetime.fromtimestamp(msg_ts)
date = msg_date.strftime("%Y-%m-%d")
urlmap = UrlMap(self.session)
expl = {
"mid": info[0],
"id": info[1],
"from": info[2],
"from_email": ", ".join(ExtractEmails(info[2])),
"to": info[3],
"subject": info[4],
"snippet": info[5],
"timestamp": msg_ts,
"shorttime": msg_date.strftime("%H:%M"),
"date": date,
"tag_ids": info[7],
"url": urlmap.url_thread(info[0]),
}
if info[8]:
expl["editing_url"] = urlmap.url_edit(info[0])
return expl
示例11: _use_data_view
def _use_data_view(self, view_name, result):
dv = UrlMap(self.env.session).map(None, 'GET', view_name, {}, {})[-1]
return dv.view(result)
示例12: _process_manifest_pass_two
def _process_manifest_pass_two(self, full_name,
manifest=None, plugin_path=None):
"""
Pass two of processing the manifest data. This maps templates and
data to API commands and links registers classes and methods as
hooks here and there. As these things depend both on configuration
and the URL map, this happens as a second phase.
"""
if not manifest:
return
manifest_path = lambda *p: self._mf_path(manifest, *p)
manifest_iteritems = lambda *p: self._mf_iteritems(manifest, *p)
# Register javascript classes
for fn in manifest.get('code', {}).get('javascript', []):
class_name = fn.replace('/', '.').rsplit('.', 1)[0]
# FIXME: Is this a good idea?
if full_name.endswith('.'+class_name):
parent, class_name = full_name.rsplit('.', 1)
else:
parent = full_name
self.register_js(parent, class_name,
os.path.join(plugin_path, fn))
# Register CSS files
for fn in manifest.get('code', {}).get('css', []):
file_name = fn.replace('/', '.').rsplit('.', 1)[0]
self.register_css(full_name, file_name,
os.path.join(plugin_path, fn))
# Register web assets
if plugin_path:
from mailpile.urlmap import UrlMap
um = UrlMap(session=self.session, config=self.config)
for url, info in manifest_iteritems('routes'):
filename = os.path.join(plugin_path, info['file'])
# Short-cut for static content
if url.startswith('/static/'):
self.register_web_asset(full_name, url[8:], filename,
mimetype=info.get('mimetype', None))
continue
# Finds the right command class and register asset in
# the right place for that particular command.
commands = []
if (not url.startswith('/api/')) and 'api' in info:
url = '/api/%d%s' % (info['api'], url)
if url[-1] == '/':
url += 'as.html'
for method in ('GET', 'POST', 'PUT', 'UPDATE', 'DELETE'):
try:
commands = um.map(None, method, url, {}, {})
break
except UsageError:
pass
output = [o.get_render_mode()
for o in commands if hasattr(o, 'get_render_mode')]
output = output and output[-1] or 'html'
if commands:
command = commands[-1]
tpath = command.template_path(output.split('.')[-1],
template=output)
self.register_web_asset(full_name,
'html/' + tpath,
filename)
else:
print 'FIXME: Un-routable URL in manifest %s' % url
# Register email content/crypto hooks
s = self
for which, reg in (
('outgoing_content', s.register_outgoing_email_content_transform),
('outgoing_crypto', s.register_outgoing_email_crypto_transform),
('incoming_crypto', s.register_incoming_email_crypto_transform),
('incoming_content', s.register_incoming_email_content_transform)
):
for item in manifest_path('email_transforms', which):
name = '%3.3d_%s' % (int(item.get('priority', 999)), full_name)
reg(name, self._get_class(full_name, item['class']))
# Register search keyword extractors
s = self
for which, reg in (
('meta', s.register_meta_kw_extractor),
('text', s.register_text_kw_extractor),
('data', s.register_data_kw_extractor)
):
for item in manifest_path('keyword_extractors', which):
reg('%s.%s' % (full_name, item),
self._get_class(full_name, item))
# Register contact/vcard hooks
for which, reg in (
('importers', self.register_vcard_importers),
('exporters', self.register_contact_exporters),
('context', self.register_contact_context_providers)
):
#.........这里部分代码省略.........
示例13: _process_manifest_pass_two
def _process_manifest_pass_two(self, full_name, manifest=None, plugin_path=None):
"""
Pass two of processing the manifest data. This maps templates and
data to API commands and links registers classes and methods as
hooks here and there. As these things depend both on configuration
and the URL map, this happens as a second phase.
"""
if not manifest:
return
manifest_path = lambda *p: self._mf_path(manifest, *p)
manifest_iteritems = lambda *p: self._mf_iteritems(manifest, *p)
# Register javascript classes
for fn in manifest.get("code", {}).get("javascript", []):
class_name = fn.replace("/", ".").rsplit(".", 1)[0]
# FIXME: Is this a good idea?
if full_name.endswith("." + class_name):
parent, class_name = full_name.rsplit(".", 1)
else:
parent = full_name
self.register_js(parent, class_name, os.path.join(plugin_path, fn))
# Register CSS files
for fn in manifest.get("code", {}).get("css", []):
file_name = fn.replace("/", ".").rsplit(".", 1)[0]
self.register_css(full_name, file_name, os.path.join(plugin_path, fn))
# Register web assets
if plugin_path:
from mailpile.urlmap import UrlMap
um = UrlMap(session=self.session, config=self.config)
for url, info in manifest_iteritems("routes"):
filename = os.path.join(plugin_path, info["file"])
# Short-cut for static content
if url.startswith("/static/"):
self.register_web_asset(full_name, url[8:], filename, mimetype=info.get("mimetype", None))
continue
# Finds the right command class and register asset in
# the right place for that particular command.
commands = []
if (not url.startswith("/api/")) and "api" in info:
url = "/api/%d%s" % (info["api"], url)
if url[-1] == "/":
url += "as.html"
for method in ("GET", "POST", "PUT", "UPDATE", "DELETE"):
try:
commands = um.map(None, method, url, {}, {})
break
except UsageError:
pass
output = [o.get_render_mode() for o in commands if hasattr(o, "get_render_mode")]
output = output and output[-1] or "html"
if commands:
command = commands[-1]
tpath = command.template_path(output.split(".")[-1], template=output)
self.register_web_asset(full_name, "html/" + tpath, filename)
else:
print "FIXME: Un-routable URL in manifest %s" % url
# Register email content/crypto hooks
s = self
for which, reg in (
("outgoing_content", s.register_outgoing_email_content_transform),
("outgoing_crypto", s.register_outgoing_email_crypto_transform),
("incoming_crypto", s.register_incoming_email_crypto_transform),
("incoming_content", s.register_incoming_email_content_transform),
):
for item in manifest_path("email_transforms", which):
name = "%3.3d_%s" % (int(item.get("priority", 999)), full_name)
reg(name, self._get_class(full_name, item["class"]))
# Register search keyword extractors
s = self
for which, reg in (
("meta", s.register_meta_kw_extractor),
("text", s.register_text_kw_extractor),
("data", s.register_data_kw_extractor),
):
for item in manifest_path("keyword_extractors", which):
reg("%s.%s" % (full_name, item), self._get_class(full_name, item))
# Register contact/vcard hooks
for which, reg in (
("importers", self.register_vcard_importers),
("exporters", self.register_contact_exporters),
("context", self.register_contact_context_providers),
):
for item in manifest_path("contacts", which):
reg(self._get_class(full_name, item))
# Register periodic jobs
def reg_job(info, spd, register):
interval, cls = info["interval"], info["class"]
callback = self._get_class(full_name, cls)
register("%s.%s/%s-%s" % (full_name, cls, spd, interval), interval, callback)
#.........这里部分代码省略.........
示例14: _use_data_view
def _use_data_view(self, view_name, result):
self._debug('use_data_view(%s, ...)' % (view_name))
dv = UrlMap(self.env.session).map(None, 'GET', view_name, {}, {})[-1]
return dv.view(result)
示例15: _process_manifest_pass_two
def _process_manifest_pass_two(self, full_name,
manifest=None, plugin_path=None):
"""
Pass two of processing the manifest data. This maps templates and
data to API commands and links registers classes and methods as
hooks here and there. As these things depend both on configuration
and the URL map, this happens as a second phase.
"""
if not manifest:
return
manifest_path = lambda *p: self._mf_path(manifest, *p)
manifest_iteritems = lambda *p: self._mf_iteritems(manifest, *p)
# Register contact/vcard hooks
for importer in manifest_path('contacts', 'importers'):
self.register_vcard_importers(self._get_class(full_name, importer))
for exporter in manifest_path('contacts', 'exporters'):
self.register_contact_exporters(self._get_class(full_name,
exporter))
for context in manifest_path('contacts', 'context'):
self.register_contact_context_providers(self._get_class(full_name,
context))
# Register javascript classes
for fn in manifest.get('code', {}).get('javascript', []):
class_name = fn.replace('/', '.').rsplit('.', 1)[0]
self.register_js(full_name, class_name,
os.path.join(plugin_path, fn))
# Register CSS files
for fn in manifest.get('code', {}).get('css', []):
file_name = fn.replace('/', '.').rsplit('.', 1)[0]
self.register_css(full_name, file_name,
os.path.join(plugin_path, fn))
# Register web assets
if plugin_path:
try:
from mailpile.urlmap import UrlMap
um = UrlMap(session=self.session, config=self.config)
for url, info in manifest_iteritems('routes'):
filename = os.path.join(plugin_path, info['file'])
# Short-cut for static content
if url.startswith('/static/'):
self.register_web_asset(full_name, url[8:], filename,
mimetype=info.get('mimetype', None))
continue
# Finds the right command class and register asset in
# the right place for that particular command.
commands = []
if (not url.startswith('/api/')) and 'api' in info:
url = '/api/%d%s' % (info['api'], url)
if url[-1] == '/':
url += 'as.html'
for method in ('GET', 'POST', 'PUT', 'UPDATE', 'DELETE'):
try:
commands = um.map(None, method, url, {}, {})
break
except UsageError:
pass
output = [o.get_render_mode()
for o in commands if hasattr(o, 'get_render_mode')]
output = output and output[-1] or 'html'
if commands:
command = commands[-1]
tpath = command.template_path(output.split('.')[-1],
template=output)
self.register_web_asset(full_name,
'html/' + tpath,
filename)
else:
print 'FIXME: Un-routable URL in manifest %s' % url
except:
import traceback
traceback.print_exc()