remove has_key

pull/94/head
eric 2020-02-12 11:12:56 -05:00
parent 82db131740
commit 60017ab959
13 changed files with 90 additions and 90 deletions

View File

@ -62,7 +62,7 @@ def add_by_oclc_from_google(oclc):
except LookupFailure, e: except LookupFailure, e:
logger.exception(u"lookup failure for %s", oclc) logger.exception(u"lookup failure for %s", oclc)
return None return None
if not results.has_key('items') or not results['items']: if not 'items' in results or not results['items']:
logger.warn(u"no google hits for %s", oclc) logger.warn(u"no google hits for %s", oclc)
return None return None
@ -136,7 +136,7 @@ def get_google_isbn_results(isbn):
except LookupFailure: except LookupFailure:
logger.exception(u"lookup failure for %s", isbn) logger.exception(u"lookup failure for %s", isbn)
return None return None
if not results.has_key('items') or not results['items']: if not 'items' in results or not results['items']:
logger.warn(u"no google hits for %s", isbn) logger.warn(u"no google hits for %s", isbn)
return None return None
return results return results
@ -188,7 +188,7 @@ def update_edition(edition):
item = results['items'][0] item = results['items'][0]
googlebooks_id = item['id'] googlebooks_id = item['id']
d = item['volumeInfo'] d = item['volumeInfo']
if d.has_key('title'): if 'title' in d:
title = d['title'] title = d['title']
else: else:
title = '' title = ''
@ -342,7 +342,7 @@ def add_by_googlebooks_id(googlebooks_id, work=None, results=None, isbn=None):
item = _get_json(url) item = _get_json(url)
d = item['volumeInfo'] d = item['volumeInfo']
if d.has_key('title'): if 'title' in d:
title = d['title'] title = d['title']
else: else:
title = '' title = ''
@ -486,7 +486,7 @@ def add_related(isbn):
logger.debug(u"merge_works path 1 %s %s", work.id, related_edition.work_id) logger.debug(u"merge_works path 1 %s %s", work.id, related_edition.work_id)
work = merge_works(work, related_edition.work) work = merge_works(work, related_edition.work)
else: else:
if other_editions.has_key(related_language): if related_language in other_editions:
other_editions[related_language].append(related_edition) other_editions[related_language].append(related_edition)
else: else:
other_editions[related_language] = [related_edition] other_editions[related_language] = [related_edition]
@ -670,9 +670,9 @@ def add_openlibrary(work, hard_refresh=False):
except LookupFailure: except LookupFailure:
logger.exception(u"OL lookup failed for %s", isbn_key) logger.exception(u"OL lookup failed for %s", isbn_key)
e = {} e = {}
if e.has_key(isbn_key): if isbn_key in e:
if e[isbn_key].has_key('details'): if 'details' in e[isbn_key]:
if e[isbn_key]['details'].has_key('oclc_numbers'): if 'oclc_numbers' in e[isbn_key]['details']:
for oclcnum in e[isbn_key]['details']['oclc_numbers']: for oclcnum in e[isbn_key]['details']['oclc_numbers']:
models.Identifier.get_or_add( models.Identifier.get_or_add(
type='oclc', type='oclc',
@ -680,42 +680,42 @@ def add_openlibrary(work, hard_refresh=False):
work=work, work=work,
edition=edition edition=edition
) )
if e[isbn_key]['details'].has_key('identifiers'): if 'identifiers' in e[isbn_key]['details']:
ids = e[isbn_key]['details']['identifiers'] ids = e[isbn_key]['details']['identifiers']
if ids.has_key('goodreads'): if 'goodreads' in ids:
models.Identifier.get_or_add( models.Identifier.get_or_add(
type='gdrd', type='gdrd',
value=ids['goodreads'][0], value=ids['goodreads'][0],
work=work, edition=edition work=work, edition=edition
) )
if ids.has_key('librarything'): if 'librarything' in ids:
models.Identifier.get_or_add( models.Identifier.get_or_add(
type='ltwk', type='ltwk',
value=ids['librarything'][0], value=ids['librarything'][0],
work=work work=work
) )
if ids.has_key('google'): if 'google' in ids:
models.Identifier.get_or_add( models.Identifier.get_or_add(
type='goog', type='goog',
value=ids['google'][0], value=ids['google'][0],
work=work work=work
) )
if ids.has_key('project_gutenberg'): if 'project_gutenberg' in ids:
models.Identifier.get_or_add( models.Identifier.get_or_add(
type='gute', type='gute',
value=ids['project_gutenberg'][0], value=ids['project_gutenberg'][0],
work=work work=work
) )
if e[isbn_key]['details'].has_key('works'): if 'works' in e[isbn_key]['details']:
work_key = e[isbn_key]['details']['works'].pop(0)['key'] work_key = e[isbn_key]['details']['works'].pop(0)['key']
logger.info(u"got openlibrary work %s for isbn %s", work_key, isbn_key) logger.info(u"got openlibrary work %s for isbn %s", work_key, isbn_key)
models.Identifier.get_or_add(type='olwk', value=work_key, work=work) models.Identifier.get_or_add(type='olwk', value=work_key, work=work)
try: try:
w = _get_json("https://openlibrary.org" + work_key, type='ol') w = _get_json("https://openlibrary.org" + work_key, type='ol')
if w.has_key('description'): if 'description' in w:
description = w['description'] description = w['description']
if isinstance(description, dict): if isinstance(description, dict):
if description.has_key('value'): if 'value' in description:
description = description['value'] description = description['value']
description = despam_description(description) description = despam_description(description)
if not work.description or \ if not work.description or \
@ -723,7 +723,7 @@ def add_openlibrary(work, hard_refresh=False):
len(description) > len(work.description): len(description) > len(work.description):
work.description = description work.description = description
work.save() work.save()
if w.has_key('subjects') and len(w['subjects']) > len(subjects): if 'subjects' in w and len(w['subjects']) > len(subjects):
subjects = w['subjects'] subjects = w['subjects']
except LookupFailure: except LookupFailure:
logger.exception(u"OL lookup failed for %s", work_key) logger.exception(u"OL lookup failed for %s", work_key)

