コード例 #1
0
ファイル: util.py プロジェクト: buechertisch/assam
def vorbestellungen_einlesen(vorbestellungsdatei):
    try:
        vorbestellungscsv = csv.reader(
            open(vorbestellungsdatei, 'rb'), delimiter=';')
        vorbestellungsheader = vorbestellungscsv.next()[1:]
    except Exception:
        vorbestellungscsv = []
        print ("Es konnten keine Vorbestellungen eingelesen werden. Die Datei",
               vorbestellungsdatei, "existiert nicht oder hat ein falsches Format.")
    vorbestellungen = {}
    zeile = 1
    for row in vorbestellungscsv:
        zeile += 1
        try:
            if row == []:
                continue
            if isbn.isValid(row[0]):
                if isbn.toI13(row[0]) not in vorbestellungen:
                    vorbestellungen[isbn.toI13(row[0])] = [row[1:]]
                else:
                    vorbestellungen[isbn.toI13(row[0])].append(row[1:])
            else:
                print ("Es ist ein Fehler beim Einlesen der Vorbestellungen "
                       "aufgetreten. Zeile {0} enthält keine gültige ISBN."
                       ).format(zeile)
        except Exception:
            print ("Es ist ein Fehler beim Einlesen der Vorbestellungen "
                   "aufgetreten. Zeile", zeile, "enthält einen Fehler.")
    return(vorbestellungsheader, vorbestellungen)
コード例 #2
0
ファイル: util.py プロジェクト: buechertisch/assam
def get_ort_zum_lesen(csv_file=ort_zum_lesen):
    try:
        ortzumlesencsv = csv.reader(open(csv_file, 'rb'), delimiter=',')
        ortzumlesenheader = ortzumlesencsv.next()[1:]
    except Exception:
        ortzumlesencsv = []
        ortzumlesenheader = []
        print ('Es konnte keine Liste für "Ein Ort zum Lesen" eingelesen '
               'werden. Die Datei', ort_zum_lesen, "existiert nicht oder "
               "hat ein falsches Format.")
    ortzumlesen = {}
    zeile = 1
    for row in ortzumlesencsv:
        zeile += 1
        try:
            if row == []:
                continue
            if isbn.isValid(row[0]):
                ortzumlesen[isbn.toI13(row[0])] = row[1:]
            else:
                print ('Es ist ein Fehler beim Einlesen der Liste für '
                       '"Ein Ort zum Lesen" aufgetreten. Zeile', zeile,
                       "enthält keine gültige ISBN.")
        except Exception:
            print ('Es ist ein Fehler beim Einlesen der Liste für "Ein Ort '
                   'zum Lesen" aufgetreten. Zeile', zeile, "enthält einen Fehler.")

    return ortzumlesenheader, ortzumlesen
コード例 #3
0
ファイル: util.py プロジェクト: buechertisch/assam
def get_blacklist(blacklist_file=schwarze_liste):
    try:
        blacklistcsv = csv.reader(open(blacklist_file, 'rb'), delimiter=';')
        blacklistheader = blacklistcsv.next()[1:]
    except Exception:
        blacklistcsv = []
        blacklistheader = []
        print ("Es konnte keine Schwarze Liste eingelesen werden. Die Datei"
               "{0} existiert nicht oder hat ein falsches Format.".format(schwarze_liste))
    blacklist = {}
    zeile = 1
    for row in blacklistcsv:
        zeile += 1
        try:
            if row == []:
                continue
            if isbn.isValid(row[0]):
                blacklist[isbn.toI13(row[0])] = row[1:]
            else:
                print ("Es ist ein Fehler beim Einlesen der Schwarzen Liste "
                       "aufgetreten. Zeile {0} enthält keine gültige ISBN.".format(zeile))
        except Exception:
            print ("Es ist ein Fehler beim Einlesen der Schwarzen Liste "
                   "aufgetreten. Zeile", zeile, "enthält einen Fehler.")

    return blacklistheader, blacklist
コード例 #4
0
 def getSRUdata(self, cisbn):
     cisbn=self.fix_isbn(cisbn)
     if (isbn.isValid(cisbn)):
         for server in self.SRU_servers.keys():
             data=url_cache.getURLdata(server %(cisbn,"dc"))
             if data:
                 data=lxml_lib.fromstring(data)
                 for child in data.getchildren():
                     if (child.tag.endswith("numberOfRecords")):
                         if (string.atoi(child.text)) > 0:
                             return(self._parse_dc_awnser(data, cisbn))
                             break
     return(False)
コード例 #5
0
ファイル: views.py プロジェクト: ratna1234/nerp
def isbn_to_record(request):
    isbn = request.POST.get('isbn')
    if isbn and isbnpy.isValid(isbn):
        if isbnpy.isI10(isbn):
            isbn = isbnpy.convert(isbn)
        try:
            record = Record.objects.get(isbn13=isbn)
        except Record.DoesNotExist:
            messages.error(request, 'Book not added yet, add it first!')
            return redirect(reverse_lazy('acquisition') + '?isbn=' + isbn)
        return redirect(reverse_lazy('view_record', kwargs={'pk': record.id}))
    else:
        messages.error(request, 'Invalid ISBN!')
        return redirect(reverse_lazy('library_index'))
コード例 #6
0
ファイル: views.py プロジェクト: ratna1234/nerp
def isbn_to_record(request):
    isbn = request.POST.get('isbn')
    if isbn and isbnpy.isValid(isbn):
        if isbnpy.isI10(isbn):
            isbn = isbnpy.convert(isbn)
        try:
            record = Record.objects.get(isbn13=isbn)
        except Record.DoesNotExist:
            messages.error(request, 'Book not added yet, add it first!')
            return redirect(reverse_lazy('acquisition') + '?isbn=' + isbn)
        return redirect(reverse_lazy('view_record', kwargs={'pk': record.id}))
    else:
        messages.error(request, 'Invalid ISBN!')
        return redirect(reverse_lazy('library_index'))
コード例 #7
0
ファイル: views.py プロジェクト: ratna1234/nerp
def save_outgoing(request):
    error = False
    transaction = Transaction.new()
    transaction.user_id = request.POST.get('user')
    transaction.borrow_date = request.POST.get('borrow_date')
    transaction.due_date = request.POST.get('due_date')
    transaction.record_id = request.POST.get('record')
    if request.POST.get('isbn'):
        isbn = request.POST.get('isbn')
        if isbnpy.isValid(isbn):
            if isbnpy.isI10(isbn):
                isbn = isbnpy.convert(isbn)
            try:
                transaction.record = Record.objects.get(isbn13=isbn)
            except Record.DoesNotExist:
                error = 'No books with provided ISBN in library database.'
        else:
            error = 'Invalid ISBN!'
        if error:
            raise Exception(error)
    transaction.save()
    messages.success(request, 'Checked Out!')
    return redirect(reverse_lazy('view_record', kwargs={'pk': transaction.record_id}))
