diff options
| author | Magnus Hagander | 2018-12-15 10:05:34 +0000 |
|---|---|---|
| committer | Magnus Hagander | 2018-12-15 10:05:34 +0000 |
| commit | d3cbef33ecc739a7fea78ab21ea097178c204f91 (patch) | |
| tree | b56248a4d520e13197491b53eb0b3feec2d0e3b6 | |
| parent | f01500dcf70022e2d23b91c147a6254ac8c4e3b2 (diff) | |
Replace usage of has_key()
It has been deprecated, and instead we should use "in" and "not in", so
make that change across the board.
33 files changed, 121 insertions, 118 deletions
diff --git a/postgresqleu/accounting/forms.py b/postgresqleu/accounting/forms.py index 35764dbf..0411c1e6 100644 --- a/postgresqleu/accounting/forms.py +++ b/postgresqleu/accounting/forms.py @@ -47,7 +47,7 @@ class JournalItemForm(forms.ModelForm): def clean(self): if not self.cleaned_data: return - if not self.cleaned_data.has_key('debit') or not self.cleaned_data.has_key('credit'): + if 'debit' not in self.cleaned_data or 'credit' not in self.cleaned_data: # This means there is an error elsewhere! return self.cleaned_data if self.cleaned_data['debit'] and self.cleaned_data['credit']: @@ -57,7 +57,7 @@ class JournalItemForm(forms.ModelForm): return self.cleaned_data def clean_object(self): - if self.cleaned_data.has_key('account'): + if 'account' in self.cleaned_data: if self.cleaned_data['account'].objectrequirement == 1: # object is required if not self.cleaned_data['object']: @@ -85,8 +85,8 @@ class JournalItemForm(forms.ModelForm): return 0 if self.cleaned_data['DELETE']: return 0 - debit = self.cleaned_data.has_key('debit') and self.cleaned_data['debit'] or 0 - credit = self.cleaned_data.has_key('credit') and self.cleaned_data['credit'] or 0 + debit = self.cleaned_data.get('debit', 0) or 0 + credit = self.cleaned_data.get('credit', 0) or 0 return debit - credit diff --git a/postgresqleu/accounting/views.py b/postgresqleu/accounting/views.py index f9338b0d..023d2848 100644 --- a/postgresqleu/accounting/views.py +++ b/postgresqleu/accounting/views.py @@ -27,12 +27,12 @@ def _setup_search(request, term): if term: request.session['searchterm'] = term else: - if request.session.has_key('searchterm'): + if 'searchterm' in request.session: del request.session['searchterm'] def _perform_search(request, year): - if request.session.has_key('searchterm'): + if 'searchterm' in request.session: searchterm = request.session['searchterm'] return (searchterm, list( @@ -67,14 +67,14 @@ class EntryPaginator(Paginator): @user_passes_test_or_error(lambda u: u.has_module_perms('accounting')) def year(request, year): year = get_object_or_404(Year, year=int(year)) - if request.GET.has_key('search'): + if 'search' in request.GET: _setup_search(request, request.GET['search']) return HttpResponseRedirect('/accounting/%s/' % year.year) (searchterm, entries) = _perform_search(request, year) paginator = EntryPaginator(entries) - currpage = request.GET.has_key('p') and int(request.GET['p']) or 1 + currpage = int(request.GET.get('p', 1)) return render(request, 'accounting/main.html', { 'entries': paginator.page(currpage), @@ -122,14 +122,14 @@ def new(request, year): def entry(request, entryid): entry = get_object_or_404(JournalEntry, pk=entryid) - if request.GET.has_key('search'): + if 'search' in request.GET: _setup_search(request, request.GET['search']) return HttpResponseRedirect('/accounting/e/%s/' % entryid) (searchterm, entries) = _perform_search(request, entry.year) paginator = EntryPaginator(entries) - currpage = request.GET.has_key('p') and int(request.GET['p']) or 1 + currpage = int(request.GET.get('p', 1)) extra = max(2, 6 - entry.journalitem_set.count()) inlineformset = inlineformset_factory(JournalEntry, JournalItem, JournalItemForm, JournalItemFormset, can_delete=True, extra=extra) @@ -331,7 +331,7 @@ SELECT ac.name AS acname, ag.name AS agname, anum, a.name, yearresult = curs.fetchall()[0][0] if request.method == 'POST': - if not request.POST.has_key('confirm') or not request.POST['confirm']: + if not request.POST.get('confirm', None): messages.warning(request, "You must check the box for confirming!") elif not request.POST['resultaccount']: messages.warning(request, "You must pick which account to post the results to!") @@ -385,7 +385,7 @@ def report(request, year, reporttype): else: year = get_object_or_404(Year, year=year) - if request.GET.has_key('obj') and request.GET['obj']: + if request.GET.get('obj', None): object = get_object_or_404(Object, pk=request.GET['obj']) objstr = "AND ji.object_id=%s" % object.id else: @@ -404,13 +404,13 @@ def report(request, year, reporttype): if year and year.isopen: messages.info(request, "This year is still open!") - if request.GET.has_key('acc') and request.GET['acc']: + if request.GET.get('acc', None): account = get_object_or_404(Account, num=request.GET['acc']) else: account = None if year: - if request.GET.has_key('ed') and request.GET['ed'] and request.GET['ed'] != 'undefined': + if request.GET.get('ed', None) and request.GET['ed'] != 'undefined': enddate = datetime.strptime(request.GET['ed'], '%Y-%m-%d').date() if year and enddate.year != year.year: enddate = date(year.year, 12, 31) @@ -420,7 +420,7 @@ def report(request, year, reporttype): # Yes, this is ugly indeed :) enddate = date(9999, 12, 31) - if request.GET.has_key('io') and request.GET['io'] == '1': + if request.GET.get('io', 0) == '1': includeopen = True else: includeopen = False @@ -447,10 +447,10 @@ def report(request, year, reporttype): 'enddate': enddate, 'includeopen': includeopen, } - if request.GET.has_key('obj') and request.GET['obj']: + if request.GET.get('obj', None): sql += " AND o.id=%(objectid)s" params['objectid'] = int(request.GET['obj']) - if request.GET.has_key('acc') and request.GET['acc']: + if request.GET.get('acc', None): sql += " AND a.num=%(account)s" params['account'] = int(request.GET['acc']) sql += " WINDOW w1 AS (PARTITION BY a.num) ORDER BY a.num, e.date, e.seq" diff --git a/postgresqleu/adyen/management/commands/process_adyen_reports.py b/postgresqleu/adyen/management/commands/process_adyen_reports.py index 2c74281d..d256254a 100644 --- a/postgresqleu/adyen/management/commands/process_adyen_reports.py +++ b/postgresqleu/adyen/management/commands/process_adyen_reports.py @@ -146,7 +146,7 @@ class Command(BaseCommand): t = "Balancetransfer2" lamount = Decimal(l['Net Credit (NC)'] or 0) - Decimal(l['Net Debit (NC)'] or 0) - if types.has_key(t): + if t in types: types[t] += lamount else: types[t] = lamount diff --git a/postgresqleu/auth.py b/postgresqleu/auth.py index a84214c7..b060d282 100644 --- a/postgresqleu/auth.py +++ b/postgresqleu/auth.py @@ -49,7 +49,7 @@ class AuthBackend(ModelBackend): # Handle login requests by sending them off to the main site def login(request): - if request.GET.has_key('next'): + if 'next' in request.GET: # Put together an url-encoded dict of parameters we're getting back, # including a small nonce at the beginning to make sure it doesn't # encrypt the same way every time. @@ -80,13 +80,13 @@ def logout(request): # Receive an authentication response from the main website and try # to log the user in. def auth_receive(request): - if request.GET.has_key('s') and request.GET['s'] == "logout": + if request.GET.get('s', None) == "logout": # This was a logout request return HttpResponseRedirect('/') - if not request.GET.has_key('i'): + if 'i' not in request.GET: return HttpResponse("Missing IV in url!", status=400) - if not request.GET.has_key('d'): + if 'd' not in request.GET: return HttpResponse("Missing data in url!", status=400) # Set up an AES object and decrypt the data we received @@ -156,7 +156,7 @@ We apologize for the inconvenience. # Finally, check of we have a data package that tells us where to # redirect the user. - if data.has_key('d'): + if 'd' in data: (ivs, datas) = data['d'][0].split('$') decryptor = AES.new(SHA.new(settings.SECRET_KEY).digest()[:16], AES.MODE_CBC, @@ -166,7 +166,7 @@ We apologize for the inconvenience. rdata = urlparse.parse_qs(s, strict_parsing=True) except ValueError: return HttpResponse("Invalid encrypted data received.", status=400) - if rdata.has_key('r'): + if 'r' in rdata: # Redirect address return HttpResponseRedirect(rdata['r'][0]) # No redirect specified, see if we have it in our settings diff --git a/postgresqleu/confreg/admin.py b/postgresqleu/confreg/admin.py index 4d02116b..e91084e7 100644 --- a/postgresqleu/confreg/admin.py +++ b/postgresqleu/confreg/admin.py @@ -558,11 +558,11 @@ class DiscountCodeAdminForm(SelectableWidgetAdminFormMixin, ConcurrentProtectedM def clean(self): cleaned_data = super(DiscountCodeAdminForm, self).clean() - if cleaned_data.has_key('discountamount') and cleaned_data.has_key('discountpercentage'): + if 'discountamount' in cleaned_data and 'discountpercentage' in cleaned_data: if cleaned_data['discountamount'] > 0 and cleaned_data['discountpercentage'] > 0: raise ValidationError('Cannot specify both discount amount and discount percentage at the same time!') - if cleaned_data.has_key('discountamount') and cleaned_data.has_key('regonly'): + if 'discountamount' in cleaned_data and 'regonly' in cleaned_data: if cleaned_data['discountamount'] > 0 and cleaned_data['regonly']: raise ValidationError('Regonly field can only be set for percentage discounts!') diff --git a/postgresqleu/confreg/backendviews.py b/postgresqleu/confreg/backendviews.py index 56037f63..e20e8e71 100644 --- a/postgresqleu/confreg/backendviews.py +++ b/postgresqleu/confreg/backendviews.py @@ -639,7 +639,7 @@ def twitter_integration(request, urlname): 'helplink': 'integrations#twitter', }) elif request.POST.get('pincode', ''): - if not (request.session.has_key('ownerkey') and request.session.has_key('ownersecret')): + if not ('ownerkey' in request.session and 'ownersecret' in request.session): messages.error(request, 'Missing data in session, cannot continue') return HttpResponseRedirect('.') try: diff --git a/postgresqleu/confreg/forms.py b/postgresqleu/confreg/forms.py index 4650cdf0..f9d4f09d 100644 --- a/postgresqleu/confreg/forms.py +++ b/postgresqleu/confreg/forms.py @@ -198,14 +198,14 @@ class ConferenceRegistrationForm(forms.ModelForm): # own, they will not be present in cleaned_data. cleaned_data = super(ConferenceRegistrationForm, self).clean() - if cleaned_data.has_key('vouchercode') and cleaned_data['vouchercode']: + if cleaned_data.get('vouchercode', None): # We know it's there, and that it exists - but is it for the # correct type of registration? errs = [] try: v = PrepaidVoucher.objects.get(vouchervalue=cleaned_data['vouchercode'], conference=self.instance.conference) - if not cleaned_data.has_key('regtype'): + if 'regtype' not in cleaned_data: errs.append('Invalid registration type specified') raise ValidationError('An invalid registration type has been selected') if v.batch.regtype != cleaned_data['regtype']: @@ -223,11 +223,11 @@ class ConferenceRegistrationForm(forms.ModelForm): if errs: self._errors['vouchercode'] = ErrorList(errs) - if cleaned_data.has_key('regtype') and cleaned_data['regtype']: + if cleaned_data.get('regtype', None): if cleaned_data['regtype'].requires_option.exists(): regtype = cleaned_data['regtype'] found = False - if cleaned_data.has_key('additionaloptions') and cleaned_data['additionaloptions']: + if cleaned_data.get('additionaloptions', None): for x in regtype.requires_option.all(): if x in cleaned_data['additionaloptions']: found = True @@ -235,7 +235,7 @@ class ConferenceRegistrationForm(forms.ModelForm): if not found: self._errors['regtype'] = 'Registration type "%s" requires at least one of the following additional options to be picked: %s' % (regtype, ", ".join([x.name for x in regtype.requires_option.all()])) - if cleaned_data.has_key('additionaloptions') and cleaned_data['additionaloptions'] and cleaned_data.has_key('regtype'): + if cleaned_data.get('additionaloptions', None) and 'regtype' in cleaned_data: regtype = cleaned_data['regtype'] errs = [] for ao in cleaned_data['additionaloptions']: @@ -536,7 +536,7 @@ class SessionSlidesFileForm(forms.Form): license = forms.BooleanField(label='License', required=False, help_text='I confirm that this this file may be redistributed by the conference website') def clean_f(self): - if not self.cleaned_data.has_key('f') or not self.cleaned_data['f']: + if not self.cleaned_data.get('f', None): return f = self.cleaned_data['f'] mtype = magicdb.buffer(f.read()) @@ -566,9 +566,9 @@ class PrepaidCreateForm(forms.Form): super(PrepaidCreateForm, self).__init__(*args, **kwargs) self.fields['regtype'].queryset = RegistrationType.objects.filter(conference=conference) self.fields['buyer'].label_from_instance = lambda x: u'{0} {1} <{2}> ({3})'.format(x.first_name, x.last_name, x.email, x.username) - if not (self.data.has_key('regtype') and - self.data.has_key('count') and - self.data.get('regtype') and + if not ('regtype' in self.data and + 'count' in self.data and + 'regtype' in self.data and self.data.get('count')): del self.fields['confirm'] @@ -585,7 +585,7 @@ class EmailSendForm(forms.Form): super(EmailSendForm, self).__init__(*args, **kwargs) self.fields['ids'].widget.attrs['readonly'] = True readytogo = False - if self.data and self.data.has_key('ids') and self.data.has_key('sender') and self.data.has_key('subject') and self.data.has_key('text'): + if self.data and 'ids' in self.data and 'sender' in self.data and 'subject' in self.data and 'text' in self.data: if len(self.data['ids']) > 1 and len(self.data['sender']) > 5 and len(self.data['subject']) > 10 and len(self.data['text']) > 50: readytogo = True if not readytogo: @@ -602,7 +602,7 @@ class EmailSessionForm(forms.Form): def __init__(self, *args, **kwargs): super(EmailSessionForm, self).__init__(*args, **kwargs) readytogo = False - if self.data and self.data.has_key('sender') and self.data.has_key('subject') and self.data.has_key('text'): + if self.data and 'sender' in self.data and 'subject' in self.data and 'text' in self.data: if len(self.data['sender']) > 5 and len(self.data['subject']) > 10 and len(self.data['text']) > 50: readytogo = True if not readytogo: @@ -730,7 +730,7 @@ class TransferRegForm(forms.Form): super(TransferRegForm, self).__init__(*args, **kwargs) self.fields['transfer_from'].queryset = ConferenceRegistration.objects.filter(conference=conference, payconfirmedat__isnull=False) self.fields['transfer_to'].queryset = ConferenceRegistration.objects.filter(conference=conference, payconfirmedat__isnull=True) - if not (self.data.has_key('transfer_from') and self.data.has_key('transfer_to')): + if not ('transfer_from' in self.data and 'transfer_to' in self.data): del self.fields['confirm'] def remove_confirm(self): diff --git a/postgresqleu/confreg/jinjabadge.py b/postgresqleu/confreg/jinjabadge.py index bb6930c9..c5cb091c 100755 --- a/postgresqleu/confreg/jinjabadge.py +++ b/postgresqleu/confreg/jinjabadge.py @@ -64,7 +64,7 @@ class JinjaBadge(Flowable): return self.height - getmm(o, 'y') - getmm(o, 'height') def draw_box(self, o): - if o.has_key('fill'): + if 'fill' in o: self.canv.setFillColor(get_color(o['fill'])) fill = 1 else: diff --git a/postgresqleu/confreg/lookups.py b/postgresqleu/confreg/lookups.py index 4e36be8a..b6cecb3a 100644 --- a/postgresqleu/confreg/lookups.py +++ b/postgresqleu/confreg/lookups.py @@ -17,7 +17,7 @@ class RegistrationLookup(ModelLookup): def get_query(self, request, term): q = super(RegistrationLookup, self).get_query(request, term) - if request.GET.has_key('conference'): + if 'conference' in request.GET: return q.filter(conference_id=request.GET['conference'], payconfirmedat__isnull=False) else: # Don't return anything if parameter not present diff --git a/postgresqleu/confreg/pdfschedule.py b/postgresqleu/confreg/pdfschedule.py index 2345cc69..8d05b87f 100644 --- a/postgresqleu/confreg/pdfschedule.py +++ b/postgresqleu/confreg/pdfschedule.py @@ -336,25 +336,25 @@ def pdfschedule(request, confname): if request.method == "POST": form = PdfScheduleForm(conference, data=request.POST) if form.is_valid(): - if form.cleaned_data.has_key('room') and form.cleaned_data['room']: + if form.cleaned_data.get('room', None): return build_linear_pdf_schedule(conference, form.cleaned_data['room'], form.cleaned_data['tracks'], - form.cleaned_data.has_key('day') and form.cleaned_data['day'], - form.cleaned_data.has_key('colored') and form.cleaned_data['colored'], - form.cleaned_data.has_key('pagesize') and form.cleaned_data['pagesize'], - form.cleaned_data.has_key('orientation') and form.cleaned_data['orientation'], - form.cleaned_data.has_key('titledatefmt') and form.cleaned_data['titledatefmt'], + form.cleaned_data.get('day', None), + form.cleaned_data.get('colored', None), + form.cleaned_data.get('pagesize', None), + form.cleaned_data.get('orientation', None), + form.cleaned_data.get('titledatefmt', None), ) else: return build_complete_pdf_schedule(conference, form.cleaned_data['tracks'], - form.cleaned_data.has_key('day') and form.cleaned_data['day'], - form.cleaned_data.has_key('colored') and form.cleaned_data['colored'], - form.cleaned_data.has_key('pagesize') and form.cleaned_data['pagesize'], - form.cleaned_data.has_key('orientation') and form.cleaned_data['orientation'], - form.cleaned_data.has_key('pagesperday') and form.cleaned_data['pagesperday'], - form.cleaned_data.has_key('titledatefmt') and form.cleaned_data['titledatefmt'], + form.cleaned_data.get('day', None), + form.cleaned_data.get('colored', None), + form.cleaned_data.get('pagesize', None), + form.cleaned_data.get('orientation', None), + form.cleaned_data.get('pagesperday', None), + form.cleaned_data.get('titledatefmt', None), ) # Fall through and render the form again if it's not valid diff --git a/postgresqleu/confreg/regtypes.py b/postgresqleu/confreg/regtypes.py index 907fa162..e8cfa4d0 100644 --- a/postgresqleu/confreg/regtypes.py +++ b/postgresqleu/confreg/regtypes.py @@ -77,16 +77,16 @@ special_reg_types = [(k, v['name']) for k, v in _specialregtypes.items()] def validate_special_reg_type(regtypename, reg): - if not _specialregtypes.has_key(regtypename): + if regtypename not in _specialregtypes: raise ValidationError('Invalid registration type record. Internal error.') _specialregtypes[regtypename]['func'](reg) def confirm_special_reg_type(regtypename, reg): - if not _specialregtypes.has_key(regtypename): + if regtypename not in _specialregtypes: return - if _specialregtypes[regtypename].has_key('confirmfunc'): + if 'confirmfunc' in _specialregtypes[regtypename]: return _specialregtypes[regtypename]['confirmfunc'](reg) else: return None diff --git a/postgresqleu/confreg/reports.py b/postgresqleu/confreg/reports.py index 9277c3af..08b2b61a 100644 --- a/postgresqleu/confreg/reports.py +++ b/postgresqleu/confreg/reports.py @@ -63,7 +63,7 @@ class ReportFilter(object): vals = POST.getlist("adv_%s" % self.id, None) return Q(**{"%s__in" % self.id: vals}) else: - if POST.has_key('adv_%s_filter' % self.id) and POST['adv_%s_filter' % self.id]: + if POST.get('adv_%s_filter' % self.id, None): # Limit by value v = POST['adv_%s_filter' % self.id] if v.startswith('>'): @@ -225,15 +225,16 @@ def build_attendee_report(conference, POST): title = POST['title'] format = POST['format'] orientation = POST['orientation'] - borders = POST.has_key('border') - pagebreaks = POST.has_key('pagebreaks') + borders = 'border' in POST + pagebreaks = 'pagebreaks' in POST fields = POST.getlist('fields') extracols = filter(None, map(lambda x: x.strip(), POST['additionalcols'].split(','))) # Build the filters q = Q(conference=conference) for f in attendee_report_filters(conference): - if POST.has_key("adv_%s_on" % f.id): + k = "adv_%s_on" % f.id + if k in POST: # This filter is checked q = q & f.build_Q(POST) diff --git a/postgresqleu/confreg/views.py b/postgresqleu/confreg/views.py index 9569acd6..fd5b8670 100644 --- a/postgresqleu/confreg/views.py +++ b/postgresqleu/confreg/views.py @@ -1174,7 +1174,7 @@ def speakerprofile(request, confurlname=None): form = SpeakerProfileForm(data=request.POST, files=request.FILES, instance=speaker) if form.is_valid(): - if request.FILES.has_key('photo'): + if 'photo' in request.FILES: raise Exception("Deal with the file!") form.save() return HttpResponseRedirect('.') @@ -1437,7 +1437,7 @@ def callforpapers_confirm(request, confname, sessionid): }) if request.method == 'POST': - if request.POST.has_key('is_confirmed') and request.POST['is_confirmed'] == '1': + if request.POST.get('is_confirmed', 0) == '1': session.status = 1 session.save() # We can generate the email for this right away, so let's do that @@ -1662,7 +1662,7 @@ def waitlist_signup(request, confname): # CSRF ensures that this post comes from us. if request.POST['submit'] != 'Sign up on waitlist': raise Exception("Invalid post button") - if not request.POST.has_key('confirm') or request.POST['confirm'] != '1': + if request.POST.get('confirm', 0) != '1': messages.warning(request, "You must check the box to confirm signing up on the waitlist") return HttpResponseRedirect("../confirm/") @@ -1696,7 +1696,7 @@ def waitlist_cancel(request, confname): # CSRF ensures that this post comes from us. if request.POST['submit'] != 'Cancel waitlist': raise Exception("Invalid post button") - if not request.POST.has_key('confirm') or request.POST['confirm'] != '1': + if request.POST.get('confirm', 0) != '1': messages.warning(request, "You must check the box to confirm canceling your position on the waitlist.") return HttpResponseRedirect("../confirm/") @@ -1878,7 +1878,7 @@ def createvouchers(request, confname): batch=batch) v.save() - if form.data.has_key('invoice') and form.data['invoice']: + if form.data.get('invoice', None): invoice = Invoice(recipient_user=buyer, recipient_email=buyer.email, recipient_name=buyername, @@ -2164,7 +2164,7 @@ def talkvote(request, confname): curs = connection.cursor() order = "" - if request.GET.has_key("sort"): + if 'sort' in request.GET: if request.GET["sort"] == "avg": order = "avg DESC NULLS LAST," elif request.GET["sort"] == "speakers": @@ -2318,7 +2318,7 @@ def createschedule(request, confname): raise PermissionDenied('You are not an administrator or talk voter for this conference!') if request.method == "POST": - if request.POST.has_key('get'): + if 'get' in request.POST: # Get the current list of tentatively scheduled talks s = {} for sess in conference.conferencesession_set.all(): @@ -2439,7 +2439,7 @@ def publishschedule(request, confname): if dirty: s.save() - if request.GET.has_key('doit') and request.GET['doit'] == '1': + if request.GET.get('doit', 0) == '1': transaction.commit() return render(request, 'confreg/schedule_publish.html', { 'done': 1, @@ -2485,10 +2485,10 @@ def simple_report(request, confname): if "__" in request.GET['report']: raise Http404("Invalid character in report name") - if not simple_reports.has_key(request.GET['report']): + if not request.GET['report'] in simple_reports: raise Http404("Report not found") - if conference.personal_data_purged and simple_reports.has_key('{0}__anon'.format(request.GET['report'])): + if conference.personal_data_purged and '{0}__anon'.format(request.GET['report']) in simple_reports: query = simple_reports['{0}__anon'.format(request.GET['report'])] else: query = simple_reports[request.GET['report']] @@ -2978,7 +2978,7 @@ def session_notify_queue(request, urlname): notifysessions = ConferenceSession.objects.filter(conference=conference).exclude(status=F('lastnotifiedstatus')) - if request.method == 'POST' and request.POST.has_key('confirm_sending') and request.POST['confirm_sending'] == '1': + if request.method == 'POST' and request.POST.get('confirm_sending', 0) == '1': # Ok, it would appear we should actually send them... num = 0 for s in notifysessions: @@ -3360,7 +3360,7 @@ def admin_email_session(request, sessionids): else: return HttpResponseRedirect('/admin/confreg/conferencesession/%s/' % sessionids) else: - form = EmailSessionForm(initial={'sender': sessions[0].conference.contactaddr, 'returnurl': request.GET.has_key('orig') and request.GET['orig'] or ''}) + form = EmailSessionForm(initial={'sender': sessions[0].conference.contactaddr, 'returnurl': request.GET.get('orig', '')}) return render(request, 'confreg/admin_email.html', { 'form': form, diff --git a/postgresqleu/confsponsor/benefitclasses/imageupload.py b/postgresqleu/confsponsor/benefitclasses/imageupload.py index cd34c302..f465a3af 100644 --- a/postgresqleu/confsponsor/benefitclasses/imageupload.py +++ b/postgresqleu/confsponsor/benefitclasses/imageupload.py @@ -21,7 +21,7 @@ class ImageUploadForm(BaseBenefitForm): declined = self.cleaned_data.get('decline', False) if not declined: if not self.cleaned_data.get('image', None): - if not self._errors.has_key('image'): + if 'image' not in self._errors: # Unless there is an error already flagged in the clean_image method self._errors['image'] = self.error_class(['This field is required']) return self.cleaned_data diff --git a/postgresqleu/confsponsor/benefitclasses/providetext.py b/postgresqleu/confsponsor/benefitclasses/providetext.py index 04a00a11..c0855083 100644 --- a/postgresqleu/confsponsor/benefitclasses/providetext.py +++ b/postgresqleu/confsponsor/benefitclasses/providetext.py @@ -13,7 +13,7 @@ class ProvideTextForm(BaseBenefitForm): if not declined: # If not declined, we will require the text if not self.cleaned_data.get('text', None): - if not self._errors.has_key('text'): + if 'text' not in self._errors: self._errors['text'] = self.error_class(['This field is required']) return self.cleaned_data diff --git a/postgresqleu/confsponsor/forms.py b/postgresqleu/confsponsor/forms.py index 3666b07e..5c0fbed1 100644 --- a/postgresqleu/confsponsor/forms.py +++ b/postgresqleu/confsponsor/forms.py @@ -123,7 +123,7 @@ class PurchaseVouchersForm(forms.Form): self.conference = conference super(PurchaseVouchersForm, self).__init__(*args, **kwargs) activeQ = Q(activeuntil__isnull=True) | Q(activeuntil__gt=date.today()) - if self.data and self.data.has_key('regtype') and self.data['regtype'] and self.data.has_key('num') and self.data['num'] and _int_with_default(self.data['num'], 0) > 0: + if self.data and self.data.get('regtype', None) and self.data.get('num', None) and _int_with_default(self.data['num'], 0) > 0: RegistrationType.objects.get(pk=self.data['regtype']) self.fields['confirm'].help_text = 'Check this box to confirm that you will pay the generated invoice' self.fields['num'].widget.attrs['readonly'] = True @@ -172,7 +172,7 @@ class PurchaseDiscountForm(forms.Form): def clean(self): cleaned_data = super(PurchaseDiscountForm, self).clean() - if cleaned_data.has_key('amount') and cleaned_data.has_key('percent'): + if 'amount' in cleaned_data and 'percent' in cleaned_data: # Only one can be specified if _int_with_default(cleaned_data['amount'], 0) > 0 and _int_with_default(cleaned_data['percent'], 0) > 0: self._errors['amount'] = ErrorList(['Cannot specify both amount and percent!']) diff --git a/postgresqleu/confsponsor/views.py b/postgresqleu/confsponsor/views.py index 730cbed3..0b671b26 100644 --- a/postgresqleu/confsponsor/views.py +++ b/postgresqleu/confsponsor/views.py @@ -198,12 +198,12 @@ def sponsor_purchase_discount(request, sponsorid): conference = sponsor.conference if request.method == 'POST': - if request.POST.has_key('confirm'): + if 'confirm' in request.POST: form = PurchaseDiscountForm(conference, showconfirm=True, data=request.POST) else: form = PurchaseDiscountForm(conference, data=request.POST) if form.is_valid(): - if not form.cleaned_data.has_key('confirm'): + if 'confirm' not in form.cleaned_data: form = PurchaseDiscountForm(conference, showconfirm=True, data=request.POST) else: # Generate the code. We can't generate the invoice at this point, as it diff --git a/postgresqleu/confwiki/views.py b/postgresqleu/confwiki/views.py index 2fd38526..bc8d19bf 100644 --- a/postgresqleu/confwiki/views.py +++ b/postgresqleu/confwiki/views.py @@ -103,7 +103,7 @@ def wikipage_history(request, confurl, wikiurl): if request.method == 'POST': # View a diff - if not (request.POST.has_key('from') and request.POST.has_key('to')): + if not ('from' in request.POST and 'to' in request.POST): messages.warning(request, "Must specify both source and target version") return HttpResponseRedirect('.') diff --git a/postgresqleu/elections/forms.py b/postgresqleu/elections/forms.py index 125adff8..984c734c 100644 --- a/postgresqleu/elections/forms.py +++ b/postgresqleu/elections/forms.py @@ -33,7 +33,7 @@ class VoteForm(forms.Form): label=candidate.name, required=True, help_text=candidate.id, - initial=votemap.has_key(candidate.id) and votemap[candidate.id] or -1) + initial=votemap.get(candidate.id, -1)) def _votestring(self, x): if x == 1: @@ -54,8 +54,9 @@ class VoteForm(forms.Form): # Second, make sure the fields match the candidates fields = self.cleaned_data.copy() for candidate in self.candidates: - if fields.has_key("cand%i" % candidate.id): - del fields["cand%i" % candidate.id] + k = "cand%i" % candidate.id + if k in fields: + del fields[k] else: raise Exception("Data for candidate %i is missing" % candidate.id) @@ -70,7 +71,7 @@ class VoteForm(forms.Form): del options[options.index(int(v))] else: # Not in the list means it was already used! Bad user! - if not self._errors.has_key(k): + if k not in self._errors: # Only add this error in case the other error hasn't already fired self._errors[k] = ErrorList(["This score has already been given to another candidate"]) diff --git a/postgresqleu/invoices/admin.py b/postgresqleu/invoices/admin.py index 5b75d1f1..3a3151b0 100644 --- a/postgresqleu/invoices/admin.py +++ b/postgresqleu/invoices/admin.py @@ -19,32 +19,32 @@ class InvoiceAdminForm(SelectableWidgetAdminFormMixin, ConcurrentProtectedModelF } def clean_recipient_email(self): - if self.cleaned_data.has_key('finalized'): + if 'finalized' in self.cleaned_data: raise ValidationError("Can't edit email field on a finalized invoice!") return self.cleaned_data['recipient_email'] def clean_recipient_name(self): - if self.cleaned_data.has_key('finalized'): + if 'finalized' in self.cleaned_data: raise ValidationError("Can't edit name field on a finalized invoice!") return self.cleaned_data['recipient_name'] def clean_recipient_address(self): - if self.cleaned_data.has_key('finalized'): + if 'finalized' in self.cleaned_data: raise ValidationError("Can't edit address field on a finalized invoice!") return self.cleaned_data['recipient_address'] def clean_title(self): - if self.cleaned_data.has_key('finalized'): + if 'finalized' in self.cleaned_data: raise ValidationError("Can't edit title field on a finalized invoice!") return self.cleaned_data['title'] def clean_total_amount(self): - if self.cleaned_data.has_key('finalized'): + if 'finalized' in self.cleaned_data: raise ValidationError("Can't edit total amount field on a finalized invoice!") return self.cleaned_data['total_amount'] def clean_total_vat(self): - if self.cleaned_data.has_key('finalized'): + if 'finalized' in self.cleaned_data: raise ValidationError("Can't edit total vat field on a finalized invoice!") return self.cleaned_data['total_vat'] diff --git a/postgresqleu/invoices/forms.py b/postgresqleu/invoices/forms.py index 23cd0f17..60aa0e34 100644 --- a/postgresqleu/invoices/forms.py +++ b/postgresqleu/invoices/forms.py @@ -58,7 +58,7 @@ class InvoiceForm(forms.ModelForm): } def clean(self): - if not self.cleaned_data['recipient_user'] and self.cleaned_data.has_key('recipient_email') and self.cleaned_data['recipient_email']: + if not self.cleaned_data['recipient_user'] and self.cleaned_data.get('recipient_email', None): # User not specified. If we can find one by email, auto-populate # the field. matches = User.objects.filter(email=self.cleaned_data['recipient_email']) @@ -106,7 +106,7 @@ class RefundForm(forms.Form): super(RefundForm, self).__init__(*args, **kwargs) self.invoice = invoice - if self.data and self.data.has_key('amount') and self.data.has_key('reason'): + if self.data and 'amount' in self.data and 'reason' in self.data: if invoice.can_autorefund: self.fields['confirm'].help_text = "Check this box to confirm that you want to generate an <b>automatic</b> refund of this invoice." else: @@ -147,7 +147,7 @@ class RefundForm(forms.Form): def clean(self): data = super(RefundForm, self).clean() - if data.has_key('vatamount') and Decimal(data['vatamount']) > 0: - if not data.has_key('vatrate') or not data['vatrate']: + if 'vatamount' in data and Decimal(data['vatamount']) > 0: + if not data.get('vatrate', 0): raise ValidationError({'vatrate': ['When VAT amount is specified, at VAT rate must be selected']}) return data diff --git a/postgresqleu/invoices/views.py b/postgresqleu/invoices/views.py index 82dc2c05..64a4a7e4 100644 --- a/postgresqleu/invoices/views.py +++ b/postgresqleu/invoices/views.py @@ -77,9 +77,9 @@ def _homeview(request, invoice_objects, unpaid=False, pending=False, deleted=Fal @login_required @user_passes_test_or_error(lambda u: u.has_module_perms('invoices')) def search(request): - if request.POST.has_key('term'): + if 'term' in request.POST: term = request.POST['term'] - elif request.GET.has_key('term'): + elif 'term' in request.GET: term = request.GET['term'] else: raise Exception("Sorry, need a search term!") @@ -146,7 +146,7 @@ def oneinvoice(request, invoicenum): postcopy = request.POST.copy() if not invoicenum == 'new': for fld in ('accounting_account', 'accounting_object', ): - if not postcopy.has_key(fld): + if fld not in postcopy: postcopy[fld] = getattr(invoice, fld) form = InvoiceForm(data=postcopy, instance=invoice) @@ -312,10 +312,10 @@ def previewinvoice(request, invoicenum): @user_passes_test_or_error(lambda u: u.has_module_perms('invoices')) @transaction.atomic def emailinvoice(request, invoicenum): - if not (request.GET.has_key('really') and request.GET['really'] == 'yes'): + if request.GET('really', None) != 'yes': return HttpResponse('Secret key is missing!', status=401) - if not request.GET.has_key('reason'): + if 'reason' not in request.GET: return HttpResponse('Reason is missing!', status=401) if not request.GET['reason'] in ('initial', 'reminder'): return HttpResponse('Invalid reason given!', status=401) @@ -431,7 +431,7 @@ def banktransfer(request): 'title': request.GET['title'], 'amount': request.GET['amount'], } - if request.GET.has_key('ret'): + if 'ret' in request.GET: param['returnurl'] = request.GET['ret'] return render(request, 'invoices/banktransfer.html', param) diff --git a/postgresqleu/paypal/management/commands/paypal_fetch.py b/postgresqleu/paypal/management/commands/paypal_fetch.py index ae7d0b50..54d843f7 100644 --- a/postgresqleu/paypal/management/commands/paypal_fetch.py +++ b/postgresqleu/paypal/management/commands/paypal_fetch.py @@ -53,14 +53,14 @@ class PaypalBaseTransaction(object): elif r['TRANSACTIONTYPE'][0] == 'sendmoney': # This is sending of money, and not receiving. The transaction # text (naturally) goes in a completely different field. - if r.has_key('NOTE'): + if 'NOTE' in r: self.transinfo.transtext = 'Paypal payment: %s' % r['NOTE'][0] else: self.transinfo.transtext = 'Paypal payment with empty note' else: - if r.has_key('SUBJECT'): + if 'SUBJECT' in r: self.transinfo.transtext = r['SUBJECT'][0] - elif r.has_key('L_NAME0'): + elif 'L_NAME0' in r: self.transinfo.transtext = r['L_NAME0'][0] else: self.transinfo.transtext = "" @@ -100,7 +100,7 @@ class PaypalTransfer(PaypalBaseTransaction): self.transinfo.transtext = "Transfer from Paypal to bank" self.transinfo.fee = 0 self.transinfo.sender = 'treasurer@postgresql.eu' - if apistruct.has_key('CURRENCYCODE') and apistruct['CURRENCYCODE'] != settings.CURRENCY_ISO: + if apistruct.get('CURRENCYCODE', None) != settings.CURRENCY_ISO: self.message = "Invalid currency %s" % apistruct['CURRENCYCODE'] self.transinfo.transtext += ' (currency %s, manually adjust amount!)' % apistruct['CURRENCYCODE'] self.transinfo.amount = -1 # To be on the safe side diff --git a/postgresqleu/paypal/management/commands/paypal_match.py b/postgresqleu/paypal/management/commands/paypal_match.py index 21606037..e52d4d2d 100755 --- a/postgresqleu/paypal/management/commands/paypal_match.py +++ b/postgresqleu/paypal/management/commands/paypal_match.py @@ -102,7 +102,7 @@ class Command(BaseCommand): accrows = [ (settings.ACCOUNTING_PAYPAL_INCOME_ACCOUNT, trans.transtext[:200], trans.amount - trans.fee, None), ] - if trans.fee <> 0: + if trans.fee != 0: accrows.append((settings.ACCOUNTING_PAYPAL_FEE_ACCOUNT, trans.transtext[:200], trans.fee, None),) create_accounting_entry(trans.timestamp.date(), accrows, True, urls) continue diff --git a/postgresqleu/paypal/util.py b/postgresqleu/paypal/util.py index aeb501a9..7c7b42bb 100644 --- a/postgresqleu/paypal/util.py +++ b/postgresqleu/paypal/util.py @@ -38,7 +38,8 @@ class PaypalAPI(object): 'STATUS': 'Success', }) for i in itertools.count(0): - if not r.has_key('L_TRANSACTIONID{0}'.format(i)): + k = 'L_TRANSACTIONID{0}'.format(i) + if k not in r: if i == 0: # Special case as it seems inconsistent if it starts on 0 or on 1. # So if there is no 0, just retry the loop at 1, and if there is still diff --git a/postgresqleu/paypal/views.py b/postgresqleu/paypal/views.py index c4935e4b..50fa4734 100644 --- a/postgresqleu/paypal/views.py +++ b/postgresqleu/paypal/views.py @@ -36,7 +36,7 @@ def paypal_return_handler(request): # Now for the main handler # Handle a paypal PDT return - if not request.GET.has_key('tx'): + if 'tx' not in request.GET: return paypal_error('Transaction id not received from paypal') tx = request.GET['tx'] @@ -95,7 +95,7 @@ def paypal_return_handler(request): return paypal_error('Mandatory field %s is missing from paypal data!', k) # Now let's find the state of the payment - if not d.has_key('payment_status'): + if 'payment_status' not in d: return paypal_error('Payment status not received from paypal!') if d['payment_status'] == 'Completed': @@ -111,7 +111,7 @@ def paypal_return_handler(request): # Paypal seems to randomly change which field actually contains # the transaction title. - if d.has_key('transaction_subject') and d['transaction_subject'] != '': + if d.get('transaction_subject', ''): transtext = d['transaction_subject'] else: transtext = d['item_name'] diff --git a/postgresqleu/trustlypayment/api.py b/postgresqleu/trustlypayment/api.py index a4fca9fd..9c8e268b 100644 --- a/postgresqleu/trustlypayment/api.py +++ b/postgresqleu/trustlypayment/api.py @@ -112,7 +112,7 @@ class TrustlyWrapper(object): raise TrustlyException("bad http response code {0}".format(u.getcode())) u.close() r = json.loads(resp) - if r.has_key('error'): + if 'error' in r: # XXX log and raise generic exception! raise TrustlyException(r['error']['message']) if r['result']['method'] != method: diff --git a/postgresqleu/trustlypayment/util.py b/postgresqleu/trustlypayment/util.py index 1165d93b..8c8ca2ad 100644 --- a/postgresqleu/trustlypayment/util.py +++ b/postgresqleu/trustlypayment/util.py @@ -51,7 +51,7 @@ class Trustly(TrustlyWrapper): method=method, notificationid=data['notificationid'], orderid=data['orderid'], - amount=data.has_key('amount') and Decimal(data['amount']) or None, + amount='amount' in data and Decimal(data['amount']) or None, messageid=data['messageid'], ) n.save() diff --git a/postgresqleu/util/diffablemodel.py b/postgresqleu/util/diffablemodel.py index 8c4f68ab..94ad3e5f 100644 --- a/postgresqleu/util/diffablemodel.py +++ b/postgresqleu/util/diffablemodel.py @@ -26,7 +26,7 @@ class DiffableModel(object): # Many to many lookups if hasattr(self, 'map_manytomany_for_diff'): for k, v in diffs.items(): - if k in manytomanyfieldnames and self.map_manytomany_for_diff.has_key(k): + if k in manytomanyfieldnames and k in self.map_manytomany_for_diff: # Try to show the display name instead here newvalue = getattr(self, self.map_manytomany_for_diff[k]) diffs[k] = (v[0], newvalue) diff --git a/postgresqleu/util/middleware.py b/postgresqleu/util/middleware.py index 778118f8..becb90c6 100644 --- a/postgresqleu/util/middleware.py +++ b/postgresqleu/util/middleware.py @@ -11,7 +11,7 @@ class FilterPersistMiddleware(object): path = request.path if path.find('/admin/') != -1: # Dont waste time if we are not in admin query_string = request.META['QUERY_STRING'] - if not request.META.has_key('HTTP_REFERER'): + if 'HTTP_REFERER' not in request.META: return None session = request.session @@ -31,7 +31,7 @@ class FilterPersistMiddleware(object): request.session[key] = query_string elif '_directlink=1' in query_string: # Direct link to a filter, by ourselves, so remove it redirect_to = path + '?' + query_string.replace('&_directlink=1', '') - if session.has_key(key): + if key in session: del session[key] return http.HttpResponseRedirect(redirect_to) else: # We are are coming from another page, restore filter if available diff --git a/postgresqleu/util/payment/adyen.py b/postgresqleu/util/payment/adyen.py index e400017a..429c6c8a 100644 --- a/postgresqleu/util/payment/adyen.py +++ b/postgresqleu/util/payment/adyen.py @@ -25,7 +25,7 @@ def _escapeVal(val): def calculate_signature(param): param = OrderedDict(sorted(param.items(), key=lambda t: t[0])) - if param.has_key('merchantSig'): + if 'merchantSig' in param: del param['merchantSig'] str = ':'.join(map(_escapeVal, param.keys() + param.values())) hm = hmac.new(binascii.a2b_hex(settings.ADYEN_SIGNKEY), diff --git a/tools/deploystatic/deploystatic.py b/tools/deploystatic/deploystatic.py index 31260652..2ea1e417 100755 --- a/tools/deploystatic/deploystatic.py +++ b/tools/deploystatic/deploystatic.py @@ -118,13 +118,13 @@ class TarWrapper(object): self.tarstruct[m.name] = m def isdir(self, d): - return self.tarstruct.has_key(d) and self.tarstruct[d].isdir() + return d in self.tarstruct and self.tarstruct[d].isdir() def isfile(self, f): - return self.tarstruct.has_key(f) and self.tarstruct[f].isfile() + return f in self.tarstruct and self.tarstruct[f].isfile() def readfile(self, src): - if self.tarstruct.has_key(src) and self.tarstruct[src].isfile(): + if src in self.tarstruct and self.tarstruct[src].isfile(): return self.tarfile.extractfile(src).read() else: return None diff --git a/tools/paypal/oneoff/backfill_paypal_fees.py b/tools/paypal/oneoff/backfill_paypal_fees.py index 5bbeadf4..bb47c752 100755 --- a/tools/paypal/oneoff/backfill_paypal_fees.py +++ b/tools/paypal/oneoff/backfill_paypal_fees.py @@ -35,7 +35,7 @@ if __name__ == "__main__": sys.exit(1) # Amounts match, get the fee # For donations, there is no fee and a different xtype - if info['TRANSACTIONTYPE'][0] == 'sendmoney' and not info.has_key('FEEAMT'): + if info['TRANSACTIONTYPE'][0] == 'sendmoney' and 'FEEAMT' not in info: print "%s: Amount %s, donation, no fee" % (ti.paypaltransid, ti.amount) ti.fee = 0 else: |
