Permalink
Browse files

Fixed #4040 -- Changed uses of has_key() to "in". Slight performance

improvement and forward-compatible with future Python releases. Patch from Gary
Wilson.


git-svn-id: http://code.djangoproject.com/svn/django/trunk@5091 bcc190cf-cafb-0310-a4f2-bffc1f526a37
  • Loading branch information...
1 parent 6c02565 commit 439cb4047fb583d08149f28e2ce66a8edfe0efa7 @malcolmt malcolmt committed Apr 26, 2007
Showing with 112 additions and 92 deletions.
  1. +1 −1 django/bin/profiling/gather_profile_stats.py
  2. +1 −1 django/contrib/admin/templatetags/admin_modify.py
  3. +3 −3 django/contrib/admin/views/auth.py
  4. +5 −5 django/contrib/admin/views/decorators.py
  5. +19 −19 django/contrib/admin/views/main.py
  6. +1 −1 django/contrib/comments/templatetags/comments.py
  7. +6 −6 django/contrib/comments/views/comments.py
  8. +1 −1 django/contrib/sitemaps/views.py
  9. +1 −1 django/core/cache/backends/simple.py
  10. +2 −2 django/core/handlers/modpython.py
  11. +1 −1 django/core/handlers/wsgi.py
  12. +3 −3 django/core/management.py
  13. +6 −6 django/core/servers/basehttp.py
  14. +3 −3 django/core/validators.py
  15. +1 −1 django/db/backends/mysql_old/base.py
  16. +1 −1 django/db/backends/postgresql/base.py
  17. +1 −1 django/db/backends/util.py
  18. +1 −1 django/db/models/fields/__init__.py
  19. +1 −1 django/db/models/fields/generic.py
  20. +2 −2 django/db/models/fields/related.py
  21. +1 −1 django/db/models/loading.py
  22. +2 −2 django/db/models/options.py
  23. +6 −6 django/db/transaction.py
  24. +4 −4 django/http/__init__.py
  25. +1 −1 django/middleware/common.py
  26. +1 −1 django/newforms/forms.py
  27. +2 −2 django/newforms/widgets.py
  28. +1 −1 django/oldforms/__init__.py
  29. +1 −1 django/template/__init__.py
  30. +3 −3 django/template/context.py
  31. +4 −4 django/template/defaulttags.py
  32. +1 −1 django/utils/datastructures.py
  33. +1 −1 django/utils/functional.py
  34. +1 −1 django/utils/translation/trans_real.py
  35. +3 −3 django/views/i18n.py
  36. +2 −0 tests/regressiontests/dispatch/tests/test_saferef.py
  37. +18 −0 tests/regressiontests/httpwrappers/tests.py