コード例 #8
0
ファイル: views.py プロジェクト: ratna1234/nerp
def save_outgoing(request):
    error = False
    transaction = Transaction.new()
    transaction.user_id = request.POST.get('user')
    transaction.borrow_date = request.POST.get('borrow_date')
    transaction.due_date = request.POST.get('due_date')
    transaction.record_id = request.POST.get('record')
    if request.POST.get('isbn'):
        isbn = request.POST.get('isbn')
        if isbnpy.isValid(isbn):
            if isbnpy.isI10(isbn):
                isbn = isbnpy.convert(isbn)
            try:
                transaction.record = Record.objects.get(isbn13=isbn)
            except Record.DoesNotExist:
                error = 'No books with provided ISBN in library database.'
        else:
            error = 'Invalid ISBN!'
        if error:
            raise Exception(error)
    transaction.save()
    messages.success(request, 'Checked Out!')
    return redirect(
        reverse_lazy('view_record', kwargs={'pk': transaction.record_id}))
コード例 #9
0
ファイル: forms.py プロジェクト: cronco/lib_admin
	def clean_isbn(self):
		isbn_val = self.cleaned_data["isbn"]
		if isbn_val:
			if not isbn.isValid(isbn_val):
				raise ValidationError("The isbn you entered is not valid")
		return isbn_val
コード例 #10
0
ファイル: views.py プロジェクト: ratna1234/nerp
def save_acquisition(request):
    if request.POST.get('book').isnumeric():
        book = Book.objects.get(id=request.POST.get('book'))
        new_book = False
    else:
        book = Book(title=request.POST.get('book'))
        new_book = True
    book.subtitle = request.POST.get('subtitle')
    book.save()

    if request.POST.get('isbn'):
        isbn = request.POST.get('isbn')
        if isbnpy.isValid(isbn):
            if isbnpy.isI10(isbn):
                isbn = isbnpy.convert(isbn)
            try:
                record = Record.objects.get(isbn13=isbn)
                new_record = False
            except Record.DoesNotExist:
                record = Record(isbn13=isbn)
                new_record = True
    else:
        if not new_book:
            try:
                record = Record.objects.get(book=book,
                                            edition=request.POST.get('book'))
                new_record = False
            except Record.DoesNotExist:
                record = Record(book=book)
                new_record = True
        else:
            record = Record(book=book)
            new_record = True

    record.book = book
    record.format = request.POST.get('format')
    if record.format != 'ebook':
        if new_record:
            record.quantity = request.POST.get('quantity')
        else:
            record.quantity += int(request.POST.get('quantity'))

    record.excerpt = request.POST.get('excerpt')
    record.edition = request.POST.get('edition')
    record.notes = request.POST.get('notes')
    record.ddc = request.POST.get('ddc')
    record.lcc = request.POST.get('lcc')
    record.pagination = request.POST.get('pagination')
    record.format = request.POST.get('format')
    record.type = request.POST.get('type')
    if record.format != 'eBook':
        record.quantity = request.POST.get('quantity')

    record.publication_has_month = False
    record.publication_has_day = False
    if request.POST.get('year'):
        dt = datetime(int(request.POST.get('year')), 1, 1)
        if request.POST.get('month'):
            record.publication_has_month = True
            dt = dt.replace(month=int(request.POST.get('month')))
            if request.POST.get('day'):
                record.publication_has_day = True
                dt = dt.replace(day=int(request.POST.get('day')))
        record.date_of_publication = dt
    else:
        record.date_of_publication = None

    if request.FILES.get('small_cover'):
        record.small_cover = request.FILES.get('small_cover')
    if request.FILES.get('medium_cover'):
        record.medium_cover = request.FILES.get('medium_cover')
    if request.FILES.get('large_cover'):
        record.large_cover = request.FILES.get('large_cover')

    if not record.date_added:
        record.date_added = datetime.today()

    record.save()

    if request.FILES.get('ebook'):
        ebooks = request.FILES.getlist('ebook')
        for ebook in ebooks:
            ebook_file = BookFile(record=record, file=ebook)
            existing_files = record.ebooks(ebook_file.format)
            for existing_file in existing_files:
                existing_file.delete()
            ebook_file.save()

    book.subjects.clear()
    for subject in request.POST.getlist('subjects'):
        if subject.isnumeric():
            book.subjects.add(Subject.objects.get(id=subject))
        else:
            new_subject = Subject(name=subject)
            new_subject.save()
            book.subjects.add(new_subject)

    record.authors.clear()
    for author in request.POST.getlist('authors'):
        if author.isnumeric():
            record.authors.add(Author.objects.get(id=author))
        else:
            new_author = Author(name=author)
            new_author.save()
            record.authors.add(new_author)

    record.languages.clear()
    for language in request.POST.getlist('languages'):
        record.languages.add(Language.objects.get(id=language))

    publisher = request.POST.get('publisher')
    if publisher:
        if publisher.isnumeric():
            record.publisher_id = publisher
        else:
            new_publisher = Publisher(name=publisher)
            new_publisher.save()
            record.publisher = new_publisher

    record.save()

    return redirect(reverse_lazy('view_record', kwargs={'pk': record.id}))
コード例 #11
0
 def parse_item_vinabook(self, response):
     folder_name = response.meta['folder']
     uri = self.path + folder_name
     url_id = None
     matches = re.finditer(r"-p(.*)\.html", response.url)
     for matchNum, match in enumerate(matches):
         matchNum = matchNum + 1
         for groupNum in range(0, len(match.groups())):
             groupNum = groupNum + 1
             url_id = match.group(1)
     while (url_id.isdigit() == False):
         matches = re.finditer(r"-p(.*)", url_id)
         for matchNum, match in enumerate(matches):
             matchNum = matchNum + 1
             for groupNum in range(0, len(match.groups())):
                 groupNum = groupNum + 1
                 url_id = match.group(1)
     check = False
     for root, dirs, files in os.walk(uri):
         for file in files:
             file = file.replace(".json", "")
             if file == url_id:
                 check = True
                 break
         if check == True:
             break
     if check == False:
         list_description = response.xpath(
             '//div[@class="full-description"]/p').extract()
         book_description = ''
         for description in list_description:
             temp = self.cleanHTML(description.strip())
             if temp is not '' or temp != u'Mời bạn đón đọc.' or temp != u'mời bạn đón đọc.':
                 book_description = book_description + ' ' + temp
         book_name = response.xpath(
             '//*[@itemprop="name"]/text()').extract()[0].strip()
         info = response.xpath('//*[@class="product-feature"]/ul/li')
         book_img = ""
         book_ISBN = ""
         book_author = ""
         book_publisher = ""
         for li in info:
             key = li.xpath('strong/text()').extract_first().strip()
             if key == u'Mã Sản phẩm:':
                 book_ISBN = li.xpath('text()').extract()[1].strip()
             if key == u'Tác giả:':
                 value = li.xpath('a/text()').extract_first()
                 if value is not None:
                     book_author = value.strip()
                 else:
                     book_author = li.xpath(
                         'span/text()').extract_first().strip()
             if key == u'Nhà phát hành:':
                 value = li.xpath('a/text()').extract_first()
                 if value is not None:
                     book_publisher = value.strip()
                 else:
                     book_publisher = li.xpath(
                         'span/text()').extract_first().strip()
         if (book_ISBN is not ''):
             if (book_ISBN[0] == str(2)) or (book_ISBN[0]
                                             == str(8)) or (book_ISBN[0]
                                                            == str(9)):
                 if isbn.isValid(
                         book_ISBN) == True and book_description is not '':
                     book_img = response.xpath(
                         '//img[@id="det_img_' + url_id +
                         '"]/@src').extract_first().strip()
                     book_temp = {
                         'name': book_name,
                         'img': book_img,
                         'isbn': book_ISBN,
                         'author': book_author,
                         'publisher': book_publisher,
                         'description': book_description,
                         'class': folder_name
                     }
                     json.dump(book_temp,
                               open(uri + '/' + url_id + '.json', "wb"))
