本文整理汇总了Python中r2.lib.filters._force_unicode函数的典型用法代码示例。如果您正苦于以下问题:Python _force_unicode函数的具体用法?Python _force_unicode怎么用?Python _force_unicode使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了_force_unicode函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的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)
开发者ID:EmileKroeger,项目名称:lesswrong,代码行数:30,代码来源:pages.py
示例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)
开发者ID:dmazak,项目名称:reddit,代码行数:29,代码来源:menus.py
示例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 ''
开发者ID:HerculesCE,项目名称:reddit,代码行数:14,代码来源:utils.py
示例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)
开发者ID:DeanHyde,项目名称:reddit,代码行数:15,代码来源:menus.py
示例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
开发者ID:GodOfConquest,项目名称:reddit,代码行数:32,代码来源:base.py
示例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("//", "/")
开发者ID:brendanlong,项目名称:lesswrong,代码行数:26,代码来源:menus.py
示例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
开发者ID:ketralnis,项目名称:reddit,代码行数:31,代码来源:base.py
示例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
开发者ID:zeantsoi,项目名称:reddit,代码行数:34,代码来源:emailer.py
示例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
开发者ID:zeantsoi,项目名称:reddit,代码行数:33,代码来源:emailer.py
示例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()
开发者ID:DanHoerst,项目名称:reddit,代码行数:25,代码来源:front.py
示例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
开发者ID:rajbot,项目名称:tikical,代码行数:7,代码来源:subreddit.py
示例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('//', '/')
开发者ID:Gelob,项目名称:reddit,代码行数:27,代码来源:menus.py
示例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
开发者ID:Sheesha1992,项目名称:reddit,代码行数:35,代码来源:cloudsearch.py
示例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
开发者ID:EeroHeikkinen,项目名称:ikaros,代码行数:29,代码来源:poll.py
示例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))
开发者ID:99plus2,项目名称:reddit,代码行数:8,代码来源:ad.py
示例16: POST_spendcreddits
def POST_spendcreddits(self, form, jquery, months, passthrough):
if months is None or months < 1:
form.set_html(".status", _("nice try."))
return
days = months * 31
if not passthrough:
raise ValueError("/spendcreddits got no passthrough?")
blob_key, payment_blob = get_blob(passthrough)
if payment_blob["goldtype"] != "gift":
raise ValueError("/spendcreddits payment_blob %s has goldtype %s" % (passthrough, payment_blob["goldtype"]))
signed = payment_blob["signed"]
giftmessage = _force_unicode(payment_blob["giftmessage"])
recipient_name = payment_blob["recipient"]
if payment_blob["account_id"] != c.user._id:
fmt = "/spendcreddits payment_blob %s has userid %d " + "but c.user._id is %d"
raise ValueError(fmt % passthrough, payment_blob["account_id"], c.user._id)
try:
recipient = Account._by_name(recipient_name)
except NotFound:
raise ValueError("Invalid username %s in spendcreddits, buyer = %s" % (recipient_name, c.user.name))
if recipient._deleted:
form.set_html(".status", _("that user has deleted their account"))
return
if not c.user.employee:
if months > c.user.gold_creddits:
raise ValueError("%s is trying to sneak around the creddit check" % c.user.name)
c.user.gold_creddits -= months
c.user.gold_creddit_escrow += months
c.user._commit()
comment_id = payment_blob.get("comment")
comment = send_gift(c.user, recipient, months, days, signed, giftmessage, comment_id)
if not c.user.employee:
c.user.gold_creddit_escrow -= months
c.user._commit()
payment_blob["status"] = "processed"
g.hardcache.set(blob_key, payment_blob, 86400 * 30)
form.set_html(".status", _("the gold has been delivered!"))
form.find("button").hide()
if comment:
gilding_message = make_comment_gold_message(comment, user_gilded=True)
jquery.gild_comment(comment_id, gilding_message, comment.gildings)
开发者ID:tolgaek,项目名称:reddit,代码行数:55,代码来源:ipn.py
示例17: title
def title(self):
titles = {'overview': _("Overview for %(user)s - %(site)s"),
'comments': _("Comments by %(user)s - %(site)s"),
'submitted': _("Submitted by %(user)s - %(site)s"),
'liked': _("Liked by %(user)s - %(site)s"),
'disliked': _("Disliked by %(user)s - %(site)s"),
'hidden': _("Hidden by %(user)s - %(site)s"),
'drafts': _("Drafts for %(user)s - %(site)s")}
title = titles.get(self.where, _('Profile for %(user)s - %(site)s')) \
% dict(user = _force_unicode(self.vuser.name), site = c.site.title)
return title
开发者ID:EeroHeikkinen,项目名称:ikaros,代码行数:11,代码来源:listingcontroller.py
示例18: get_related_query
def get_related_query(self, query, article, start, end, nsfw):
'''build related query in cloudsearch syntax'''
query = _force_unicode(query)
query = query[:1024]
query = u"|".join(query.split())
query = u"title:'%s'" % query
nsfw = nsfw and u"nsfw:0" or u""
query = u"(and %s timestamp:%s..%s %s)" % (query, start, end, nsfw)
return g.search.SearchQuery(query,
raw_sort="-text_relevance",
syntax="cloudsearch")
开发者ID:pra85,项目名称:reddit,代码行数:11,代码来源:cloudsearch.py
示例19: is_selected
def is_selected(self):
"""Given the current request path, would the button be selected."""
if self.opt:
return request.params.get(self.opt, '') in self.aliases
else:
stripped_path = request.path.rstrip('/').lower()
ustripped_path = _force_unicode(stripped_path)
if stripped_path == self.bare_path:
return True
if stripped_path in self.aliases:
return True
开发者ID:EmileKroeger,项目名称:lesswrong,代码行数:11,代码来源:menus.py
示例20: get_message_subject
def get_message_subject(message):
sr = Subreddit._byID(message.sr_id, data=True)
if message.first_message:
first_message = Message._byID(message.first_message, data=True)
conversation_subject = first_message.subject
else:
conversation_subject = message.subject
return u"[r/{subreddit} mail]: {subject}".format(
subreddit=sr.name, subject=_force_unicode(conversation_subject))
开发者ID:AHAMED750,项目名称:reddit,代码行数:11,代码来源:message_to_email.py
注:本文中的r2.lib.filters._force_unicode函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论