@@ -22,7 +22,7 @@ def gather_stats(p):
else:
continue
print "Processing %s" % f
- if profiles.has_key(path):
+ if path in profiles:
profiles[path].add(prof)
else:
profiles[path] = prof
@@ -74,7 +74,7 @@ def __init__(self, bound_field_var):
self.bound_field_var = bound_field_var
def get_nodelist(cls, klass):
- if not cls.nodelists.has_key(klass):
+ if klass not in cls.nodelists:
try:
field_class_name = klass.__name__
template_name = "widget/%s.html" % class_name_to_underscored(field_class_name)
@@ -17,7 +17,7 @@ def user_add_stage(request):
if not errors:
new_user = manipulator.save(new_data)
msg = _('The %(name)s "%(obj)s" was added successfully.') % {'name': 'user', 'obj': new_user}
- if request.POST.has_key("_addanother"):
+ if "_addanother" in request.POST:
request.user.message_set.create(message=msg)
return HttpResponseRedirect(request.path)
else:
@@ -29,7 +29,7 @@ def user_add_stage(request):
return render_to_response('admin/auth/user/add_form.html', {
'title': _('Add user'),
'form': form,
- 'is_popup': request.REQUEST.has_key('_popup'),
+ 'is_popup': '_popup' in request.REQUEST,
'add': True,
'change': False,
'has_delete_permission': False,
@@ -63,7 +63,7 @@ def user_change_password(request, id):
return render_to_response('admin/auth/user/change_password.html', {
'title': _('Change password: %s') % escape(user.username),
'form': form,
- 'is_popup': request.REQUEST.has_key('_popup'),
+ 'is_popup': '_popup' in request.REQUEST,
'add': True,
'change': False,
'has_delete_permission': False,
@@ -12,7 +12,7 @@
def _display_login_form(request, error_message=''):
request.session.set_test_cookie()
- if request.POST and request.POST.has_key('post_data'):
+ if request.POST and 'post_data' in request.POST:
# User has failed login BUT has previously saved post data.
post_data = request.POST['post_data']
elif request.POST:
@@ -48,7 +48,7 @@ def staff_member_required(view_func):
def _checklogin(request, *args, **kwargs):
if request.user.is_authenticated() and request.user.is_staff:
# The user is valid. Continue to the admin page.
- if request.POST.has_key('post_data'):
+ if 'post_data' in request.POST:
# User must have re-authenticated through a different window
# or tab.
request.POST = _decode_post_data(request.POST['post_data'])
@@ -57,7 +57,7 @@ def _checklogin(request, *args, **kwargs):
assert hasattr(request, 'session'), "The Django admin requires session middleware to be installed. Edit your MIDDLEWARE_CLASSES setting to insert 'django.contrib.sessions.middleware.SessionMiddleware'."
# If this isn't already the login page, display it.
- if not request.POST.has_key(LOGIN_FORM_KEY):
+ if LOGIN_FORM_KEY not in request.POST:
if request.POST:
message = _("Please log in again, because your session has expired. Don't worry: Your submission has been saved.")
else:
@@ -90,9 +90,9 @@ def _checklogin(request, *args, **kwargs):
if user.is_active and user.is_staff:
login(request, user)
# TODO: set last_login with an event.
- if request.POST.has_key('post_data'):
+ if 'post_data' in request.POST:
post_data = _decode_post_data(request.POST['post_data'])
- if post_data and not post_data.has_key(LOGIN_FORM_KEY):
+ if post_data and LOGIN_FORM_KEY not in post_data:
# overwrite request.POST with the saved post_data, and continue
request.POST = post_data
request.user = user
@@ -257,17 +257,17 @@ def add_stage(request, app_label, model_name, show_delete=False, form_url='', po
msg = _('The %(name)s "%(obj)s" was added successfully.') % {'name': opts.verbose_name, 'obj': new_object}
# Here, we distinguish between different save types by checking for
# the presence of keys in request.POST.
- if request.POST.has_key("_continue"):
+ if "_continue" in request.POST:
request.user.message_set.create(message=msg + ' ' + _("You may edit it again below."))
- if request.POST.has_key("_popup"):
+ if "_popup" in request.POST:
post_url_continue += "?_popup=1"
return HttpResponseRedirect(post_url_continue % pk_value)
- if request.POST.has_key("_popup"):
+ if "_popup" in request.POST:
if type(pk_value) is str: # Quote if string, so JavaScript doesn't think it's a variable.
pk_value = '"%s"' % pk_value.replace('"', '\\"')
return HttpResponse('<script type="text/javascript">opener.dismissAddAnotherPopup(window, %s, "%s");</script>' % \
(pk_value, str(new_object).replace('"', '\\"')))
- elif request.POST.has_key("_addanother"):
+ elif "_addanother" in request.POST:
request.user.message_set.create(message=msg + ' ' + (_("You may add another %s below.") % opts.verbose_name))
return HttpResponseRedirect(request.path)
else:
@@ -288,7 +288,7 @@ def add_stage(request, app_label, model_name, show_delete=False, form_url='', po
c = template.RequestContext(request, {
'title': _('Add %s') % opts.verbose_name,
'form': form,
- 'is_popup': request.REQUEST.has_key('_popup'),
+ 'is_popup': '_popup' in request.REQUEST,
'show_delete': show_delete,
})
@@ -308,7 +308,7 @@ def change_stage(request, app_label, model_name, object_id):
if not request.user.has_perm(app_label + '.' + opts.get_change_permission()):
raise PermissionDenied
- if request.POST and request.POST.has_key("_saveasnew"):
+ if request.POST and "_saveasnew" in request.POST:
return add_stage(request, app_label, model_name, form_url='../../add/')
try:
@@ -343,16 +343,16 @@ def change_stage(request, app_label, model_name, object_id):
LogEntry.objects.log_action(request.user.id, ContentType.objects.get_for_model(model).id, pk_value, str(new_object), CHANGE, change_message)
msg = _('The %(name)s "%(obj)s" was changed successfully.') % {'name': opts.verbose_name, 'obj': new_object}
- if request.POST.has_key("_continue"):
+ if "_continue" in request.POST:
request.user.message_set.create(message=msg + ' ' + _("You may edit it again below."))
- if request.REQUEST.has_key('_popup'):
+ if '_popup' in request.REQUEST:
return HttpResponseRedirect(request.path + "?_popup=1")
else:
return HttpResponseRedirect(request.path)
- elif request.POST.has_key("_saveasnew"):
+ elif "_saveasnew" in request.POST:
request.user.message_set.create(message=_('The %(name)s "%(obj)s" was added successfully. You may edit it again below.') % {'name': opts.verbose_name, 'obj': new_object})
return HttpResponseRedirect("../%s/" % pk_value)
- elif request.POST.has_key("_addanother"):
+ elif "_addanother" in request.POST:
request.user.message_set.create(message=msg + ' ' + (_("You may add another %s below.") % opts.verbose_name))
return HttpResponseRedirect("../add/")
else:
@@ -392,7 +392,7 @@ def change_stage(request, app_label, model_name, object_id):
'form': form,
'object_id': object_id,
'original': manipulator.original_object,
- 'is_popup': request.REQUEST.has_key('_popup'),
+ 'is_popup': '_popup' in request.REQUEST,
})
return render_change_form(model, manipulator, c, change=True)
change_stage = staff_member_required(never_cache(change_stage))
@@ -558,12 +558,12 @@ def __init__(self, request, model):
self.page_num = int(request.GET.get(PAGE_VAR, 0))
except ValueError:
self.page_num = 0
- self.show_all = request.GET.has_key(ALL_VAR)
- self.is_popup = request.GET.has_key(IS_POPUP_VAR)
+ self.show_all = ALL_VAR in request.GET
+ self.is_popup = IS_POPUP_VAR in request.GET
self.params = dict(request.GET.items())
- if self.params.has_key(PAGE_VAR):
+ if PAGE_VAR in self.params:
del self.params[PAGE_VAR]
- if self.params.has_key(ERROR_FLAG):
+ if ERROR_FLAG in self.params:
del self.params[ERROR_FLAG]
self.order_field, self.order_type = self.get_ordering()
@@ -594,7 +594,7 @@ def get_query_string(self, new_params=None, remove=None):
if k.startswith(r):
del p[k]
for k, v in new_params.items():
- if p.has_key(k) and v is None:
+ if k in p and v is None:
del p[k]
elif v is not None:
p[k] = v
@@ -656,7 +656,7 @@ def get_ordering(self):
order_field, order_type = ordering[0][1:], 'desc'
else:
order_field, order_type = ordering[0], 'asc'
- if params.has_key(ORDER_VAR):
+ if ORDER_VAR in params:
try:
field_name = lookup_opts.admin.list_display[int(params[ORDER_VAR])]
try:
@@ -674,15 +674,15 @@ def get_ordering(self):
order_field = f.name
except (IndexError, ValueError):
pass # Invalid ordering specified. Just use the default.
- if params.has_key(ORDER_TYPE_VAR) and params[ORDER_TYPE_VAR] in ('asc', 'desc'):
+ if ORDER_TYPE_VAR in params and params[ORDER_TYPE_VAR] in ('asc', 'desc'):
order_type = params[ORDER_TYPE_VAR]
return order_field, order_type
def get_query_set(self):
qs = self.manager.get_query_set()
lookup_params = self.params.copy() # a dictionary of the query string
for i in (ALL_VAR, ORDER_VAR, ORDER_TYPE_VAR, SEARCH_VAR, IS_POPUP_VAR):
- if lookup_params.has_key(i):
+ if i in lookup_params:
del lookup_params[i]
# Apply lookup parameters from the query string.
@@ -116,7 +116,7 @@ def render(self, context):
comment_list = get_list_function(**kwargs).order_by(self.ordering + 'submit_date').select_related()
if not self.free:
- if context.has_key('user') and context['user'].is_authenticated():
+ if 'user' in context and context['user'].is_authenticated():
user_id = context['user'].id
context['user_can_moderate_comments'] = Comment.objects.user_is_moderator(context['user'])
else:
@@ -217,10 +217,10 @@ def post_comment(request):
errors = manipulator.get_validation_errors(new_data)
# If user gave correct username/password and wasn't already logged in, log them in
# so they don't have to enter a username/password again.
- if manipulator.get_user() and not manipulator.get_user().is_authenticated() and new_data.has_key('password') and manipulator.get_user().check_password(new_data['password']):
+ if manipulator.get_user() and not manipulator.get_user().is_authenticated() and 'password' in new_data and manipulator.get_user().check_password(new_data['password']):
from django.contrib.auth import login
login(request, manipulator.get_user())
- if errors or request.POST.has_key('preview'):
+ if errors or 'preview' in request.POST:
class CommentFormWrapper(oldforms.FormWrapper):
def __init__(self, manipulator, new_data, errors, rating_choices):
oldforms.FormWrapper.__init__(self, manipulator, new_data, errors)
@@ -244,7 +244,7 @@ def ratings(self):
'rating_range': rating_range,
'rating_choices': rating_choices,
}, context_instance=RequestContext(request))
- elif request.POST.has_key('post'):
+ elif 'post' in request.POST:
# If the IP is banned, mail the admins, do NOT save the comment, and
# serve up the "Thanks for posting" page as if the comment WAS posted.
if request.META['REMOTE_ADDR'] in settings.BANNED_IPS:
@@ -298,7 +298,7 @@ def post_free_comment(request):
new_data['is_public'] = IS_PUBLIC in option_list
manipulator = PublicFreeCommentManipulator()
errors = manipulator.get_validation_errors(new_data)
- if errors or request.POST.has_key('preview'):
+ if errors or 'preview' in request.POST:
comment = errors and '' or manipulator.get_comment(new_data)
return render_to_response('comments/free_preview.html', {
'comment': comment,
@@ -307,7 +307,7 @@ def post_free_comment(request):
'target': target,
'hash': security_hash,
}, context_instance=RequestContext(request))
- elif request.POST.has_key('post'):
+ elif 'post' in request.POST:
# If the IP is banned, mail the admins, do NOT save the comment, and
# serve up the "Thanks for posting" page as if the comment WAS posted.
if request.META['REMOTE_ADDR'] in settings.BANNED_IPS:
@@ -330,7 +330,7 @@ def comment_was_posted(request):
The object the comment was posted on
"""
obj = None
- if request.GET.has_key('c'):
+ if 'c' in request.GET:
content_type_id, object_id = request.GET['c'].split(':')
try:
content_type = ContentType.objects.get(pk=content_type_id)
@@ -16,7 +16,7 @@ def index(request, sitemaps):
def sitemap(request, sitemaps, section=None):
maps, urls = [], []
if section is not None:
- if not sitemaps.has_key(section):
+ if section not in sitemaps:
raise Http404("No sitemap available for section: %r" % section)
maps.append(sitemaps[section])
else:
@@ -52,7 +52,7 @@ def delete(self, key):
pass
def has_key(self, key):
- return self._cache.has_key(key)
+ return key in self._cache
def _cull(self):
if self._cull_frequency == 0:
@@ -42,11 +42,11 @@ def get_full_path(self):
def is_secure(self):
# Note: modpython 3.2.10+ has req.is_https(), but we need to support previous versions
- return self._req.subprocess_env.has_key('HTTPS') and self._req.subprocess_env['HTTPS'] == 'on'
+ return 'HTTPS' in self._req.subprocess_env and self._req.subprocess_env['HTTPS'] == 'on'
def _load_post_and_files(self):
"Populates self._post and self._files"
- if self._req.headers_in.has_key('content-type') and self._req.headers_in['content-type'].startswith('multipart'):
+ if 'content-type' in self._req.headers_in and self._req.headers_in['content-type'].startswith('multipart'):
self._post, self._files = http.parse_file_upload(self._req.headers_in, self.raw_post_data)
else:
self._post, self._files = http.QueryDict(self.raw_post_data), datastructures.MultiValueDict()
@@ -103,7 +103,7 @@ def get_full_path(self):
return '%s%s' % (self.path, self.environ.get('QUERY_STRING', '') and ('?' + self.environ.get('QUERY_STRING', '')) or '')
def is_secure(self):
- return self.environ.has_key('HTTPS') and self.environ['HTTPS'] == 'on'
+ return 'HTTPS' in self.environ and self.environ['HTTPS'] == 'on'
def _load_post_and_files(self):
# Populates self._post and self._files
@@ -314,7 +314,7 @@ def get_sql_delete(app):
# Drop the table now
output.append('%s %s;' % (style.SQL_KEYWORD('DROP TABLE'),
style.SQL_TABLE(backend.quote_name(model._meta.db_table))))
- if backend.supports_constraints and references_to_delete.has_key(model):
+ if backend.supports_constraints and model in references_to_delete:
for rel_class, f in references_to_delete[model]:
table = rel_class._meta.db_table
col = f.column
@@ -843,7 +843,7 @@ def inspectdb():
att_name += '_field'
comment_notes.append('Field renamed because it was a Python reserved word.')
- if relations.has_key(i):
+ if i in relations:
rel_to = relations[i][1] == table_name and "'self'" or table2model(relations[i][1])
field_type = 'ForeignKey(%s' % rel_to
if att_name.endswith('_id'):
@@ -1550,7 +1550,7 @@ def execute_from_command_line(action_mapping=DEFAULT_ACTION_MAPPING, argv=None):
action = args[0]
except IndexError:
parser.print_usage_and_exit()
- if not action_mapping.has_key(action):
+ if action not in action_mapping:
print_error("Your action, %r, was invalid." % action, argv[0])
# Switch to English, because django-admin.py creates database content
@@ -208,15 +208,15 @@ def guess_scheme(environ):
else:
return 'http'
-_hoppish = {
+_hop_headers = {
'connection':1, 'keep-alive':1, 'proxy-authenticate':1,
'proxy-authorization':1, 'te':1, 'trailers':1, 'transfer-encoding':1,
'upgrade':1
-}.has_key
+}
def is_hop_by_hop(header_name):
"""Return true if 'header_name' is an HTTP/1.1 "Hop-by-Hop" header"""
- return _hoppish(header_name.lower())
+ return header_name.lower() in _hop_headers
class ServerHandler(object):
"""Manage the invocation of a WSGI application"""
@@ -334,7 +334,7 @@ def cleanup_headers(self):
Subclasses can extend this to add other defaults.
"""
- if not self.headers.has_key('Content-Length'):
+ if 'Content-Length' not in self.headers:
self.set_content_length()
def start_response(self, status, headers,exc_info=None):
@@ -368,11 +368,11 @@ def send_preamble(self):
if self.origin_server:
if self.client_is_modern():
self._write('HTTP/%s %s\r\n' % (self.http_version,self.status))
- if not self.headers.has_key('Date'):
+ if 'Date' not in self.headers:
self._write(
'Date: %s\r\n' % time.asctime(time.gmtime(time.time()))
)
- if self.server_software and not self.headers.has_key('Server'):
+ if self.server_software and 'Server' not in self.headers:
self._write('Server: %s\r\n' % self.server_software)
else:
self._write('Status: %s\r\n' % self.status)
Oops, something went wrong.

0 comments on commit 439cb40

Please sign in to comment.