コード例 #12
0
import sys
import isbn
import components.db
conn=components.db.connect()

cursor=conn.cursor()

cursor.execute("SELECT * from title where isbn RLIKE '[0-9X][0-9X][0-9X][0-9X][0-9X][0-9X][0-9X][0-9X][0-9X][0-9X]'")

rows=cursor.fetchall()

total = 0

for r in rows:
	#print "Dealing with %s"  %r[1]
	if isbn.isValid(r[1]):
		prefix=r[1][:-1]
		cursor.execute("SELECT * from title where isbn RLIKE %s and not (isbn = %s)",('^%s' % prefix,r[1]))
		partial_matches=cursor.fetchall()
		if len(partial_matches)>1:
			print "WTF %s" % r[1]
		else: 
			if len(partial_matches)==1:
				print "FIXING ISBN r[1]"
				print "%s == %s?" % (r[2],partial_matches[0][2])
				print "%s == %s?" % (r[1],partial_matches[0][1])
				#grab bad_isbn
				#delete bad title entry
				#change
				cursor.execute("UPDATE author set title_id=%s where title_id=%s",(r[0],partial_matches[0][0]))
				cursor.execute("UPDATE author_title set title_id=%s where title_id=%s",(r[0],partial_matches[0][0]))
コード例 #13
0
ファイル: assam.py プロジェクト: buechertisch/assam
def main():
    interaktiv = True
    # Hier wird jedes _mögliche_ Plattformobjekt mit None-Werten initialisiert
    # weil die spaeter erwartet werden.
    global PF
    PF = Platforms()
    PF.create_available_platforms()

    # Gibt eins der möglichen Intros aus.
    print '\n' + 'Willkommen bei Assam - ' + intros[int(str(time.time())[-1]) % len(intros)] + '\n'

    vorbestellungsheader, vorbestellungen = vorbestellungen_einlesen(
        vorbestellungsdatei)
    # um evt. Fehlerzeilen in der Datei zu entfernen
    vorbestellungen_schreiben(vorbestellungsdatei, vorbestellungsheader, vorbestellungen)

    print "Es wurden", sum(len(vorbestellungen[isbn]) for isbn in vorbestellungen), "Vorbestellungen für", len(vorbestellungen), "verschiedene Titel eingelesen"

    blacklistheader, blacklist = get_blacklist()
    print "Es wurden", len(blacklist), "Einträge der Schwarzen Liste eingelesen"

    ortzumlesenheader, ortzumlesen = get_ort_zum_lesen()
    print "Es wurden", len(ortzumlesen), 'Einträge für "Ein Ort zum Lesen" eingelesen'

    global learners_mode, markt, tabelle, quittieren
    while 1:  # Während das Programm läuft
        if interaktiv:  # Interaktiver Modus
            while 1:  # Bis eine gültige Eingabe gemacht wurde
                print '_' * 80, '\n'
                eingabe = raw_input('ISBN: ')

                if eingabe == '':
                    continue

                elif isbn.isValid(eingabe):
                    my_isbn = isbn.toI13(eingabe)
                    if learners_mode:
                        print '\n' * 55
                    break

                elif 'vorbest' in eingabe.lower():
                    vorbestellungsheader, vorbestellungen = vorbestellungen_einlesen(
                        vorbestellungsdatei)
                    print 'Vorbestellung eingeben:'
                    key = ''
                    key = raw_input('ISBN? ')
                    while not isbn.isValid(key):
                        key = raw_input(
                            'Das war keine gültige ISBN. Bitte gib eine ISBN ein: ')
                    key = isbn.toI13(key)
                    neue_vorbestellung = []
                    if key not in vorbestellungen:
                        vorbestellungen[key] = []
                    for i in vorbestellungsheader:
                        if i == 'Bestelldatum':
                            neue_vorbestellung += [time.strftime('%d.%m.%Y')]
                        else:
                            neue_vorbestellung += [raw_input(i + '? ')]
                    vorbestellungen[key] += [neue_vorbestellung]
                    vorbestellungen_schreiben(vorbestellungsdatei, vorbestellungsheader, vorbestellungen)

                elif 'datei' in eingabe.lower():
                    try:
                        isbnquelle = re.search('.*? (.*)', eingabe).groups()[0]
                        isbndatei = open(isbnquelle, 'r')
                        ergebnisdatei = open(isbnquelle + '-ergebnisse.csv', 'w')
                        print >> ergebnisdatei, ';'.join([
                            'ISBN',
                            'Titel',
                            'Kategorien [1]',
                            'Kategorien [2]',
                            'Kategorien [3]'
                        ])
                        interaktiv = False
                        print 'Assam verarbeitet jetzt die ISBNs aus der Datei ' + isbnquelle + ':'
                        while 1:
                            # print 1
                            eingabe = isbndatei.next()
                            if isbn.isValid(eingabe):
                                # print 2
                                my_isbn = isbn.isbn_strip(eingabe)
                                # print 3
                                print ''
                                print my_isbn
                                break  # Aus dem  'while' vor 5 Zeilen ausbrechen
                        break  # Aus dem 2. 'while' oben ausbrechen

                    except Exception:
                        print 'Es gab einen Fehler mit der Datei.'

                elif eingabe in GEWICHTE:
                    buch.print_entscheidung(eingabe)
                    continue
                elif eingabe.lower() == 'ende':
                    exit()
                elif eingabe.lower() == 'hilfe':
                    print hilfetext
                elif eingabe.lower() == 'web':
                    for plattform in plattformen_requested:
                        url = 'http://' + \
                            eval(plattform.lower() + '.host') + \
                            eval(plattform.lower() + '.pfad')
                        webbrowser.open(url)
                        time.sleep(1)
                elif eingabe[0] == '-':
                    plattformbefehl = PF.remove_requested_platforms(eingabe)
                    if plattformbefehl:
                        continue
                    elif 'lern' in eingabe.lower():
                        learners_mode = False
                        tabelle = True
                        print 'Assam läuft nun im Profi-Modus. Mit "+ Lernen" schaltest Du den Lern-Modus wieder an.'
                    elif 'tabelle' in eingabe.lower():
                        tabelle = False
                        print 'Die Tabelle wird nun nicht mehr angezeigt. Mit "+ Tabelle" kannst du sie wieder aktivieren.'
                    elif 'quitt' in eingabe.lower():
                        if quittieren == True:
                            quittieren = False
                            print >> quittung, ';'.join(
                                ['', '', '', 'Summe:', '=summe(e2:e' + str(quittungsposten) + ')'])
                            quittung.close()
                            print 'Die Quittung wurde beendet. Sie steht in der Datei "Quittung.csv".'
                        else:
                            print 'Es wird derzeit keine Quittung erstellt.'
                    elif 'l50' in eingabe.lower():
                        markt = False
                        print 'Die Kategorie "L50" wird nun nicht mehr berücksichtigt.'
                    else:
                        print 'Diesen Befehl versteht Assam nicht. Tippe "Hilfe" um zu erfahren welche Befehle es gibt.'

                elif eingabe[0] == '+':
                    plattformbefehl = False
                    # Alle ursprünglich vorhandenen Plattformen testen.
                    for plattform in plattformen_available:
                        if plattform.lower() in eingabe.lower():
                            plattformbefehl = True
                            if plattform in plattformen_requested:
                                print plattform, 'wird bereits angefragt.'
                            else:
                                plattformen_requested.append(plattform)
                                print plattform, 'wird nun wieder angefragt.'
                    if plattformbefehl:
                        continue
                    elif 'lern' in eingabe.lower():
                        learners_mode = True
                        tabelle = False
                        print 'Assam läuft nun im Lern-Modus. Mit "- Lernen" wechselst Du zum Profi-Modus.'
                    elif 'tabelle' in eingabe.lower():
                        tabelle = True
                        print 'Die Tabelle wird ab nun immer angezeigt. Mit "- Tabelle" kannst du sie wieder deaktivieren.\n'
                        print_gewinntabelle()
                    elif 'quitt' in eingabe.lower():
                        if quittieren == False:
                            quittieren = True
                            quittungsposten = 1
                            quittung = open(quittungsdatei, 'w')
                            print >> quittung, ';'.join(
                                ['Nr.', 'ISBN', 'Titel', 'Ausgabe', 'Wert'])
                            print 'Die folgenden Eingaben werden in eine Quittung geschrieben. "-Quittung" schließt sie ab, die Einträge stehen in der Datei "Quittung.csv".'
                        else:
                            print 'Die Eingaben werden bereits in eine Quittung geschrieben. Schließe sie mit "-Quittung" ab und sichere ggf. ihren Inhalt bevor Du eine neue beginnst.'
                    elif 'l50' in eingabe.lower():
                        markt = True
                        print 'Die Kategorie "L50" wird nun wieder angegeben'
                    else:
                        print 'Diesen Befehl versteht Assam nicht. Tippe "Hilfe" um zu erfahren welche Befehle es gibt.'

                else:
                    print 'Die ISBN scheint falsch zu sein...'

        else:  # Bei ISBNs aus Datei (non-interaktiver Modus)
            try:
                while 1:
                    eingabe = isbndatei.next()
                    if isbn.isValid(eingabe):
                        my_isbn = isbn.isbn_strip(eingabe)
                        print my_isbn
                        break
                    else:
                        continue
            except Exception:
                interaktiv = True
                ergebnisdatei.close()
                print '\nFertig!'
                continue

        # Alle Objekte initialisieren
        buch = Buch()  # mit leeren Attributen

        PF.create_and_start_requested_platforms(isbn=my_isbn)

        # Jede Plattform wird frühestens dann gejoint wenn die Antwort der
        # vorangegangenen Plattform vollständig ist. Überschreitet eine Plattform
        # das Zeitlimit, erscheinen alle folgenden auch verzögert. Die Warnung ist
        # aber nur dann gerechtfertigt wenn sie über die fremdverschuldete
        # Verzögerung hinaus länger brauchen.
        time_warning_alt = 0
        for plattformobjekt in PF.plattformen_created:
            plattformobjekt.join()
            plattformobjekt.Dauer = (round(time.time() - plattformobjekt.Start, 1))
            if plattformobjekt.Dauer > max(time_warning, time_warning_alt):
                time_warning_alt = plattformobjekt.Dauer
                plattformobjekt.Kommentar += 'Lange Antwortzeit (' + str(
                    plattformobjekt.Dauer).replace('.', ',') + ' sec). '

        buch.start(markt)  # Füllt die Attribute von buch mit Werten

        if interaktiv:
            print ''
            print_title()
            if tabelle:
                print_gewinntabelle()
            buch.print_UVP()
            if buch.gewichtsrelevanz:
                while 1:
                    gewicht = raw_input(
                        'Das Ergebnis ist gewichtsabhängig, bitte gib die Gewichtsklasse an (<450g: 1, 450-950g: 2, >950g: 3.): ')
                    if gewicht == '':
                        gewicht = '1'
                    if gewicht in GEWICHTE:
                        print ''
                        break
            else:
                gewicht = '1'
            buch.print_entscheidung(gewicht)

            if my_isbn in blacklist:
                print '\n\x1b[30;31mAchtung, dieses Buch steht auf der schwarzen Liste!\x1b[0m'
                for i in range(len(blacklistheader)):
                    print '%-20s' % (blacklistheader[i] + ':') + blacklist[my_isbn][i]

            if my_isbn in ortzumlesen:
                print '\nDieses Buch könnte für "Ein Ort zum Lesen" interessant sein'
                for i in range(len(ortzumlesenheader)):
                    print '%-20s' % (ortzumlesenheader[i] + ':') + ortzumlesen[my_isbn][i]

            if my_isbn in vorbestellungen:
                # Neu einlesen falls es zwischenzeitlich Änderungen gab (und vor
                # allem weil wieder geschrieben werden wird)
                vorbestellungsheader, vorbestellungen = vorbestellungen_einlesen(
                    vorbestellungsdatei)
            if my_isbn in vorbestellungen:
                print ''
                einfach = False
                if len(vorbestellungen[my_isbn]) == 1:
                    einfach = True
                    print 'Es gibt eine Vorbestellung für dieses Buch:\n'
                    for i in range(len(vorbestellungsheader)):
                        print '%-20s' % (vorbestellungsheader[i] + ':') + vorbestellungen[my_isbn][0][i]

                else:
                    print 'Es gibt', len(vorbestellungen[my_isbn]), 'Vorbestellungen für dieses Buch:'
                    for i in range(len(vorbestellungen[my_isbn])):
                        print '\nVorbestellung', str(i + 1) + ':'
                        for j in range(len(vorbestellungsheader)):
                            print '%-20s' % (vorbestellungsheader[j] + ':') + vorbestellungen[my_isbn][i][j]

                print ''
                drucken = ''
                while drucken not in ('j', 'n'):  # Druckentscheidung
                    # das erste Zeichen in Lowercase, falls es existiert.
                    drucken = raw_input('Möchtest Du ' + ('die' if einfach else 'eine') +
                                        ' Vorbestellung drucken (Ja/Nein)? ')[:1].lower()
                if drucken == 'j':
                    if einfach:
                        drucken = '1'
                    # ggf. Auswahl
                    while drucken not in [str(x) for x in range(1, len(vorbestellungen[my_isbn]) + 1)]:
                        drucken = raw_input(
                            'Welche Vorbestellung möchtest Du drucken (Nummer von 1 bis ' + str(len(vorbestellungen[my_isbn])) + ')? ')
                    drucken = int(drucken)
                    mitarbeiter = raw_input(
                        'Mit welchem Namen möchtest Du im Laufzettel stehen? ')

                print ''
                loeschen = ''
                # Löschentscheidung für den Eintrag von eben (einzigen oder
                # ausgewählten)
                while loeschen not in ('j', 'n'):
                    loeschen = raw_input('Möchtest Du ' + ('diese' if (einfach or drucken != 'n')
                                                           else 'eine') + ' Vorbestellung löschen (Ja/Nein)? ')[:1].lower()
                if loeschen == 'j':
                    if einfach:
                        loeschen = 1
                    elif drucken != 'n':
                        loeschen = drucken
                    else:
                        while str(loeschen) not in [str(x) for x in range(1, len(vorbestellungen[my_isbn]) + 1)]:
                            loeschen = raw_input(
                                'Welche Vorbestellung möchtest Du löschen (Nummer von 1 bis ' + str(len(vorbestellungen[my_isbn])) + ')? ')
                        loeschen = int(loeschen)

                if drucken in range(1, len(vorbestellungen[my_isbn]) + 1):
                    dateiname = laufzettelpfad + 'Laufzettel_' + ''.join(x for x in (PF.amazon.Titel or PF.easyankauf.Titel or 'Unbekannter Titel ').replace(
                        ' ', '-') if x.isalnum() or x == '-')[0:18] + '...' + str(int(time.time()))[6:] + '.txt'
                    laufzettel = open(dateiname, 'w')
                    laufzettel.write(
                        '-Laufzettel-\nDieses Buch passt auf eine Vorbestellung und kommt aus der Vorrecherche.\n\n')
                    laufzettel.write('%-20s' % 'Datum:' +
                                     time.strftime('%d.%m.%Y') + '\n')
                    laufzettel.write('%-20s' % 'Gefunden von:' +
                                     mitarbeiter + '\n\n')

                    laufzettel.write('Gefundenes Buch:\n')
                    laufzettel.write('%-20s' % 'ISBN:' + my_isbn +
                                     ' / ' + isbn.convert(my_isbn) + '\n')
                    laufzettel.write(
                        '%-20s' % 'Titel:' + (PF.amazon.Titel or PF.easyankauf.Titel or 'Unbekannter Titel ') + '\n')
                    laufzettel.write('%-20s' % 'Ladenpreisempf.:' +
                                     (float_to_string(buch.UVP) + "¤" if buch.UVP else '/') + '\n\n')

                    laufzettel.write('Bestelltes Buch:\n')
                    for i in range(len(vorbestellungsheader)):
                        print >> laufzettel, '%-20s' % (vorbestellungsheader[i] + ':') + vorbestellungen[
                            my_isbn][drucken - 1][i]
                    laufzettel.write('\n' + '%-20s' % 'Aus Assam gelöscht?' +
                                     ('Nein' if loeschen == 'n' else 'Ja') + '\n\n')

                    laufzettel.write('%-20s' % 'Kunde informiert am' + '...\n')
                    laufzettel.write('%-20s' % 'durch' + '...\n')
                    laufzettel.close()

                # if loeschen !='n':
                    # vorbestellungen[my_isbn].pop(loeschen-1)
                    # with open('vorbestellungen.csv', 'wb') as vorbestellungscsv:
                    #csvwriter = csv.writer(vorbestellungscsv, delimiter=';',quotechar='"', quoting=csv.QUOTE_ALL)
                    # csvwriter.writerow(vorbestellungsheader)
                    # for vorbest_isbn in vorbestellungen:
                    # for vorbestellung in vorbestellungen[vorbest_isbn]:
                    #vorbestellungscsv.write(vorbest_isbn+ ';')
                    # csvwriter.writerow(vorbestellung)

                if loeschen != 'n':
                    vorbestellungen[my_isbn].pop(loeschen - 1)
                    vorbestellungen_schreiben(vorbestellungsdatei, vorbestellungsheader, vorbestellungen)

                # andere_loeschen=''
                # if not einfach and andere_loeschen != 'n':
                    # while andere_loeschen not in ('j', 'n'): # Löschentscheidung für weiteren Eintrag
                    #andere_loeschen = raw_input('Möchtest Du eine ' + ('andere' if loeschen =='n' else 'weitere') + ' Vorbestellung löschen? ')[:1].lower()

                    # if andere_loeschen=='j':
                    # print 'loesch...' #eig. loeschprozess von Nr x

        else:
            print >> ergebnisdatei, ';'.join([
                my_isbn,
                (PF.amazon.Titel or PF.easyankauf.Titel or 'Unbekannter Titel ').replace(';', ','),
                ' '.join(buch.Entscheidung['1']),
                (' '.join(buch.Entscheidung['2']) if (
                    ' '.join(buch.Entscheidung['2']) != ' '.join(buch.Entscheidung['1'])) else ''),
                (' '.join(buch.Entscheidung['3']) if (
                    ' '.join(buch.Entscheidung['3']) != ' '.join(buch.Entscheidung['2'])) else ''),
            ])

            #(' '.join(Entscheidung['2']) if (' '.join(Entscheidung['2']) != ' '.join(Entscheidung['1']))),
        if quittieren:
            print >> quittung, ';'.join([
                str(quittungsposten),
                my_isbn + ' / ' + isbn.convert(my_isbn),
                (PF.amazon.Titel or PF.easyankauf.Titel or 'Unbekannter Titel ').replace(';', ','),
                (PF.amazon.Ausgabe or PF.easyankauf.Ausgabe or 'Unbekannte Ausgabe').replace(
                    ';', ','),
                float_to_string(min(buch.Preise)) if buch.Preise else '???'
            ])
            quittungsposten += 1
