本文整理汇总了Python中sumo.utils.smart_int函数的典型用法代码示例。如果您正苦于以下问题:Python smart_int函数的具体用法?Python smart_int怎么用?Python smart_int使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了smart_int函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: compare_revisions
def compare_revisions(request, document_slug):
"""Compare two wiki document revisions.
The ids are passed as query string parameters (to and from).
"""
locale = request.GET.get('locale', request.locale)
doc = get_object_or_404(
Document, locale=locale, slug=document_slug)
if 'from' not in request.GET or 'to' not in request.GET:
raise Http404
from_id = smart_int(request.GET.get('from'))
to_id = smart_int(request.GET.get('to'))
revision_from = get_object_or_404(Revision, document=doc, id=from_id)
revision_to = get_object_or_404(Revision, document=doc, id=to_id)
if request.is_ajax():
template = 'wiki/includes/revision_diff.html'
else:
template = 'wiki/compare_revisions.html'
return jingo.render(request, template,
{'document': doc, 'revision_from': revision_from,
'revision_to': revision_to})
示例2: wiki_rows
def wiki_rows(request, readout_slug):
"""Return the table contents HTML for the given readout and mode."""
readout = _kb_readout(
request, readout_slug, READOUTS, locale=request.GET.get("locale"), mode=smart_int(request.GET.get("mode"), None)
)
max_rows = smart_int(request.GET.get("max"), fallback=None)
return HttpResponse(readout.render(max_rows=max_rows))
示例3: wiki_rows
def wiki_rows(request, readout_slug):
"""Return the table contents HTML for the given readout and mode."""
product = _get_product(request)
readout = _kb_readout(request, readout_slug, READOUTS,
locale=request.GET.get('locale'),
mode=smart_int(request.GET.get('mode'), None),
product=product)
max_rows = smart_int(request.GET.get('max'), fallback=None)
return HttpResponse(readout.render(max_rows=max_rows))
示例4: helpful_vote
def helpful_vote(request, document_slug):
"""Vote for Helpful/Not Helpful document"""
revision = get_object_or_404(
Revision, id=smart_int(request.POST['revision_id']))
if not revision.has_voted(request):
ua = request.META.get('HTTP_USER_AGENT', '')[:1000] # 1000 max_length
vote = HelpfulVote(revision=revision, user_agent=ua)
if 'helpful' in request.POST:
vote.helpful = True
message = _('Glad to hear it — thanks for the feedback!')
else:
message = _('Sorry to hear that. Try searching for solutions '
'below.')
if request.user.is_authenticated():
vote.creator = request.user
else:
vote.anonymous_id = request.anonymous.anonymous_id
vote.save()
statsd.incr('wiki.vote')
else:
message = _('You already voted on this Article.')
if request.is_ajax():
return HttpResponse(json.dumps({'message': message}))
return HttpResponseRedirect(revision.document.get_absolute_url())
示例5: helpful_vote
def helpful_vote(request, document_slug):
"""Vote for Helpful/Not Helpful document"""
if 'revision_id' not in request.POST:
return HttpResponseBadRequest()
revision = get_object_or_404(
Revision, id=smart_int(request.POST['revision_id']))
survey = None
if revision.document.category == TEMPLATES_CATEGORY:
return HttpResponseBadRequest()
if not revision.has_voted(request):
ua = request.META.get('HTTP_USER_AGENT', '')[:1000] # 1000 max_length
vote = HelpfulVote(revision=revision, user_agent=ua)
if 'helpful' in request.POST:
vote.helpful = True
message = _('Glad to hear it — thanks for the feedback!')
else:
message = _('Sorry to hear that.')
# If user is over the limit, don't save but pretend everything is ok.
if not request.limited:
if request.user.is_authenticated():
vote.creator = request.user
else:
vote.anonymous_id = request.anonymous.anonymous_id
vote.save()
statsd.incr('wiki.vote')
# Send a survey if flag is enabled and vote wasn't helpful.
if 'helpful' not in request.POST:
survey = jingo.render_to_string(
request, 'wiki/includes/unhelpful_survey.html',
{'vote_id': vote.id})
# Save vote metadata: referrer and search query (if available)
for name in ['referrer', 'query', 'source']:
val = request.POST.get(name)
if val:
vote.add_metadata(name, val)
else:
message = _('You already voted on this Article.')
if request.is_ajax():
r = {'message': message}
if survey:
r.update(survey=survey)
return HttpResponse(json.dumps(r))
return HttpResponseRedirect(revision.document.get_absolute_url())
示例6: unhelpful_survey
def unhelpful_survey(request):
"""Ajax only view: Unhelpful vote survey processing."""
vote = get_object_or_404(HelpfulVote,
id=smart_int(request.POST.get('vote_id')))
# The survey is the posted data, minus the vote_id and button value.
survey = request.POST.copy()
survey.pop('vote_id')
survey.pop('button')
# Save the survey in JSON format, taking care not to exceed 1000 chars.
vote.add_metadata('survey', truncated_json_dumps(survey, 1000, 'comment'))
return HttpResponse(
json.dumps({'message': _('Thanks for making us better!')}))
示例7: compare_revisions
def compare_revisions(request, document_slug):
"""Compare two wiki document revisions.
The ids are passed as query string parameters (to and from).
"""
locale = request.GET.get("locale", request.locale)
doc = get_object_or_404(Document, locale=locale, slug=document_slug)
if "from" not in request.GET or "to" not in request.GET:
raise Http404
from_id = smart_int(request.GET.get("from"))
to_id = smart_int(request.GET.get("to"))
revision_from = get_object_or_404(Revision, document=doc, id=from_id)
revision_to = get_object_or_404(Revision, document=doc, id=to_id)
if request.is_ajax():
template = "wiki/includes/revision_diff.html"
else:
template = "wiki/compare_revisions.html"
return jingo.render(
request, template, {"document": doc, "revision_from": revision_from, "revision_to": revision_to}
)
示例8: helpful_vote
def helpful_vote(request, document_slug):
"""Vote for Helpful/Not Helpful document"""
if "revision_id" not in request.POST:
return HttpResponseBadRequest()
revision = get_object_or_404(Revision, id=smart_int(request.POST["revision_id"]))
if not revision.has_voted(request):
ua = request.META.get("HTTP_USER_AGENT", "")[:1000] # 1000 max_length
vote = HelpfulVote(revision=revision, user_agent=ua)
if "helpful" in request.POST:
vote.helpful = True
message = _("Glad to hear it — thanks for the feedback!")
else:
message = _("Sorry to hear that. Try searching for solutions " "below.")
if request.user.is_authenticated():
vote.creator = request.user
else:
vote.anonymous_id = request.anonymous.anonymous_id
vote.save()
statsd.incr("wiki.vote")
# Save vote metadata: referrer and search query (if available)
for name in ["referrer", "query"]:
val = request.POST.get(name)
if val:
vote.add_metadata(name, val)
else:
message = _("You already voted on this Article.")
if request.is_ajax():
return HttpResponse(json.dumps({"message": message}))
return HttpResponseRedirect(revision.document.get_absolute_url())
示例9: search
def search(request, template=None):
"""Performs search or displays the search form."""
# JSON-specific variables
is_json = (request.GET.get('format') == 'json')
callback = request.GET.get('callback', '').strip()
mimetype = 'application/x-javascript' if callback else 'application/json'
# Search "Expires" header format
expires_fmt = '%A, %d %B %Y %H:%M:%S GMT'
# Check callback is valid
if is_json and callback and not jsonp_is_valid(callback):
return HttpResponse(
json.dumps({'error': _('Invalid callback function.')}),
mimetype=mimetype, status=400)
language = locale_or_default(request.GET.get('language', request.locale))
r = request.GET.copy()
a = request.GET.get('a', '0')
# Search default values
try:
category = map(int, r.getlist('category')) or \
settings.SEARCH_DEFAULT_CATEGORIES
except ValueError:
category = settings.SEARCH_DEFAULT_CATEGORIES
r.setlist('category', category)
# Basic form
if a == '0':
r['w'] = r.get('w', constants.WHERE_BASIC)
# Advanced form
if a == '2':
r['language'] = language
r['a'] = '1'
# TODO: Rewrite so SearchForm is unbound initially and we can use `initial`
# on the form fields.
if 'include_archived' not in r:
r['include_archived'] = False
search_form = SearchForm(r)
if not search_form.is_valid() or a == '2':
if is_json:
return HttpResponse(
json.dumps({'error': _('Invalid search data.')}),
mimetype=mimetype,
status=400)
t = template if request.MOBILE else 'search/form.html'
search_ = jingo.render(request, t,
{'advanced': a, 'request': request,
'search_form': search_form})
search_['Cache-Control'] = 'max-age=%s' % \
(settings.SEARCH_CACHE_PERIOD * 60)
search_['Expires'] = (datetime.utcnow() +
timedelta(
minutes=settings.SEARCH_CACHE_PERIOD)) \
.strftime(expires_fmt)
return search_
cleaned = search_form.cleaned_data
page = max(smart_int(request.GET.get('page')), 1)
offset = (page - 1) * settings.SEARCH_RESULTS_PER_PAGE
# get language name for display in template
lang = language.lower()
if settings.LANGUAGES.get(lang):
lang_name = settings.LANGUAGES[lang]
else:
lang_name = ''
wiki_s = wiki_search
question_s = question_search
discussion_s = discussion_search
documents = []
# wiki filters
# Category filter
if cleaned['category']:
wiki_s = wiki_s.filter(category__in=cleaned['category'])
# Locale filter
wiki_s = wiki_s.filter(locale=language)
# Product filter
products = cleaned['product']
for p in products:
wiki_s = wiki_s.filter(tag=p)
# Tags filter
tags = [t.strip() for t in cleaned['tags'].split()]
for t in tags:
wiki_s = wiki_s.filter(tag=t)
# Archived bit
#.........这里部分代码省略.........
示例10: search_with_es
def search_with_es(request, template=None):
"""ES-specific search view"""
engine = "elastic"
# Time ES and Sphinx separate. See bug 723930.
# TODO: Remove this once Sphinx is gone.
start = time.time()
# JSON-specific variables
is_json = request.GET.get("format") == "json"
callback = request.GET.get("callback", "").strip()
mimetype = "application/x-javascript" if callback else "application/json"
# Search "Expires" header format
expires_fmt = "%A, %d %B %Y %H:%M:%S GMT"
# Check callback is valid
if is_json and callback and not jsonp_is_valid(callback):
return HttpResponse(json.dumps({"error": _("Invalid callback function.")}), mimetype=mimetype, status=400)
language = locale_or_default(request.GET.get("language", request.locale))
r = request.GET.copy()
a = request.GET.get("a", "0")
# Search default values
try:
category = map(int, r.getlist("category")) or settings.SEARCH_DEFAULT_CATEGORIES
except ValueError:
category = settings.SEARCH_DEFAULT_CATEGORIES
r.setlist("category", category)
# Basic form
if a == "0":
r["w"] = r.get("w", constants.WHERE_BASIC)
# Advanced form
if a == "2":
r["language"] = language
r["a"] = "1"
# TODO: Rewrite so SearchForm is unbound initially and we can use
# `initial` on the form fields.
if "include_archived" not in r:
r["include_archived"] = False
search_form = SearchForm(r)
if not search_form.is_valid() or a == "2":
if is_json:
return HttpResponse(json.dumps({"error": _("Invalid search data.")}), mimetype=mimetype, status=400)
t = template if request.MOBILE else "search/form.html"
search_ = jingo.render(request, t, {"advanced": a, "request": request, "search_form": search_form})
search_["Cache-Control"] = "max-age=%s" % (settings.SEARCH_CACHE_PERIOD * 60)
search_["Expires"] = (datetime.utcnow() + timedelta(minutes=settings.SEARCH_CACHE_PERIOD)).strftime(expires_fmt)
return search_
cleaned = search_form.cleaned_data
page = max(smart_int(request.GET.get("page")), 1)
offset = (page - 1) * settings.SEARCH_RESULTS_PER_PAGE
# TODO: This is fishy--why does it have to be coded this way?
# get language name for display in template
lang = language.lower()
if settings.LANGUAGES.get(lang):
lang_name = settings.LANGUAGES[lang]
else:
lang_name = ""
wiki_s = Document.search()
question_s = Question.search()
discussion_s = Thread.search()
# wiki filters
# Category filter
if cleaned["category"]:
wiki_s = wiki_s.filter(document_category__in=cleaned["category"])
# Locale filter
wiki_s = wiki_s.filter(document_locale=language)
# Product filter
products = cleaned["product"]
for p in products:
wiki_s = wiki_s.filter(document_tag=p)
# Tags filter
tags = [t.strip() for t in cleaned["tags"].split()]
for t in tags:
wiki_s = wiki_s.filter(document_tag=t)
# Archived bit
if a == "0" and not cleaned["include_archived"]:
# Default to NO for basic search:
cleaned["include_archived"] = False
if not cleaned["include_archived"]:
wiki_s = wiki_s.filter(document_is_archived=False)
# End of wiki filters
#.........这里部分代码省略.........
示例11: test_sanity
def test_sanity(self):
eq_(10, smart_int('10'))
eq_(10, smart_int('10.5'))
示例12: test_large_values
def test_large_values(self):
"""Makes sure ints that would cause an overflow result in fallback."""
eq_(0, smart_int('1' * 1000))
示例13: test_wrong_type
def test_wrong_type(self):
eq_(0, smart_int(None))
eq_(10, smart_int([], 10))
示例14: test_empty_string
def test_empty_string(self):
eq_(0, smart_int(''))
示例15: test_int
def test_int(self):
eq_(10, smart_int(10))