本文整理汇总了Python中tower._函数的典型用法代码示例。如果您正苦于以下问题:Python _函数的具体用法?Python _怎么用?Python _使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了_函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: form_valid
def form_valid(self, form):
"""Custom form validation to support email changing.
If user is already authenticated and reaches this points, it's
an email changing procedure. Validate that email is good and
save it in the database.
Otherwise continue with the default django-browserid verification.
"""
if not self.request.user.is_authenticated():
return super(BrowserIDVerify, self).form_valid(form)
failure_url = urlparams(reverse('phonebook:profile_edit'), bid_login_failed=1)
self.assertion = form.cleaned_data['assertion']
self.audience = get_audience(self.request)
result = verify(self.assertion, self.audience)
if not result:
messages.error(self.request, _('Authentication failed.'))
return redirect(failure_url)
email = result['email']
if User.objects.filter(email=email).exists():
messages.error(self.request, _('Email already exists in the database.'))
return redirect('phonebook:logout')
user = self.request.user
user.email = email
user.save()
return redirect('phonebook:profile_view', user.username)
示例2: in_app_config
def in_app_config(request, addon_id, addon, webapp=True):
inapp = addon.premium_type in amo.ADDON_INAPPS
if not inapp:
messages.error(request,
_('Your app is not configured for in-app payments.'))
return redirect(reverse('mkt.developers.apps.payments',
args=[addon.app_slug]))
try:
account = addon.app_payment_account
except ObjectDoesNotExist:
messages.error(request, _('No payment account for this app.'))
return redirect(reverse('mkt.developers.apps.payments',
args=[addon.app_slug]))
seller_config = get_seller_product(account)
owner = acl.check_addon_ownership(request, addon)
if request.method == 'POST':
# Reset the in-app secret for the app.
(client.api.generic
.product(seller_config['resource_pk'])
.patch(data={'secret': generate_key(48)}))
messages.success(request, _('Changes successfully saved.'))
return redirect(reverse('mkt.developers.apps.in_app_config',
args=[addon.app_slug]))
return jingo.render(request, 'developers/payments/in-app-config.html',
{'addon': addon, 'owner': owner,
'seller_config': seller_config})
示例3: twitter_post
def twitter_post(request):
"""Post a tweet, and return a rendering of it (and any replies)."""
try:
reply_to_id = int(request.POST.get('reply_to', ''))
except ValueError:
# L10n: the tweet needs to be a reply to another tweet.
return HttpResponseBadRequest(_('Reply-to is empty'))
content = request.POST.get('content', '')
if len(content) == 0:
# L10n: the tweet has no content.
return HttpResponseBadRequest(_('Message is empty'))
if len(content) > 140:
return HttpResponseBadRequest(_('Message is too long'))
try:
credentials = request.twitter.api.verify_credentials()
username = credentials['screen_name']
if username in settings.CC_BANNED_USERS:
return render(request, 'customercare/tweets.html',
{'tweets': []})
result = request.twitter.api.update_status(
status=content,
in_reply_to_status_id=reply_to_id)
except (TwythonError, TwythonAuthError), e:
# L10n: {message} is an error coming from our twitter api library
return HttpResponseBadRequest(
_('An error occured: {message}').format(message=e))
示例4: emailchange
def emailchange(request, user_id, token, hash):
user = get_object_or_404(UserProfile, id=user_id)
try:
_uid, newemail = EmailResetCode.parse(token, hash)
except ValueError:
return http.HttpResponse(status=400)
if _uid != user.id:
# I'm calling this a warning because invalid hashes up to this point
# could be any number of things, but this is a targeted attack from
# one user account to another
log.warning((u"[Tampering] Valid email reset code for UID (%s) "
"attempted to change email address for user (%s)")
% (_uid, user))
return http.HttpResponse(status=400)
user.email = newemail
user.save()
l = {'user': user, 'newemail': newemail}
log.info(u"User (%(user)s) confirmed new email address (%(newemail)s)" % l)
messages.success(request, _('Your email address was changed successfully'),
_(u'From now on, please use {0} to log in.').format(newemail))
return http.HttpResponseRedirect(reverse('users.edit'))
示例5: setup_viewer
def setup_viewer(request, file_obj):
data = {
"file": file_obj,
"version": file_obj.version,
"addon": file_obj.version.addon,
"status": False,
"selected": {},
"validate_url": "",
}
if acl.check_reviewer(request) or acl.check_addon_ownership(
request, file_obj.version.addon, viewer=True, ignore_disabled=True
):
data["validate_url"] = reverse(
"mkt.developers.apps.json_file_validation", args=[file_obj.version.addon.app_slug, file_obj.id]
)
if acl.check_reviewer(request):
data["file_link"] = {
"text": _("Back to review"),
"url": reverse("reviewers.apps.review", args=[data["addon"].app_slug]),
}
else:
data["file_link"] = {"text": _("Back to app"), "url": reverse("detail", args=[data["addon"].pk])}
return data
示例6: answer_vote
def answer_vote(request, question_id, answer_id):
"""Vote for Helpful/Not Helpful answers"""
answer = get_object_or_404(Answer, pk=answer_id, question=question_id)
if answer.question.is_locked:
raise PermissionDenied
if not answer.has_voted(request):
vote = AnswerVote(answer=answer)
if 'helpful' in request.REQUEST:
vote.helpful = True
AnswerMarkedHelpfulAction(answer.creator).save()
message = _('Glad to hear it!')
else:
AnswerMarkedNotHelpfulAction(answer.creator).save()
message = _('Sorry to hear that.')
if request.user.is_authenticated():
vote.creator = request.user
else:
vote.anonymous_id = request.anonymous.anonymous_id
vote.save()
ua = request.META.get('HTTP_USER_AGENT')
if ua:
vote.add_metadata('ua', ua[:1000]) # 1000 max_length
statsd.incr('questions.votes.answer')
else:
message = _('You already voted on this reply.')
if request.is_ajax():
return HttpResponse(json.dumps({'message': message}))
return HttpResponseRedirect(answer.get_absolute_url())
示例7: api
def api(request):
try:
access = Access.objects.get(user=request.user)
except Access.DoesNotExist:
access = None
roles = request.amo_user.groups.all()
if roles:
messages.error(request, _('Users with roles cannot use the API.'))
elif not request.amo_user.read_dev_agreement:
messages.error(request, _('You must accept the terms of service.'))
elif request.method == 'POST':
if 'delete' in request.POST:
if access:
access.delete()
messages.success(request, _('API key deleted.'))
else:
if not access:
key = 'mkt:%s:%s' % (request.amo_user.pk,
request.amo_user.email)
access = Access.objects.create(key=key, user=request.user,
secret=generate())
else:
access.update(secret=generate())
messages.success(request, _('New API key generated.'))
return redirect(reverse('mkt.developers.apps.api'))
return jingo.render(request, 'developers/api.html',
{'consumer': access, 'profile': profile,
'roles': roles})
示例8: is_valid
def is_valid(self, fatal=True):
"""
Runs some overall archive checks.
fatal: if the archive is not valid and fatal is True, it will raise
an error, otherwise it will return False.
"""
try:
zip = zipfile.ZipFile(self.source, self.mode)
except (BadZipfile, IOError):
if fatal:
log.info('Error extracting', exc_info=True)
raise
return False
_info = zip.infolist()
for info in _info:
if '..' in info.filename or info.filename.startswith('/'):
log.error('Extraction error, Invalid archive: %s' %
self.source)
raise forms.ValidationError(_('Invalid archive.'))
if info.file_size > settings.FILE_UNZIP_SIZE_LIMIT:
log.error('Extraction error, file too big: %s, %s'
% (self.source, info.file_size))
raise forms.ValidationError(_('Invalid archive.'))
self.info = _info
self.zip = zip
return True
示例9: is_compatible
def is_compatible(self):
"""Returns tuple of compatibility and reasons why if not.
Server side conditions for determining compatibility are:
* The add-on is an extension (not a theme, app, etc.)
* Has not opted in to strict compatibility.
* Does not use binary_components in chrome.manifest.
Note: The lowest maxVersion compat check needs to be checked
separately.
Note: This does not take into account the client conditions.
"""
compat = True
reasons = []
if self.addon.type != amo.ADDON_EXTENSION:
compat = False
# TODO: We may want this. For now we think it may be confusing.
# reasons.append(_('Add-on is not an extension.'))
if self.files.filter(binary_components=True).exists():
compat = False
reasons.append(_("Add-on uses binary components."))
if self.files.filter(strict_compatibility=True).exists():
compat = False
reasons.append(_("Add-on has opted into strict compatibility " "checking."))
return (compat, reasons)
示例10: preload_submit
def preload_submit(request, addon_id, addon):
if request.method == "POST":
form = PreloadTestPlanForm(request.POST, request.FILES)
if form.is_valid():
# Save test plan file.
test_plan = request.FILES["test_plan"]
# Figure the type to save it as (cleaned as pdf/xls from the form).
filetype = mimetypes.guess_type(test_plan.name)[0]
if "pdf" in filetype:
filename = "test_plan_%s.pdf"
else:
filename = "test_plan_%s.xls"
# Timestamp.
filename = filename % str(time.time()).split(".")[0]
save_test_plan(request.FILES["test_plan"], filename, addon)
# Log test plan.
PreloadTestPlan.objects.filter(addon=addon).update(status=amo.STATUS_DISABLED)
PreloadTestPlan.objects.create(addon=addon, filename=filename)
messages.success(request, _("Application for preload successfully submitted."))
return redirect(addon.get_dev_url("versions"))
else:
messages.error(request, _("There was an error with the form."))
else:
form = PreloadTestPlanForm()
return render(request, "developers/apps/preload/submit.html", {"addon": addon, "form": form})
示例11: get_json_data
def get_json_data(self, fileorpath):
path = get_filepath(fileorpath)
if zipfile.is_zipfile(path):
zf = SafeUnzip(path)
zf.is_valid() # Raises forms.ValidationError if problems.
try:
data = zf.extract_path('manifest.webapp')
except KeyError:
raise forms.ValidationError(
_('The file "manifest.webapp" was not found at the root '
'of the packaged app archive.'))
else:
file_ = get_file(fileorpath)
data = file_.read()
file_.close()
try:
enc_guess = chardet.detect(data)
data = strip_bom(data)
decoded_data = data.decode(enc_guess['encoding'])
except (ValueError, UnicodeDecodeError) as exc:
msg = 'Error parsing webapp %r (encoding: %r %.2f%% sure): %s: %s'
log.error(msg % (fileorpath, enc_guess['encoding'],
enc_guess['confidence'] * 100.0,
exc.__class__.__name__, exc))
raise forms.ValidationError(
_('Could not decode the webapp manifest file.'))
try:
return json.loads(decoded_data)
except Exception:
raise forms.ValidationError(
_('The webapp manifest is not valid JSON.'))
示例12: sidebar
def sidebar(app):
"""Populates the sidebar with (categories, types)."""
from addons.models import Category
if app is None:
return [], []
# We muck with query to make order_by and extra_order_by play nice.
q = Category.objects.filter(application=app.id, weight__gte=0,
type=amo.ADDON_EXTENSION)
categories = order_by_translation(q, 'name')
categories.query.extra_order_by.insert(0, 'weight')
Type = collections.namedtuple('Type', 'id name url')
base = urlresolvers.reverse('home')
types = [Type(99, _('Collections'), base + 'collections/')]
shown_types = {
amo.ADDON_PERSONA: urlresolvers.reverse('browse.personas'),
amo.ADDON_DICT: urlresolvers.reverse('browse.language-tools'),
amo.ADDON_SEARCH: urlresolvers.reverse('browse.search-tools'),
amo.ADDON_THEME: urlresolvers.reverse('browse.themes'),
}
titles = dict(amo.ADDON_TYPES,
**{amo.ADDON_DICT: _('Dictionaries & Language Packs')})
for type_, url in shown_types.items():
if type_ in app.types:
types.append(Type(type_, titles[type_], url))
return categories, sorted(types, key=lambda x: x.name)
示例13: del_image_async
def del_image_async(request, image_id):
"""Delete an image given its object id."""
user = request.user
if not user.is_authenticated():
message = _('You are not logged in.')
return HttpResponseForbidden(
json.dumps({'status': 'error', 'message': message}))
try:
image = ImageAttachment.objects.get(pk=image_id)
except ImageAttachment.DoesNotExist:
message = _('The requested image could not be found.')
return HttpResponseNotFound(
json.dumps({'status': 'error', 'message': message}))
if not ((user == image.creator) or
(user.has_perm('upload.delete_imageattachment'))):
message = _('You do not have permission to do that.')
return HttpResponseForbidden(
json.dumps({'status': 'error', 'message': message}))
image.file.delete()
if image.thumbnail:
image.thumbnail.delete()
image.delete()
return HttpResponse(json.dumps({'status': 'success'}))
示例14: up_image_async
def up_image_async(request, model_name, object_pk):
"""Upload all images in request.FILES."""
# Verify the model agaist our white-list
if model_name not in ALLOWED_MODELS:
message = _('Model not allowed.')
return HttpResponseBadRequest(
json.dumps({'status': 'error', 'message': message}))
# Get the model
m = get_model(*model_name.split('.'))
# Then look up the object by pk
try:
obj = m.objects.get(pk=object_pk)
except ObjectDoesNotExist:
message = _('Object does not exist.')
return HttpResponseNotFound(
json.dumps({'status': 'error', 'message': message}))
try:
file_info = upload_imageattachment(request, obj)
except FileTooLargeError as e:
return HttpResponseBadRequest(
json.dumps({'status': 'error', 'message': e.args[0]}))
if isinstance(file_info, dict) and 'thumbnail_url' in file_info:
return HttpResponse(
json.dumps({'status': 'success', 'file': file_info}))
message = _('Invalid or no image received.')
return HttpResponseBadRequest(
json.dumps({'status': 'error', 'message': message,
'errors': file_info}))
示例15: ajax
def ajax(request):
"""Query for a user matching a given email."""
if "q" not in request.GET:
raise http.Http404()
data = {"status": 0, "message": ""}
email = request.GET.get("q", "").strip()
dev_only = request.GET.get("dev", "1")
try:
dev_only = int(dev_only)
except ValueError:
dev_only = 1
dev_only = dev_only and settings.MARKETPLACE
if not email:
data.update(message=_("An email address is required."))
return data
user = UserProfile.objects.filter(email=email)
if dev_only:
user = user.exclude(read_dev_agreement=None)
msg = _("A user with that email address does not exist.")
msg_dev = _(
"A user with that email address does not exist, or the user " "has not yet accepted the developer agreement."
)
if user:
data.update(status=1, id=user[0].id, name=user[0].name)
else:
data["message"] = msg_dev if dev_only else msg
return escape_all(data)