コード例 #14
0
 def is_isbn_valid(self, isbn):
     if not isValid(isbn):
         raise ValidationError("The ISBN entered is not valid.")
コード例 #15
0
def is_isbn(text):
    return isbn.isValid(str(text))
コード例 #16
0
 def is_isbn_valid(self, isbn):
     if not isValid(isbn):
         raise ValidationError("The ISBN entered is not valid.")
コード例 #17
0
ファイル: views.py プロジェクト: ratna1234/nerp
def acquisition(request):
    record_data = {}
    record = None

    if request.GET.get('isbn'):
        isbn = request.GET.get('isbn')
        if isbnpy.isValid(isbn):
            url = 'http://openlibrary.org/api/volumes/brief/json/isbn:' + isbn
            response = urllib2.urlopen(url)
            # response = urllib2.urlopen('http://127.0.0.1/json/3.json')
            data = json.load(response)
            if isbnpy.isI10(isbn):
                isbn = isbnpy.convert(isbn)
            if data == {}:
                record_data['isbn13'] = isbn
                record_form = RecordForm(instance=record)
                return render(request, 'acquisition.html', {
                    'data': record_data,
                    'form': record_form
                })
            data = data.itervalues().next()['records'].itervalues().next()

            try:
                record = Record.objects.get(isbn13=isbn)
                new_record = False
            except Record.DoesNotExist:
                record = Record(isbn13=isbn)
                new_record = True
                # pp(data)
            if record.book_id:
                book = record.book
            else:
                book = Book()

            book.title = data['data']['title']
            if data['details']['details'].has_key('subtitle'):
                book.subtitle = data['details']['details']['subtitle']
            book.save()

            if data['details']['details'].has_key('pagination'):
                record.pagination = data['data']['pagination']
            elif data['details']['details'].has_key('number_of_pages'):
                record.pagination = str(
                    data['data']['number_of_pages']) + ' p.'

            if data['details']['details'].has_key('physical_format'):
                record.format = data['details']['details']['physical_format']
                if record.format.startswith('electronic'):
                    record.format = 'eBook'
                    # record.openlibrary_url = data['data']['url']

            if data['details']['details'].has_key('weight'):
                record.weight = data['details']['details'].get('weight')
            if data['details']['details'].has_key('physical_dimensions'):
                record.dimensions = data['details']['details'].get(
                    'physical_dimensions')

            if data['data'].has_key('classifications'):
                if data['data']['classifications'].has_key(
                        'dewey_decimal_class'):
                    record.ddc = data['data']['classifications'].get(
                        'dewey_decimal_class')[0]
                if data['data']['classifications'].has_key(
                        'lc_classifications'):
                    record.lcc = data['data']['classifications'].get(
                        'lc_classifications')[0]

            try:
                record.date_of_publication = datetime.strptime(
                    data['data']['publish_date'], '%B %d, %Y').date()
                record.publication_has_month = True
                record.publication_has_day = True
            except ValueError:
                try:
                    record.date_of_publication = datetime.strptime(
                        data['data']['publish_date'], '%Y').date()
                    record.publication_has_month = False
                    record.publication_has_day = False
                except ValueError:
                    try:
                        record.date_of_publication = datetime.strptime(
                            data['data']['publish_date'], '%B %Y').date()
                        record.publication_has_day = False
                        record.publication_has_month = True
                    except ValueError:
                        record.date_of_publication = datetime.strptime(
                            data['data']['publish_date'], '%m/%d/%Y').date()
                        record.publication_has_day = True
                        record.publication_has_month = True

            if data['data'].has_key('identifiers'):
                if data['data']['identifiers'].has_key('openlibrary'):
                    record.openlibrary_id = data['data']['identifiers'][
                        'openlibrary'][0]
                if data['data']['identifiers'].has_key('goodreads'):
                    record.goodreads_id = data['data']['identifiers'][
                        'goodreads'][0]
                if data['data']['identifiers'].has_key('librarything'):
                    record.librarything_id = data['data']['identifiers'][
                        'librarything'][0]
                if data['data']['identifiers'].has_key('oclc'):
                    record.oclc_id = data['data']['identifiers']['oclc'][0]
                if data['data']['identifiers'].has_key('lccn'):
                    record.lccn_id = data['data']['identifiers']['lccn'][0]

            if data['data'].has_key('by_statement'):
                record.by_statement = data['data'].get('by_statement')

            if data['data'].has_key('notes'):
                record.notes = data['data'].get('notes')

            if data['data'].has_key('excerpts'):
                record.excerpt = data['data'].get('excerpts')[0].get('text')

            record.book = book

            setting = LibrarySetting.get()
            record.type = setting.default_type

            if new_record:
                record.date_added = datetime.today()
            record.save()

            if data['details']['details'].has_key('languages'):
                record.languages.clear()
                for lang in data['details']['details']['languages']:
                    lang_key = lang['key'].replace('/languages/', '')
                    try:
                        book_lang = Language.objects.get(code=lang_key)
                    except Language.DoesNotExist:
                        try:
                            book_lang = Language.objects.get(
                                code=lang_key[:-1])
                        except Language.DoesNotExist:
                            raise Exception(
                                "Please add a language with code " + lang_key +
                                " or " + lang_key[:-1] + " first!")
                    record.languages.add(book_lang)

            if data['data'].has_key('publish_places'):
                record.published_places.clear()
                for place in data['data']['publish_places']:
                    try:
                        published_place = Place.objects.get(name=place['name'])
                    except Place.DoesNotExist:
                        published_place = Place(name=place['name'])
                    published_place.save()
                    record.published_places.add(published_place)

            record.authors.clear()
            if data['details']['details'].has_key('authors'):
                for author in data['details']['details']['authors']:
                    author_key = author['key'].replace('/authors/', '')
                    try:
                        book_author = Author.objects.get(identifier=author_key)
                    except Author.DoesNotExist:
                        book_author = Author(identifier=author_key)
                    book_author.name = author['name']
                    book_author.save()
                    record.authors.add(book_author)
            elif data['data'].has_key('authors'):
                for author in data['data']['authors']:
                    author_key = author['url'].replace(
                        'http://openlibrary.org/authors/', '')
                    try:
                        book_author = Author.objects.get(identifier=author_key)
                    except Author.DoesNotExist:
                        book_author = Author(identifier=author_key)
                    book_author.name = author['name']
                    book_author.save()
                    record.authors.add(book_author)

            if data['data'].has_key('ebooks'):
                if data['data']['ebooks'][0].has_key('formats'):
                    formats = data['data']['ebooks'][0]['formats']
                    for book_format in formats:
                        ebooks = record.ebooks(book_format)
                        for ebook in ebooks:
                            ebook.delete()
                        if formats[book_format].has_key('url'):
                            url = formats[book_format].get('url')
                            result = urllib.urlretrieve(url)
                            book_file = BookFile(record=record)
                            book_file.file.save(os.path.basename(url),
                                                File(open(result[0])))
                            book_file.save()

            subjects = None
            if data['details']['details'].has_key('subjects'):
                subjects = data['details']['details']['subjects']
            elif data['data'].has_key('subjects'):
                subjects = data['data']['subjects']
            if subjects:
                record.book.subjects.clear()
                for subject in subjects:
                    if type(subject) == dict:
                        subject = title_case(subject['name'])
                    try:
                        book_subject = Subject.objects.get(name=subject)
                    except Subject.DoesNotExist:
                        book_subject = Subject(name=subject)
                    book_subject.save()
                    record.book.subjects.add(book_subject)

            # record.publishers.clear()
            # for publisher in data['details']['details']['publishers']:
            #     try:
            #         book_publisher = Publisher.objects.get(name=publisher['name'])
            #     except Publisher.DoesNotExist:
            #         book_publisher = Publisher(name=publisher['name'])
            #         book_publisher.save()
            #     record.publishers.add(book_publisher)
            try:
                book_publisher = Publisher.objects.get(
                    name=data['details']['details']['publishers'][0])
            except Publisher.DoesNotExist:
                book_publisher = Publisher(
                    name=data['details']['details']['publishers'][0])
                book_publisher.save()
            record.publisher = book_publisher

            if data['data'].has_key('cover'):

                if data['data']['cover'].has_key('large'):
                    cover_url = data['data']['cover']['large']
                    result = urllib.urlretrieve(cover_url)
                    record.large_cover.save(os.path.basename(cover_url),
                                            File(open(result[0])))
                if data['data']['cover'].has_key('medium'):
                    cover_url = data['data']['cover']['medium']
                    result = urllib.urlretrieve(cover_url)
                    record.medium_cover.save(os.path.basename(cover_url),
                                             File(open(result[0])))

                if data['data']['cover'].has_key('small'):
                    cover_url = data['data']['cover']['small']
                    result = urllib.urlretrieve(cover_url)
                    record.small_cover.save(os.path.basename(cover_url),
                                            File(open(result[0])))

            # thumbnail_url = data['details']['thumbnail_url']
            # result = urllib.urlretrieve(thumbnail_url)
            # record.thumbnail.save(
            #     os.path.basename(thumbnail_url),
            #     File(open(result[0]))
            # )

            # import pdb
            #
            # pdb.set_trace()
            record_data = RecordSerializer(record).data

    record_form = RecordForm(instance=record)

    return render(request, 'acquisition.html', {
        'data': record_data,
        'form': record_form
    })