View File

@ -140,7 +140,7 @@ class BaseScraper(object):
else: else:
if el.text: if el.text:
value_list.append(el.text) value_list.append(el.text)
elif el.has_key('content'): elif 'content' in el:
value_list.append(el['content']) value_list.append(el['content'])
return value_list return value_list

View File

@ -20,12 +20,12 @@ def gluejar_search(q, user_ip='69.243.24.29', page=1):
'googlebooks_id': item.get('id')} 'googlebooks_id': item.get('id')}
# TODO: allow multiple authors # TODO: allow multiple authors
if v.has_key('authors') and len(v['authors']) == 1: if 'authors' in v and len(v['authors']) == 1:
r['author'] = r['authors_short'] = v['authors'][0] r['author'] = r['authors_short'] = v['authors'][0]
elif v.has_key('authors') and len(v['authors']) > 2: elif 'authors' in v and len(v['authors']) > 2:
r['author'] = v['authors'][0] r['author'] = v['authors'][0]
r['authors_short'] = '%s et al.' % v['authors'][0] r['authors_short'] = '%s et al.' % v['authors'][0]
elif v.has_key('authors') and len(v['authors']) == 2: elif 'authors' in v and len(v['authors']) == 2:
r['author'] = v['authors'][0] r['author'] = v['authors'][0]
r['authors_short'] = '%s and %s' % (v['authors'][0], v['authors'][1]) r['authors_short'] = '%s and %s' % (v['authors'][0], v['authors'][1])
else: else:
@ -41,7 +41,7 @@ def gluejar_search(q, user_ip='69.243.24.29', page=1):
r['isbn_13'] = regluit.core.isbn.convert_10_to_13(i['identifier']) r['isbn_13'] = regluit.core.isbn.convert_10_to_13(i['identifier'])
# cover image # cover image
if v.has_key('imageLinks'): if 'imageLinks' in v:
url = v['imageLinks'].get('thumbnail', "") url = v['imageLinks'].get('thumbnail', "")
url = re.sub( url = re.sub(
r'http://(bks[0-9]+\.)?books\.google\.com', r'http://(bks[0-9]+\.)?books\.google\.com',

View File

@ -542,17 +542,17 @@ class SearchTests(TestCase):
self.assertEqual(len(results), 10) self.assertEqual(len(results), 10)
r = results[0] r = results[0]
self.assertTrue(r.has_key('title')) self.assertTrue('title' in r)
self.assertTrue(r.has_key('author')) self.assertTrue('author' in r)
self.assertTrue(r.has_key('description')) self.assertTrue('description' in r)
self.assertTrue(r.has_key('cover_image_thumbnail')) self.assertTrue('cover_image_thumbnail' in r)
self.assertTrue( self.assertTrue(
r['cover_image_thumbnail'].startswith('https') r['cover_image_thumbnail'].startswith('https')
or r['cover_image_thumbnail'].startswith('http') or r['cover_image_thumbnail'].startswith('http')
) )
self.assertTrue(r.has_key('publisher')) self.assertTrue('publisher' in r)
self.assertTrue(r.has_key('isbn_13')) self.assertTrue('isbn_13' in r)
self.assertTrue(r.has_key('googlebooks_id')) self.assertTrue('googlebooks_id' in r)
def test_pagination(self, mocking=False): def test_pagination(self, mocking=False):
if not (mocking or settings.TEST_INTEGRATION): if not (mocking or settings.TEST_INTEGRATION):
@ -825,7 +825,7 @@ class GoodreadsTest(TestCase):
reviews = gc.review_list_unauth(user_id=gr_uid, shelf='read') reviews = gc.review_list_unauth(user_id=gr_uid, shelf='read')
# test to see whether there is a book field in each of the review # test to see whether there is a book field in each of the review
# url for test is https://www.goodreads.com/review/list.xml?id=767708&shelf=read&page=1&per_page=20&order=a&v=2&key=[key] # url for test is https://www.goodreads.com/review/list.xml?id=767708&shelf=read&page=1&per_page=20&order=a&v=2&key=[key]
self.assertTrue(all([r.has_key("book") for r in reviews])) self.assertTrue(all(["book" in r for r in reviews]))
class LibraryThingTest(TestCase): class LibraryThingTest(TestCase):

View File

@ -81,7 +81,7 @@ ID_MORE_VALIDATION = {
} }
def identifier_cleaner(id_type, quiet=False): def identifier_cleaner(id_type, quiet=False):
if ID_VALIDATION.has_key(id_type): if id_type in ID_VALIDATION:
(regex, err_msg) = ID_VALIDATION[id_type] (regex, err_msg) = ID_VALIDATION[id_type]
extra = ID_MORE_VALIDATION.get(id_type, None) extra = ID_MORE_VALIDATION.get(id_type, None)
if isinstance(regex, (str, unicode)): if isinstance(regex, (str, unicode)):

View File

@ -531,14 +531,14 @@ class MsgForm(forms.Form):
def full_clean(self): def full_clean(self):
super(MsgForm, self).full_clean() super(MsgForm, self).full_clean()
if self.data.has_key("supporter"): if "supporter" in self.data:
try: try:
self.cleaned_data['supporter'] = User.objects.get(id=self.data["supporter"]) self.cleaned_data['supporter'] = User.objects.get(id=self.data["supporter"])
except User.DoesNotExist: except User.DoesNotExist:
raise ValidationError("Supporter does not exist") raise ValidationError("Supporter does not exist")
else: else:
raise ValidationError("Supporter is not specified") raise ValidationError("Supporter is not specified")
if self.data.has_key("work"): if "work" in self.data:
try: try:
self.cleaned_data['work'] = Work.objects.get(id=self.data["work"]) self.cleaned_data['work'] = Work.objects.get(id=self.data["work"])
except Work.DoesNotExist: except Work.DoesNotExist:

View File

@ -171,13 +171,13 @@ def process_kindle_email(request):
download + login/account creation; add kindle email to profile download + login/account creation; add kindle email to profile
""" """
user = request.user user = request.user
if user.is_authenticated and request.session.has_key('kindle_email'): if user.is_authenticated and 'kindle_email' in request.session:
user.profile.kindle_email = request.session['kindle_email'] user.profile.kindle_email = request.session['kindle_email']
user.profile.save() user.profile.save()
request.session.pop('kindle_email') request.session.pop('kindle_email')
def next(request): def next(request):
if request.COOKIES.has_key('next'): if 'next' in request.COOKIES:
response = HttpResponseRedirect(urllib.unquote(urllib.unquote(request.COOKIES['next']))) response = HttpResponseRedirect(urllib.unquote(urllib.unquote(request.COOKIES['next'])))
response.delete_cookie('next') response.delete_cookie('next')
return response return response
@ -314,7 +314,7 @@ def work(request, work_id, action='display'):
for form in formset.deleted_forms: for form in formset.deleted_forms:
detach_edition(form.instance) detach_edition(form.instance)
alert = 'editions have been split' alert = 'editions have been split'
if request.POST.has_key('select_edition'): if 'select_edition' in request.POST:
selected_id = request.POST['select_edition'] selected_id = request.POST['select_edition']
try: try:
work.selected_edition = work.editions.get(id=selected_id) work.selected_edition = work.editions.get(id=selected_id)
@ -326,7 +326,7 @@ def work(request, work_id, action='display'):
formset = EditionFormSet(instance=work) formset = EditionFormSet(instance=work)
# process waiting add request # process waiting add request
if not request.user.is_anonymous and request.session.has_key("add_wishlist"): if not request.user.is_anonymous and "add_wishlist" in request.session:
add_url = request.session["add_wishlist"] add_url = request.session["add_wishlist"]
if add_url == request.path: if add_url == request.path:
request.user.wishlist.add_work(work, "login", notify=True) request.user.wishlist.add_work(work, "login", notify=True)
@ -556,7 +556,7 @@ def googlebooks(request, googlebooks_id):
work_url = reverse('work', kwargs={'work_id': edition.work_id}) work_url = reverse('work', kwargs={'work_id': edition.work_id})
# process waiting add request # process waiting add request
if not request.user.is_anonymous and request.session.has_key("add_wishlist"): if not request.user.is_anonymous and "add_wishlist" in request.session:
add_url = request.session["add_wishlist"] add_url = request.session["add_wishlist"]
if add_url == request.path: if add_url == request.path:
request.user.wishlist.add_work(edition.work, "login", notify=True) request.user.wishlist.add_work(edition.work, "login", notify=True)
@ -601,7 +601,7 @@ class MapSubjectView(FormView):
context = self.get_context_data() context = self.get_context_data()
context['subject'] = form.cleaned_data['subject'] context['subject'] = form.cleaned_data['subject']
context['onto_subject'] = form.cleaned_data['onto_subject'] context['onto_subject'] = form.cleaned_data['onto_subject']
if self.request.POST.has_key('confirm_map_subject'): if 'confirm_map_subject' in self.request.POST:
initial_count = context['onto_subject'].works.all().count() initial_count = context['onto_subject'].works.all().count()
initial_free_count = context['onto_subject'].works.filter(is_free=True).count() initial_free_count = context['onto_subject'].works.filter(is_free=True).count()
context['onto_subject'].works.add(*list(context['subject'].works.all())) context['onto_subject'].works.add(*list(context['subject'].works.all()))
@ -616,7 +616,7 @@ class MapSubjectView(FormView):
class FilterableListView(ListView): class FilterableListView(ListView):
send_marc = False send_marc = False
def get_queryset(self): def get_queryset(self):
if self.request.GET.has_key('pub_lang'): if 'pub_lang' in self.request.GET:
if self.model is models.Campaign: if self.model is models.Campaign:
return self.get_queryset_all().filter(work__language=self.request.GET['pub_lang']) return self.get_queryset_all().filter(work__language=self.request.GET['pub_lang'])
else: else:
@ -626,7 +626,7 @@ class FilterableListView(ListView):
def get_context_data(self, **kwargs): def get_context_data(self, **kwargs):
context = super(FilterableListView, self).get_context_data(**kwargs) context = super(FilterableListView, self).get_context_data(**kwargs)
if self.request.GET.has_key('pub_lang'): if 'pub_lang' in self.request.GET:
context['pub_lang'] = self.request.GET['pub_lang'] context['pub_lang'] = self.request.GET['pub_lang']
else: else:
context['pub_lang'] = '' context['pub_lang'] = ''
@ -700,7 +700,7 @@ class FacetedView(FilterableListView):
context = super(FacetedView, self).get_context_data(**kwargs) context = super(FacetedView, self).get_context_data(**kwargs)
facet = self.kwargs.get('facet','all') facet = self.kwargs.get('facet','all')
qs = self.get_queryset() qs = self.get_queryset()
if self.request.GET.has_key('setkw') and self.request.user.is_staff: if 'setkw' in self.request.GET and self.request.user.is_staff:
setkw = self.request.GET['setkw'] setkw = self.request.GET['setkw']
try: try:
context['setkw'] = models.Subject.objects.get(name=setkw) context['setkw'] = models.Subject.objects.get(name=setkw)
@ -858,7 +858,7 @@ class MergeView(FormView):
return context return context
def get_form_class(self): def get_form_class(self):
if self.request.method == 'POST' and self.request.POST.has_key('confirm_merge_works'): if self.request.method == 'POST' and 'confirm_merge_works' in self.request.POST:
return WorkForm return WorkForm
else: else:
return OtherWorkForm return OtherWorkForm
@ -873,7 +873,7 @@ class MergeView(FormView):
def form_valid(self, form): def form_valid(self, form):
other_work = form.cleaned_data['other_work'] other_work = form.cleaned_data['other_work']
context = self.get_context_data() context = self.get_context_data()
if self.request.POST.has_key('confirm_merge_works'): if 'confirm_merge_works' in self.request.POST:
context['old_work_id'] = other_work.id context['old_work_id'] = other_work.id
self.work = merge_works(self.work, other_work, self.request.user) self.work = merge_works(self.work, other_work, self.request.user)
context['merge_complete'] = True context['merge_complete'] = True
@ -983,11 +983,11 @@ class PledgeView(FormView):
'ack_name':ack_name, 'ack_dedication':ack_dedication, 'anonymous':anonymous} 'ack_name':ack_name, 'ack_dedication':ack_dedication, 'anonymous':anonymous}
if self.request.method == 'POST': if self.request.method == 'POST':
self.data.update(self.request.POST.dict()) self.data.update(self.request.POST.dict())
if not self.request.POST.has_key('anonymous'): if not 'anonymous' in self.request.POST:
del self.data['anonymous'] del self.data['anonymous']
if not self.request.POST.has_key('ack_name'): if not 'ack_name' in self.request.POST:
del self.data['ack_name'] del self.data['ack_name']
if not self.request.POST.has_key('ack_dedication'): if not 'ack_dedication' in self.request.POST:
del self.data['ack_dedication'] del self.data['ack_dedication']
return {'data':self.data} return {'data':self.data}
else: else:
@ -1106,7 +1106,7 @@ class PurchaseView(PledgeView):
data.update(self.data) data.update(self.data)
self.data = data self.data = data
self.data['give'] = self.give self.data['give'] = self.give
if not self.request.POST.has_key('anonymous'): if not 'anonymous' in self.request.POST:
del self.data['anonymous'] del self.data['anonymous']
return {'data':self.data} return {'data':self.data}
else: else:
@ -1173,7 +1173,7 @@ class FundView(FormView):
def get_form_kwargs(self): def get_form_kwargs(self):
kwargs = super(FundView, self).get_form_kwargs() kwargs = super(FundView, self).get_form_kwargs()
if kwargs.has_key('data'): if 'data' in kwargs:
data = kwargs['data'].copy() data = kwargs['data'].copy()
kwargs['data'] = data kwargs['data'] = data
else: else:
@ -1442,7 +1442,7 @@ class FundCompleteView(TemplateView):
if not self.user_is_ok(): if not self.user_is_ok():
return context return context
gift = self.transaction.extra.has_key('give_to') gift = 'give_to' in self.transaction.extra
if not gift: if not gift:
# add the work corresponding to the Transaction on the user's wishlist if it's not already on the wishlist # add the work corresponding to the Transaction on the user's wishlist if it's not already on the wishlist
if self.transaction.user is not None and (campaign is not None) and (work is not None): if self.transaction.user is not None and (campaign is not None) and (work is not None):
@ -2576,7 +2576,7 @@ def feedback(request, recipient='unglueit@ebookfoundation.org', template='feedba
context['page'] = request.GET['page'] context['page'] = request.GET['page']
except: except:
context['page'] = '/' context['page'] = '/'
if not context.has_key('subject'): if not 'subject' in context:
context['subject'] = "Feedback on page "+context['page'] context['subject'] = "Feedback on page "+context['page']
form = FeedbackForm(initial=context) form = FeedbackForm(initial=context)
context['form'] = form context['form'] = form
@ -2631,11 +2631,11 @@ class DownloadView(PurchaseView):
if not self.campaign or self.campaign.type != THANKS: if not self.campaign or self.campaign.type != THANKS:
return False return False
elif self.user_license and self.user_license.thanked: elif self.user_license and self.user_license.thanked:
return self.request.GET.has_key('offer_id') or self.request.POST.has_key('offer_id') return 'offer_id' in self.request.GET or 'offer_id' in self.request.POST
elif self.lib_thanked: elif self.lib_thanked:
return False return False
elif self.campaign.status != 'ACTIVE': elif self.campaign.status != 'ACTIVE':
return self.request.GET.has_key('testmode') or self.request.POST.has_key('testmode') return 'testmode' in self.request.GET or 'testmode' in self.request.POST
else: else:
return True return True
@ -2655,7 +2655,7 @@ class DownloadView(PurchaseView):
return HttpResponse("Our attempt to set up your contribution failed. We have logged this problem.") return HttpResponse("Our attempt to set up your contribution failed. We have logged this problem.")
def get_form_kwargs(self): def get_form_kwargs(self):
if self.kwargs.has_key('work'): if 'work' in self.kwargs:
self.work = self.kwargs["work"] self.work = self.kwargs["work"]
self.show_beg = lambda: False self.show_beg = lambda: False
else: else:
@ -2669,7 +2669,7 @@ class DownloadView(PurchaseView):
} }
if self.request.method == 'POST': if self.request.method == 'POST':
self.data.update(self.request.POST.dict()) self.data.update(self.request.POST.dict())
if not self.request.POST.has_key('anonymous'): if not 'anonymous' in self.request.POST:
del self.data['anonymous'] del self.data['anonymous']
return {'data':self.data} return {'data':self.data}
else: else:
@ -2763,8 +2763,8 @@ class DownloadView(PurchaseView):
'action': "Contribution", 'action': "Contribution",
'user_license': self.user_license, 'user_license': self.user_license,
'lib_thanked': self.lib_thanked, 'lib_thanked': self.lib_thanked,
'amount': D(self.request.session.pop('amount')/100) if self.request.session.has_key('amount') else None, 'amount': D(self.request.session.pop('amount')/100) if 'amount' in self.request.session else None,
'testmode': self.request.GET.has_key('testmode') or self.request.POST.has_key('testmode'), 'testmode': 'testmode' in self.request.GET or 'testmode' in self.request.POST,
'source': self.request.GET.get('source', self.request.POST.get('source', '')), 'source': self.request.GET.get('source', self.request.POST.get('source', '')),
}) })
@ -3077,7 +3077,7 @@ def send_to_kindle(request, work_id, javascript='0'):
title = ebook.edition.work.kindle_safe_title() title = ebook.edition.work.kindle_safe_title()
context['ebook'] = ebook context['ebook'] = ebook
if request.POST.has_key('kindle_email'): if 'kindle_email' in request.POST:
kindle_email = request.POST['kindle_email'] kindle_email = request.POST['kindle_email']
try: try:
validate_email(kindle_email) validate_email(kindle_email)
@ -3122,7 +3122,7 @@ def send_to_kindle(request, work_id, javascript='0'):
logger.error('Unexpected error: %s', sys.exc_info()) logger.error('Unexpected error: %s', sys.exc_info())
return local_response(request, javascript, context, 1) return local_response(request, javascript, context, 1)
if request.POST.has_key('kindle_email') and not request.user.is_authenticated: if 'kindle_email' in request.POST and not request.user.is_authenticated:
return HttpResponseRedirect(reverse('superlogin')) return HttpResponseRedirect(reverse('superlogin'))
return local_response(request, javascript, context, 2) return local_response(request, javascript, context, 2)
@ -3147,7 +3147,7 @@ class LibModeView(FormView):
success_url = reverse_lazy('marc') success_url = reverse_lazy('marc')
def form_valid(self, form): def form_valid(self, form):
enable = form.data.has_key('enable') enable = 'enable' in form.data
if enable: if enable:
try: try:
libpref = self.request.user.libpref libpref = self.request.user.libpref

