本文整理汇总了Python中r2.lib.filters._force_unicode函数的典型用法代码示例。如果您正苦于以下问题:Python _force_unicode函数的具体用法?Python _force_unicode怎么用?Python _force_unicode使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了_force_unicode函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: __init__
def __init__(self, link = None, comment = None,
link_title = '', *a, **kw):
# TODO: temp hack until we find place for builder_wrapper
link.render_full = True
from r2.controllers.listingcontroller import ListingController
link_builder = IDBuilder(link._fullname,
wrap = ListingController.builder_wrapper)
# link_listing will be the one-element listing at the top
self.link_listing = LinkListing(link_builder, nextprev=False).listing()
# link is a wrapped Link object
self.link = self.link_listing.things[0]
link_title = ((self.link.title) if hasattr(self.link, 'title') else '')
if comment:
author = Account._byID(comment.author_id, data=True).name
params = {'author' : author, 'title' : _force_unicode(link_title)}
title = strings.permalink_title % params
else:
params = {'title':_force_unicode(link_title), 'site' : c.site.title}
title = strings.link_info_title % params
if not c.default_sr:
# Not on the main page, so include a pointer to the canonical URL for this link
self.canonical_link = link.canonical_url
Reddit.__init__(self, title = title, body_class = 'post', *a, **kw)
示例2: __init__
def __init__(
self,
title,
dest,
sr_path=True,
nocname=False,
aliases=None,
target="",
use_params=False,
css_class="",
data=None,
):
aliases = aliases or []
aliases = set(_force_unicode(a.rstrip("/")) for a in aliases)
if dest:
aliases.add(_force_unicode(dest.rstrip("/")))
self.title = title
self.dest = dest
self.selected = False
self.sr_path = sr_path
self.nocname = nocname
self.aliases = aliases
self.target = target
self.use_params = use_params
self.data = data
Styled.__init__(self, self._style, css_class=css_class)
示例3: query_string
def query_string(dict):
pairs = []
for k,v in dict.iteritems():
if v is not None:
try:
k = url_escape(_force_unicode(k))
v = url_escape(_force_unicode(v))
pairs.append(k + '=' + v)
except UnicodeDecodeError:
continue
if pairs:
return '?' + '&'.join(pairs)
else:
return ''
示例4: __init__
def __init__(self, title, dest, sr_path = True,
nocname=False, opt = '', aliases = [],
target = "", style = "plain", **kw):
# keep original dest to check against c.location when rendering
aliases = set(_force_unicode(a.rstrip('/')) for a in aliases)
aliases.add(_force_unicode(dest.rstrip('/')))
self.request_params = dict(request.GET)
self.stripped_path = _force_unicode(request.path.rstrip('/').lower())
Styled.__init__(self, style = style, sr_path = sr_path,
nocname = nocname, target = target,
aliases = aliases, dest = dest,
selected = False,
title = title, opt = opt, **kw)
示例5: format_output_url
def format_output_url(cls, url, **kw):
"""
Helper method used during redirect to ensure that the redirect
url (assisted by frame busting code or javasctipt) will point
to the correct domain and not have any extra dangling get
parameters. The extensions are also made to match and the
resulting url is utf8 encoded.
Node: for development purposes, also checks that the port
matches the request port
"""
preserve_extension = kw.pop("preserve_extension", True)
u = UrlParser(url)
if u.is_reddit_url():
# make sure to pass the port along if not 80
if not kw.has_key('port'):
kw['port'] = request.port
# disentangle the cname (for urls that would have
# cnameframe=1 in them)
u.mk_cname(**kw)
# make sure the extensions agree with the current page
if preserve_extension and c.extension:
u.set_extension(c.extension)
# unparse and encode it un utf8
rv = _force_unicode(u.unparse()).encode('utf8')
if "\n" in rv or "\r" in rv:
abort(400)
return rv
示例6: build
def build(self, base_path=""):
"""Generates the href of the button based on the base_path provided."""
if self.style == "external":
self.path = self.dest
self.bare_path = self.dest
return
# append to the path or update the get params dependent on presence
# of opt
if self.opt:
p = request.get.copy()
p[self.opt] = self.dest
else:
p = {}
base_path = ("%s/%s/" % (base_path, self.dest)).replace("//", "/")
p.update(self.dest_params)
self.bare_path = _force_unicode(base_path.replace("//", "/")).lower()
self.bare_path = self.bare_path.rstrip("/")
# append the query string
base_path += query_string(p)
# since we've been sloppy of keeping track of "//", get rid
# of any that may be present
self.path = base_path.replace("//", "/")
示例7: format_output_url
def format_output_url(cls, url, **kw):
"""
Helper method used during redirect to ensure that the redirect
url (assisted by frame busting code or javasctipt) will point
to the correct domain and not have any extra dangling get
parameters. The extensions are also made to match and the
resulting url is utf8 encoded.
Node: for development purposes, also checks that the port
matches the request port
"""
u = UrlParser(url)
if u.is_reddit_url():
# make sure to pass the port along if not 80
if not kw.has_key("port"):
kw["port"] = request.port
# disentagle the cname (for urls that would have
# cnameframe=1 in them)
u.mk_cname(**kw)
# make sure the extensions agree with the current page
if c.extension:
u.set_extension(c.extension)
# unparse and encode it un utf8
rv = _force_unicode(u.unparse()).encode("utf8")
if any(ch.isspace() for ch in rv):
raise ValueError("Space characters in redirect URL: [%r]" % rv)
return rv
示例8: email_password_change_email
def email_password_change_email(user, new_email=None, password_change=False):
"""Queues a system email for email or password change notification."""
from r2.lib.pages import EmailPasswordChangeEmail
token = make_reset_token(AccountRecoveryToken, user, issue_limit=1)
if not token:
return False
passlink = token.make_token_url()
if not passlink:
return False
g.log.info("Generated %s: %s", AccountRecoveryToken.__name__, passlink)
signer = MessageSigner(g.secrets["outbound_url_secret"])
signature = base64.urlsafe_b64encode(
signer.make_signature(
_force_unicode(passlink),
max_age=timedelta(days=180))
)
email_kind = Email.Kind.EMAIL_CHANGE
if password_change:
email_kind = Email.Kind.PASSWORD_CHANGE
_system_email(
user.email,
EmailPasswordChangeEmail(
user=user,
new_email=new_email,
passlink=passlink,
email_kind=email_kind,
signature=signature,
).render(style='email'),
email_kind,
reply_to=g.support_email,
)
return True
示例9: password_email
def password_email(user):
"""For resetting a user's password."""
from r2.lib.pages import PasswordReset
token = make_reset_token(PasswordResetToken, user, issue_limit=3)
if not token:
return False
passlink = token.make_token_url()
if not passlink:
return False
g.log.info("Generated %s: %s for user %s",
PasswordResetToken.__name__,
passlink,
user.name)
signer = MessageSigner(g.secrets["outbound_url_secret"])
signature = base64.urlsafe_b64encode(
signer.make_signature(
_force_unicode(passlink),
max_age=timedelta(days=180))
)
_system_email(
user.email,
PasswordReset(
user=user,
passlink=passlink,
signature=signature,
).render(style='email'),
Email.Kind.RESET_PASSWORD,
reply_to=g.support_email,
user=user,
)
return True
示例10: GET_related
def GET_related(self, num, article, after, reverse, count):
"""Related page: performs a search using title of article as
the search query.
"""
if not can_view_link_comments(article):
abort(403, 'forbidden')
query = self.related_replace_regex.sub(self.related_replace_with,
article.title)
query = _force_unicode(query)
query = query[:1024]
query = "|".join(query.split())
query = "title:'%s'" % query
rel_range = timedelta(days=3)
start = (article._date - rel_range).strftime("%s")
end = (article._date + rel_range).strftime("%s")
query = "(and %s timestamp:%s..%s)" % (query, start, end)
q = SearchQuery(query, raw_sort="-text_relevance",
syntax="cloudsearch")
num, t, pane = self._search(q, num=num, after=after, reverse=reverse,
count=count)
return LinkInfoPage(link=article, content=pane,
subtitle=_('related')).render()
示例11: _by_domain
def _by_domain(cls, domain, _update = False):
sr_id = cls._by_domain_cache(_force_unicode(domain).lower(),
_update = _update)
if sr_id:
return cls._byID(sr_id, True)
else:
return None
示例12: build
def build(self, base_path = ''):
'''Generates the href of the button based on the base_path provided.'''
# append to the path or update the get params dependent on presence
# of opt
if self.opt:
p = self.request_params.copy()
if self.dest:
p[self.opt] = self.dest
elif self.opt in p:
del p[self.opt]
else:
p = {}
base_path = ("%s/%s/" % (base_path, self.dest)).replace('//', '/')
self.action_params = p
self.bare_path = _force_unicode(base_path.replace('//', '/')).lower()
self.bare_path = self.bare_path.rstrip('/')
self.base_path = base_path
# append the query string
base_path += query_string(p)
# since we've been sloppy of keeping track of "//", get rid
# of any that may be present
self.path = base_path.replace('//', '/')
示例13: __init__
def __init__(self, query, sr=None, sort=None, syntax=None, raw_sort=None,
faceting=None, recent=None, include_over18=True,
rank_expressions=None, start=0, num=1000):
if syntax is None:
syntax = self.default_syntax
elif syntax not in self.known_syntaxes:
raise ValueError("Unknown search syntax: %s" % syntax)
self.syntax = syntax
self.query = filters._force_unicode(query or u'')
self.converted_data = None
self.bq = u''
# filters
self.sr = sr
self._recent = recent
self.recent = self.recents[recent]
self.include_over18 = include_over18
# rank / rank expressions
self._sort = sort
if raw_sort:
self.sort = raw_sort
else:
self.sort = self.sorts[sort]
self.rank_expressions = rank_expressions
# pagination
self.start = start
self.num = num
# facets
self.faceting = faceting
self.results = None
示例14: renderpolls
def renderpolls(text, thing):
polls_not_voted = []
polls_voted = []
oldballots = []
def checkmatch(match):
pollid = match.group(1)
try:
poll = Poll._byID(pollid, True)
if poll.thingid != thing._id:
return "Error: Poll belongs to a different comment"
if poll.user_has_voted(c.user):
polls_voted.append(pollid)
return poll.render_results()
else:
polls_not_voted.append(pollid)
return poll.render()
except NotFound:
return "Error: Poll not found!"
text = re.sub(pollid_re, checkmatch, _force_unicode(text))
if polls_voted or polls_not_voted:
voted_on_all = not polls_not_voted
page = _get_pageclass('PollWrapper')(thing, text, voted_on_all)
text = page.render('html')
return text
示例15: submit_link
def submit_link(self):
from r2.lib.template_helpers import get_domain
from mako.filters import url_escape
d = get_domain(subreddit=False)
u = _force_unicode(self.url())
return "http://%s/r/ads/submit?url=%s" % (d, url_escape(u))