コード例 #18
0
ファイル: views.py プロジェクト: ratna1234/nerp
def save_acquisition(request):
    if request.POST.get('book').isnumeric():
        book = Book.objects.get(id=request.POST.get('book'))
        new_book = False
    else:
        book = Book(title=request.POST.get('book'))
        new_book = True
    book.subtitle = request.POST.get('subtitle')
    book.save()

    if request.POST.get('isbn'):
        isbn = request.POST.get('isbn')
        if isbnpy.isValid(isbn):
            if isbnpy.isI10(isbn):
                isbn = isbnpy.convert(isbn)
            try:
                record = Record.objects.get(isbn13=isbn)
                new_record = False
            except Record.DoesNotExist:
                record = Record(isbn13=isbn)
                new_record = True
    else:
        if not new_book:
            try:
                record = Record.objects.get(book=book, edition=request.POST.get('book'))
                new_record = False
            except Record.DoesNotExist:
                record = Record(book=book)
                new_record = True
        else:
            record = Record(book=book)
            new_record = True

    record.book = book
    record.format = request.POST.get('format')
    if record.format != 'ebook':
        if new_record:
            record.quantity = request.POST.get('quantity')
        else:
            record.quantity += int(request.POST.get('quantity'))

    record.excerpt = request.POST.get('excerpt')
    record.edition = request.POST.get('edition')
    record.notes = request.POST.get('notes')
    record.ddc = request.POST.get('ddc')
    record.lcc = request.POST.get('lcc')
    record.pagination = request.POST.get('pagination')
    record.format = request.POST.get('format')
    record.type = request.POST.get('type')
    if record.format != 'eBook':
        record.quantity = request.POST.get('quantity')

    record.publication_has_month = False
    record.publication_has_day = False
    if request.POST.get('year'):
        dt = datetime(int(request.POST.get('year')), 1, 1)
        if request.POST.get('month'):
            record.publication_has_month = True
            dt = dt.replace(month=int(request.POST.get('month')))
            if request.POST.get('day'):
                record.publication_has_day = True
                dt = dt.replace(day=int(request.POST.get('day')))
        record.date_of_publication = dt
    else:
        record.date_of_publication = None

    if request.FILES.get('small_cover'):
        record.small_cover = request.FILES.get('small_cover')
    if request.FILES.get('medium_cover'):
        record.medium_cover = request.FILES.get('medium_cover')
    if request.FILES.get('large_cover'):
        record.large_cover = request.FILES.get('large_cover')

    if not record.date_added:
        record.date_added = datetime.today()

    record.save()

    if request.FILES.get('ebook'):
        ebooks = request.FILES.getlist('ebook')
        for ebook in ebooks:
            ebook_file = BookFile(record=record, file=ebook)
            existing_files = record.ebooks(ebook_file.format)
            for existing_file in existing_files:
                existing_file.delete()
            ebook_file.save()

    book.subjects.clear()
    for subject in request.POST.getlist('subjects'):
        if subject.isnumeric():
            book.subjects.add(Subject.objects.get(id=subject))
        else:
            new_subject = Subject(name=subject)
            new_subject.save()
            book.subjects.add(new_subject)

    record.authors.clear()
    for author in request.POST.getlist('authors'):
        if author.isnumeric():
            record.authors.add(Author.objects.get(id=author))
        else:
            new_author = Author(name=author)
            new_author.save()
            record.authors.add(new_author)

    record.languages.clear()
    for language in request.POST.getlist('languages'):
        record.languages.add(Language.objects.get(id=language))

    publisher = request.POST.get('publisher')
    if publisher:
        if publisher.isnumeric():
            record.publisher_id = publisher
        else:
            new_publisher = Publisher(name=publisher)
            new_publisher.save()
            record.publisher = new_publisher

    record.save()

    return redirect(reverse_lazy('view_record', kwargs={'pk': record.id}))