View File

@ -87,35 +87,35 @@ def get_edition_for_id(id_type, id_value, user=None):
return ident.edition if ident.edition else ident.work.preferred_edition return ident.edition if ident.edition else ident.work.preferred_edition
#need to make a new edition #need to make a new edition
if identifiers.has_key('goog'): if 'goog' in identifiers:
edition = add_by_googlebooks_id(identifiers['goog']) edition = add_by_googlebooks_id(identifiers['goog'])
if edition: if edition:
return user_edition(edition, user) return user_edition(edition, user)
if identifiers.has_key('isbn'): if 'isbn' in identifiers:
edition = add_by_isbn(identifiers['isbn']) edition = add_by_isbn(identifiers['isbn'])
if edition: if edition:
return user_edition(edition, user) return user_edition(edition, user)
if identifiers.has_key('doab'): if 'doab' in identifiers:
edition = add_by_doab(identifiers['doab']) edition = add_by_doab(identifiers['doab'])
if edition: if edition:
return user_edition(edition, user) return user_edition(edition, user)
if identifiers.has_key('oclc'): if 'oclc' in identifiers:
edition = add_by_oclc(identifiers['oclc']) edition = add_by_oclc(identifiers['oclc'])
if edition: if edition:
return user_edition(edition, user) return user_edition(edition, user)
if identifiers.has_key('glue'): if 'glue' in identifiers:
try: try:
work = models.safe_get_work(identifiers['glue']) work = models.safe_get_work(identifiers['glue'])
return work.preferred_edition return work.preferred_edition
except: except:
pass pass
if identifiers.has_key('http'): if 'http' in identifiers:
edition = add_by_webpage(identifiers['http'], user=user) edition = add_by_webpage(identifiers['http'], user=user)
return user_edition(edition, user) return user_edition(edition, user)
@ -217,7 +217,7 @@ def edit_edition(request, work_id, edition_id, by=None):
'title': title, 'title': title,
} }
if request.method == 'POST': if request.method == 'POST':
keep_editing = request.POST.has_key('add_author_submit') keep_editing = 'add_author_submit' in request.POST
form = None form = None
edition.new_authors = zip( edition.new_authors = zip(
request.POST.getlist('new_author'), request.POST.getlist('new_author'),
@ -226,32 +226,32 @@ def edit_edition(request, work_id, edition_id, by=None):
edition.new_subjects = request.POST.getlist('new_subject') edition.new_subjects = request.POST.getlist('new_subject')
if edition.id and admin: if edition.id and admin:
for author in edition.authors.all(): for author in edition.authors.all():
if request.POST.has_key('delete_author_%s' % author.id): if 'delete_author_%s' % author.id in request.POST:
edition.remove_author(author) edition.remove_author(author)
form = EditionForm(instance=edition, data=request.POST, files=request.FILES) form = EditionForm(instance=edition, data=request.POST, files=request.FILES)
keep_editing = True keep_editing = True
break break
work_rels = models.WorkRelation.objects.filter(Q(to_work=work) | Q(from_work=work)) work_rels = models.WorkRelation.objects.filter(Q(to_work=work) | Q(from_work=work))
for work_rel in work_rels: for work_rel in work_rels:
if request.POST.has_key('delete_work_rel_%s' % work_rel.id): if 'delete_work_rel_%s' % work_rel.id in request.POST:
work_rel.delete() work_rel.delete()
form = EditionForm(instance=edition, data=request.POST, files=request.FILES) form = EditionForm(instance=edition, data=request.POST, files=request.FILES)
keep_editing = True keep_editing = True
break break
activate_all = request.POST.has_key('activate_all_ebooks') activate_all = 'activate_all_ebooks' in request.POST
deactivate_all = request.POST.has_key('deactivate_all_ebooks') deactivate_all = 'deactivate_all_ebooks' in request.POST
ebookchange = False ebookchange = False
if request.POST.has_key('set_ebook_rights') and request.POST.has_key('set_rights'): if 'set_ebook_rights' in request.POST and 'set_rights' in request.POST:
rights = request.POST['set_rights'] rights = request.POST['set_rights']
for ebook in work.ebooks_all(): for ebook in work.ebooks_all():
ebook.rights = rights ebook.rights = rights
ebook.save() ebook.save()
ebookchange = True ebookchange = True
for ebook in work.ebooks_all(): for ebook in work.ebooks_all():
if request.POST.has_key('activate_ebook_%s' % ebook.id) or activate_all: if 'activate_ebook_%s' % ebook.id in request.POST or activate_all:
ebook.activate() ebook.activate()
ebookchange = True ebookchange = True
elif request.POST.has_key('deactivate_ebook_%s' % ebook.id) or deactivate_all: elif 'deactivate_ebook_%s' % ebook.id in request.POST or deactivate_all:
ebook.deactivate() ebook.deactivate()
ebookchange = True ebookchange = True
if ebookchange: if ebookchange:
@ -312,7 +312,7 @@ def edit_edition(request, work_id, edition_id, by=None):
work=work work=work
) )
for relator in edition.relators.all(): for relator in edition.relators.all():
if request.POST.has_key('change_relator_%s' % relator.id): if 'change_relator_%s' % relator.id in request.POST:
new_relation = request.POST['change_relator_%s' % relator.id] new_relation = request.POST['change_relator_%s' % relator.id]
relator.set(new_relation) relator.set(new_relation)
related_work = form.cleaned_data['add_related_work'] related_work = form.cleaned_data['add_related_work']
@ -324,7 +324,7 @@ def edit_edition(request, work_id, edition_id, by=None):
) )
for (author_name, author_relation) in edition.new_authors: for (author_name, author_relation) in edition.new_authors:
edition.add_author(author_name, author_relation) edition.add_author(author_name, author_relation)
if form.cleaned_data.has_key('bisac'): if 'bisac' in form.cleaned_data:
bisacsh = form.cleaned_data['bisac'] bisacsh = form.cleaned_data['bisac']
while bisacsh: while bisacsh:
Subject.set_by_name(bisacsh.full_label, work, authority="bisacsh") Subject.set_by_name(bisacsh.full_label, work, authority="bisacsh")