コード例 #19
0
 def wrapper(isbn, *args, **kwargs):
     if not isValid(isbn):
         raise ValueError('Invalid ISBN')
     return function(isbn, *args, **kwargs)
コード例 #20
0
ファイル: views.py プロジェクト: ratna1234/nerp
def acquisition(request):
    record_data = {}
    record = None

    if request.GET.get('isbn'):
        isbn = request.GET.get('isbn')
        if isbnpy.isValid(isbn):
            url = 'http://openlibrary.org/api/volumes/brief/json/isbn:' + isbn
            response = urllib2.urlopen(url)
            # response = urllib2.urlopen('http://127.0.0.1/json/3.json')
            data = json.load(response)
            if isbnpy.isI10(isbn):
                isbn = isbnpy.convert(isbn)
            if data == {}:
                record_data['isbn13'] = isbn
                record_form = RecordForm(instance=record)
                return render(request, 'acquisition.html', {'data': record_data, 'form': record_form})
            data = data.itervalues().next()['records'].itervalues().next()

            try:
                record = Record.objects.get(isbn13=isbn)
                new_record = False
            except Record.DoesNotExist:
                record = Record(isbn13=isbn)
                new_record = True
                # pp(data)
            if record.book_id:
                book = record.book
            else:
                book = Book()

            book.title = data['data']['title']
            if data['details']['details'].has_key('subtitle'):
                book.subtitle = data['details']['details']['subtitle']
            book.save()

            if data['details']['details'].has_key('pagination'):
                record.pagination = data['data']['pagination']
            elif data['details']['details'].has_key('number_of_pages'):
                record.pagination = str(data['data']['number_of_pages']) + ' p.'

            if data['details']['details'].has_key('physical_format'):
                record.format = data['details']['details']['physical_format']
                if record.format.startswith('electronic'):
                    record.format = 'eBook'
                    # record.openlibrary_url = data['data']['url']

            if data['details']['details'].has_key('weight'):
                record.weight = data['details']['details'].get('weight')
            if data['details']['details'].has_key('physical_dimensions'):
                record.dimensions = data['details']['details'].get('physical_dimensions')

            if data['data'].has_key('classifications'):
                if data['data']['classifications'].has_key('dewey_decimal_class'):
                    record.ddc = data['data']['classifications'].get('dewey_decimal_class')[0]
                if data['data']['classifications'].has_key('lc_classifications'):
                    record.lcc = data['data']['classifications'].get('lc_classifications')[0]

            try:
                record.date_of_publication = datetime.strptime(data['data']['publish_date'], '%B %d, %Y').date()
                record.publication_has_month = True
                record.publication_has_day = True
            except ValueError:
                try:
                    record.date_of_publication = datetime.strptime(data['data']['publish_date'], '%Y').date()
                    record.publication_has_month = False
                    record.publication_has_day = False
                except ValueError:
                    try:
                        record.date_of_publication = datetime.strptime(data['data']['publish_date'], '%B %Y').date()
                        record.publication_has_day = False
                        record.publication_has_month = True
                    except ValueError:
                        record.date_of_publication = datetime.strptime(data['data']['publish_date'], '%m/%d/%Y').date()
                        record.publication_has_day = True
                        record.publication_has_month = True

            if data['data'].has_key('identifiers'):
                if data['data']['identifiers'].has_key('openlibrary'):
                    record.openlibrary_id = data['data']['identifiers']['openlibrary'][0]
                if data['data']['identifiers'].has_key('goodreads'):
                    record.goodreads_id = data['data']['identifiers']['goodreads'][0]
                if data['data']['identifiers'].has_key('librarything'):
                    record.librarything_id = data['data']['identifiers']['librarything'][0]
                if data['data']['identifiers'].has_key('oclc'):
                    record.oclc_id = data['data']['identifiers']['oclc'][0]
                if data['data']['identifiers'].has_key('lccn'):
                    record.lccn_id = data['data']['identifiers']['lccn'][0]

            if data['data'].has_key('by_statement'):
                record.by_statement = data['data'].get('by_statement')

            if data['data'].has_key('notes'):
                record.notes = data['data'].get('notes')

            if data['data'].has_key('excerpts'):
                record.excerpt = data['data'].get('excerpts')[0].get('text')

            record.book = book

            setting = LibrarySetting.get()
            record.type = setting.default_type

            if new_record:
                record.date_added = datetime.today()
            record.save()

            if data['details']['details'].has_key('languages'):
                record.languages.clear()
                for lang in data['details']['details']['languages']:
                    lang_key = lang['key'].replace('/languages/', '')
                    try:
                        book_lang = Language.objects.get(code=lang_key)
                    except Language.DoesNotExist:
                        try:
                            book_lang = Language.objects.get(code=lang_key[:-1])
                        except Language.DoesNotExist:
                            raise Exception(
                                "Please add a language with code " + lang_key + " or " + lang_key[:-1] + " first!")
                    record.languages.add(book_lang)

            if data['data'].has_key('publish_places'):
                record.published_places.clear()
                for place in data['data']['publish_places']:
                    try:
                        published_place = Place.objects.get(name=place['name'])
                    except Place.DoesNotExist:
                        published_place = Place(name=place['name'])
                    published_place.save()
                    record.published_places.add(published_place)

            record.authors.clear()
            if data['details']['details'].has_key('authors'):
                for author in data['details']['details']['authors']:
                    author_key = author['key'].replace('/authors/', '')
                    try:
                        book_author = Author.objects.get(identifier=author_key)
                    except Author.DoesNotExist:
                        book_author = Author(identifier=author_key)
                    book_author.name = author['name']
                    book_author.save()
                    record.authors.add(book_author)
            elif data['data'].has_key('authors'):
                for author in data['data']['authors']:
                    author_key = author['url'].replace('http://openlibrary.org/authors/', '')
                    try:
                        book_author = Author.objects.get(identifier=author_key)
                    except Author.DoesNotExist:
                        book_author = Author(identifier=author_key)
                    book_author.name = author['name']
                    book_author.save()
                    record.authors.add(book_author)

            if data['data'].has_key('ebooks'):
                if data['data']['ebooks'][0].has_key('formats'):
                    formats = data['data']['ebooks'][0]['formats']
                    for book_format in formats:
                        ebooks = record.ebooks(book_format)
                        for ebook in ebooks:
                            ebook.delete()
                        if formats[book_format].has_key('url'):
                            url = formats[book_format].get('url')
                            result = urllib.urlretrieve(url)
                            book_file = BookFile(record=record)
                            book_file.file.save(
                                os.path.basename(url),
                                File(open(result[0]))
                            )
                            book_file.save()

            subjects = None
            if data['details']['details'].has_key('subjects'):
                subjects = data['details']['details']['subjects']
            elif data['data'].has_key('subjects'):
                subjects = data['data']['subjects']
            if subjects:
                record.book.subjects.clear()
                for subject in subjects:
                    if type(subject) == dict:
                        subject = title_case(subject['name'])
                    try:
                        book_subject = Subject.objects.get(name=subject)
                    except Subject.DoesNotExist:
                        book_subject = Subject(name=subject)
                    book_subject.save()
                    record.book.subjects.add(book_subject)

            # record.publishers.clear()
            # for publisher in data['details']['details']['publishers']:
            #     try:
            #         book_publisher = Publisher.objects.get(name=publisher['name'])
            #     except Publisher.DoesNotExist:
            #         book_publisher = Publisher(name=publisher['name'])
            #         book_publisher.save()
            #     record.publishers.add(book_publisher)
            try:
                book_publisher = Publisher.objects.get(name=data['details']['details']['publishers'][0])
            except Publisher.DoesNotExist:
                book_publisher = Publisher(name=data['details']['details']['publishers'][0])
                book_publisher.save()
            record.publisher = book_publisher

            if data['data'].has_key('cover'):

                if data['data']['cover'].has_key('large'):
                    cover_url = data['data']['cover']['large']
                    result = urllib.urlretrieve(cover_url)
                    record.large_cover.save(
                        os.path.basename(cover_url),
                        File(open(result[0]))
                    )
                if data['data']['cover'].has_key('medium'):
                    cover_url = data['data']['cover']['medium']
                    result = urllib.urlretrieve(cover_url)
                    record.medium_cover.save(
                        os.path.basename(cover_url),
                        File(open(result[0]))
                    )

                if data['data']['cover'].has_key('small'):
                    cover_url = data['data']['cover']['small']
                    result = urllib.urlretrieve(cover_url)
                    record.small_cover.save(
                        os.path.basename(cover_url),
                        File(open(result[0]))
                    )

            # thumbnail_url = data['details']['thumbnail_url']
            # result = urllib.urlretrieve(thumbnail_url)
            # record.thumbnail.save(
            #     os.path.basename(thumbnail_url),
            #     File(open(result[0]))
            # )

            # import pdb
            #
            # pdb.set_trace()
            record_data = RecordSerializer(record).data

    record_form = RecordForm(instance=record)

    return render(request, 'acquisition.html', {'data': record_data, 'form': record_form})
コード例 #21
0
 def clean_isbn(self):
     isbn_val = self.cleaned_data["isbn"]
     if isbn_val:
         if not isbn.isValid(isbn_val):
             raise ValidationError("The isbn you entered is not valid")
     return isbn_val