View File

@ -117,7 +117,7 @@ def rh_tools(request, template_name='rh_intro.html'):
for claim in claims: for claim in claims:
if claim.can_open_new: if claim.can_open_new:
if request.method == 'POST' and \ if request.method == 'POST' and \
request.POST.has_key('cl_%s-work' % claim.id) and \ 'cl_%s-work' % claim.id in request.POST and \
int(request.POST['cl_%s-work' % claim.id]) == claim.work_id : int(request.POST['cl_%s-work' % claim.id]) == claim.work_id :
claim.campaign_form = OpenCampaignForm( claim.campaign_form = OpenCampaignForm(
data = request.POST, data = request.POST,
@ -153,7 +153,7 @@ def rh_tools(request, template_name='rh_intro.html'):
if claim.campaign: if claim.campaign:
if claim.campaign.status in ['ACTIVE','INITIALIZED']: if claim.campaign.status in ['ACTIVE','INITIALIZED']:
e_m_key = 'edit_managers_%s' % claim.campaign.id e_m_key = 'edit_managers_%s' % claim.campaign.id
if request.method == 'POST' and request.POST.has_key(e_m_key): if request.method == 'POST' and e_m_key in request.POST:
claim.campaign.edit_managers_form = EditManagersForm( claim.campaign.edit_managers_form = EditManagersForm(
instance=claim.campaign, instance=claim.campaign,
data=request.POST, data=request.POST,
@ -174,7 +174,7 @@ def rh_tools(request, template_name='rh_intro.html'):
new_campaign = None new_campaign = None
for campaign in campaigns: for campaign in campaigns:
if campaign.clonable(): if campaign.clonable():
if request.method == 'POST' and request.POST.has_key('c%s-campaign_id'% campaign.id): if request.method == 'POST' and 'c%s-campaign_id'% campaign.id in request.POST:
clone_form = CloneCampaignForm(data=request.POST, prefix = 'c%s' % campaign.id) clone_form = CloneCampaignForm(data=request.POST, prefix = 'c%s' % campaign.id)
if clone_form.is_valid(): if clone_form.is_valid():
campaign.clone() campaign.clone()
@ -211,7 +211,7 @@ def manage_campaign(request, id, ebf=None, action='manage'):
offer.offer_form = OfferForm(instance=offer, prefix='offer_%d'%offer.id) offer.offer_form = OfferForm(instance=offer, prefix='offer_%d'%offer.id)
if request.method == 'POST' : if request.method == 'POST' :
if request.POST.has_key('add_premium') : if 'add_premium' in request.POST :
new_premium_form = CustomPremiumForm(data=request.POST) new_premium_form = CustomPremiumForm(data=request.POST)
if new_premium_form.is_valid(): if new_premium_form.is_valid():
new_premium_form.save() new_premium_form.save()
@ -221,7 +221,7 @@ def manage_campaign(request, id, ebf=None, action='manage'):
alerts.append(_('New premium has not been added')) alerts.append(_('New premium has not been added'))
form = ManageCampaignForm(instance=campaign) form = ManageCampaignForm(instance=campaign)
activetab = '#2' activetab = '#2'
elif request.POST.has_key('save') or request.POST.has_key('launch') : elif 'save' in request.POST or 'launch' in request.POST :
form = ManageCampaignForm(instance=campaign, data=request.POST) form = ManageCampaignForm(instance=campaign, data=request.POST)
if form.is_valid(): if form.is_valid():
form.save() form.save()
@ -250,9 +250,9 @@ def manage_campaign(request, id, ebf=None, action='manage'):
else: else:
alerts.append(_('Campaign has NOT been launched')) alerts.append(_('Campaign has NOT been launched'))
new_premium_form = CustomPremiumForm(initial={'campaign': campaign}) new_premium_form = CustomPremiumForm(initial={'campaign': campaign})
elif request.POST.has_key('inactivate') : elif 'inactivate' in request.POST :
activetab = '#2' activetab = '#2'
if request.POST.has_key('premium_id'): if 'premium_id' in request.POST:
premiums_to_stop = request.POST.getlist('premium_id') premiums_to_stop = request.POST.getlist('premium_id')
for premium_to_stop in premiums_to_stop: for premium_to_stop in premiums_to_stop:
selected_premium = models.Premium.objects.get(id=premium_to_stop) selected_premium = models.Premium.objects.get(id=premium_to_stop)
@ -262,9 +262,9 @@ def manage_campaign(request, id, ebf=None, action='manage'):
alerts.append(_('Premium %s has been inactivated'% premium_to_stop)) alerts.append(_('Premium %s has been inactivated'% premium_to_stop))
form = ManageCampaignForm(instance=campaign) form = ManageCampaignForm(instance=campaign)
new_premium_form = CustomPremiumForm(initial={'campaign': campaign}) new_premium_form = CustomPremiumForm(initial={'campaign': campaign})
elif request.POST.has_key('change_offer'): elif 'change_offer' in request.POST:
for offer in offers : for offer in offers :
if request.POST.has_key('offer_%d-work' % offer.id) : if 'offer_%d-work' % offer.id in request.POST :
offer.offer_form = OfferForm( offer.offer_form = OfferForm(
instance=offer, instance=offer,
data = request.POST, data = request.POST,

View File

@ -359,7 +359,7 @@ def edit_user(request, redirect_to=None):
request.user.username = form.cleaned_data['username'] request.user.username = form.cleaned_data['username']
request.user.save() request.user.save()
if 'set_password' in request.POST.keys() and \ if 'set_password' in request.POST.keys() and \
form.cleaned_data.has_key('set_password'): 'set_password' in form.cleaned_data:
if not request.user.has_usable_password(): if not request.user.has_usable_password():
request.user.set_password(form.cleaned_data['set_password']) request.user.set_password(form.cleaned_data['set_password'])
request.user.save() request.user.save()

View File

@ -27,7 +27,7 @@ for purchase in stripe_reader:
except Campaign.DoesNotExist: except Campaign.DoesNotExist:
print('missing campaign:'+ campaign_id) print('missing campaign:'+ campaign_id)
continue continue
if royalties_due.has_key(campaign.id): if campaign.id in royalties_due:
royalty_due = royalties_due[campaign.id].royalty_due royalty_due = royalties_due[campaign.id].royalty_due
else: else:
royalty_due = D(0) royalty_due = D(0)

View File

@ -353,7 +353,7 @@ class EPUB(zipfile.ZipFile):
element.text = value element.text = value
self.opf[0].append(element) self.opf[0].append(element)
# note that info is ignoring namespace entirely # note that info is ignoring namespace entirely
if self.info["metadata"].has_key(term): if term in self.info["metadata"]:
self.info["metadata"][term] = [self.info["metadata"][term] , value] self.info["metadata"][term] = [self.info["metadata"][term] , value]
else: else:
self.info["metadata"][term] = value self.info["metadata"][term] = value

View File

@ -81,9 +81,9 @@ def modify_rds_parameter(group_name, parameter, value, apply_immediate=False):
""" """
pg = rds.get_all_dbparameters(group_name) pg = rds.get_all_dbparameters(group_name)
while not pg.has_key(parameter) and hasattr(pg, 'Marker'): while not parameter in pg and hasattr(pg, 'Marker'):
pg = rds.get_all_dbparameters(group_name, marker = pg.Marker) pg = rds.get_all_dbparameters(group_name, marker = pg.Marker)
if pg.has_key(parameter): if parameter in pg:
pg[parameter].value = value pg[parameter].value = value
pg[parameter].apply(immediate=apply_immediate) pg[parameter].apply(immediate=apply_immediate)
return True return True