示例#1
0
def add(request):
    # Require login.
    if not (request.user.is_authenticated()):
        return redirect_to_login(request.get_full_path())

    # Make sure gid is in the post request
    if not ('gid' in request.POST):
        return HttpResponseRedirect("/edit/")

    try:
        b = Book.objects.get(gid=request.POST['gid'])
    except Book.DoesNotExist:
        # Book being recommended doesn't already exist, so add it.
        b = Book.objects.create(gid=request.POST['gid'])
        gb = gbooks.get(request.POST['gid'])
        b.title = gb.title
        b.authors = gb.authors
        b.isbn = gb.isbn
        try:
            # Download the thumbnail image from Google
            if gb.thumbnail_url:
                req = urllib2.Request(gb.thumbnail_url)
                req.add_header("User-Agent", "Mozilla")
                try:
                    image_link = urllib2.urlopen(req)
                    img_data = image_link.read()
                    image_link.close()
                    rand_fn = b.isbn + '-' + b.gid
                    rand_pth = os.path.join(BOOK_COVERS, rand_fn)
                    with open(rand_pth, 'w') as f:
                        os.chmod(rand_pth, 0666)
                        f.write(img_data)
                    b.cover_image = rand_fn
                except Exception, e:
                    print >> sys.stderr, "Tried to save thumbnail, but got exception:", repr(
                        e)
        finally:
            b.save()
    # Now add the recommendation
    try:
        recommendation = Recommendation.objects.get(user=request.user, book=b)
    except Recommendation.DoesNotExist:
        recommendation = Recommendation.objects.create(user=request.user,
                                                       book=b)
    finally:
        recommendation.save()
    return HttpResponseRedirect("/edit/")
示例#2
0
def add(request):
	# Require login.
	if not (request.user.is_authenticated()):
		return redirect_to_login(request.get_full_path())
		
	# Make sure gid is in the post request
	if not ('gid' in request.POST):
		return HttpResponseRedirect("/edit/")
	
	try:
		b = Book.objects.get(gid=request.POST['gid'])
	except Book.DoesNotExist:
		# Book being recommended doesn't already exist, so add it.
		b = Book.objects.create(gid=request.POST['gid'])
		gb = gbooks.get(request.POST['gid'])
		b.title = gb.title
		b.authors = gb.authors
		b.isbn = gb.isbn
		try:
			# Download the thumbnail image from Google
			if gb.thumbnail_url:
				req = urllib2.Request(gb.thumbnail_url)
				req.add_header("User-Agent", "Mozilla")
				try:
					image_link = urllib2.urlopen(req)
					img_data = image_link.read()
					image_link.close()
					rand_fn = b.isbn + '-' + b.gid
					rand_pth = os.path.join(BOOK_COVERS, rand_fn)
					with open(rand_pth, 'w') as f:
						os.chmod(rand_pth, 0666)
						f.write(img_data)
					b.cover_image = rand_fn
				except Exception, e:
					print >>sys.stderr, "Tried to save thumbnail, but got exception:", repr(e)
		finally:
			b.save()
	# Now add the recommendation
	try:
		recommendation = Recommendation.objects.get(user=request.user, book=b)
	except Recommendation.DoesNotExist:
		recommendation = Recommendation.objects.create(user=request.user, book=b)
	finally:
		recommendation.save()
	return HttpResponseRedirect("/edit/")
示例#3
0
def edit(request):
    # TODO: Clean up this messy method.

    # Require login.
    if not (request.user.is_authenticated()):
        return redirect_to_login(request.get_full_path())

    recs = Recommendation.objects.filter(user=request.user)
    category_types = CategoryType.objects.all()
    all_categories = Category.objects.all()
    context = {
        'recs': recs,
        'category_types': category_types,
        'cat_check_htmls': []
    }
    books_in_c = {}
    for c in all_categories:
        books_in_c[c] = [r for r in recs.filter(book__category=c) \
                                        .distinct()]
    print >> sys.stderr, repr(books_in_c)
    for rec in recs:
        b = ''
        for ct in category_types:
            b += '<p style="font-weight: bold">%s</p>' % ct.description
            for c in ct.get_categories():
                b += '<input type="checkbox" name="{0}" id="{1}{0}"'.format(
                    c.slug, rec.id)
                if rec in books_in_c[c]:
                    b += 'checked="checked" '
                b += '/><label for="%d%s">%s</label><br />' % (rec.id, c.slug,
                                                               c.name)
        context['cat_check_htmls'].append(b)

    if 'keywords' in request.GET:
        context['results'] = gbooks.search(request.GET['keywords'])
    elif 'gid' in request.POST:
        if 'action' in request.POST:
            b = Book.objects.get(gid=request.POST['gid'])
            r = Recommendation.objects.get(user=request.user, book=b)
            if request.POST['action'] == 'update':
                for c in Category.objects.all():
                    if c.slug in request.POST:
                        c.books.add(b)
                    else:
                        c.books.remove(b)
                r.comment = request.POST['blurb']
                r.save()
                print >> sys.stderr, repr(request.POST)
            elif request.POST['action'] == 'delete':
                if len(Recommendation.objects.filter(book=r.book)) == 1:
                    os.unlink(
                        os.path.join('/opt/infxbooklist/bookcovers/',
                                     r.book.cover_image))
                    r.book.delete()
                r.delete()
        else:
            # Make the book if doesn't exist, update if does
            gb = gbooks.get(request.POST['gid'])
            b = Book.objects.get_or_create(gid=gb.gid)[0]
            b.title = gb.title
            b.authors = gb.authors
            b.isbn = gb.isbn
            try:
                # Download the thumbnail image from Google
                req = urllib2.Request(gb.thumbnail_url)
                req.add_header("User-Agent", "Mozilla")
                try:
                    # TODO: These images are never deleted. Write a cron script to
                    #       scrub the dir of images that tables no longer reference.
                    image_link = urllib2.urlopen(req)
                    img_data = image_link.read()
                    image_link.close()
                    rand_fn = datetime.datetime.utcnow().isoformat(
                    ) + '__' + str(random.randint(0, sys.maxint))
                    rand_pth = os.path.join('/opt/infxbooklist/bookcovers',
                                            rand_fn)
                    with open(rand_pth, 'w') as f:
                        f.write(img_data)
                    b.cover_image = rand_fn
                except Exception, e:
                    print >> sys.stderr, "Tried to save thumbnail, but got exception:", repr(
                        e)
            finally:
                b.save()
            # Create a Recommendation, which links User and Book
            Recommendation(user=request.user, book=b).save()
        # Redirect to avoid refresh issues
        return HttpResponseRedirect("/edit/")
    # Go.
    return render_to_response('edit.html', context)
示例#4
0
def edit(request):
    # TODO: Clean up this messy method.
    
    # Require login.
    if not (request.user.is_authenticated()):
        return redirect_to_login(request.get_full_path())

    recs = Recommendation.objects.filter(user=request.user)
    category_types = CategoryType.objects.all()
    all_categories = Category.objects.all()
    context = {'recs': recs,
               'category_types': category_types,
               'cat_check_htmls': []}
    books_in_c = {}
    for c in all_categories:
        books_in_c[c] = [r for r in recs.filter(book__category=c) \
                                        .distinct()]
    print >>sys.stderr, repr(books_in_c)
    for rec in recs:
	    b = ''
	    for ct in category_types:
	        b += '<p style="font-weight: bold">%s</p>' % ct.description
	        for c in ct.get_categories():
	            b += '<input type="checkbox" name="{0}" id="{1}{0}"'.format(c.slug, rec.id)
	            if rec in books_in_c[c]:
	                b += 'checked="checked" '
	            b += '/><label for="%d%s">%s</label><br />' % (rec.id, c.slug, c.name)
	    context['cat_check_htmls'].append(b)
             
    if 'keywords' in request.GET:
        context['results'] = gbooks.search(request.GET['keywords'])
    elif 'gid' in request.POST:
        if 'action' in request.POST:
            b = Book.objects.get(gid=request.POST['gid'])
            r = Recommendation.objects.get(user=request.user,
                                           book=b)
            if request.POST['action'] == 'update':
                for c in Category.objects.all():
                    if c.slug in request.POST:
                        c.books.add(b)
                    else:
                        c.books.remove(b)
                r.comment = request.POST['blurb']
                r.save()
                print >>sys.stderr, repr(request.POST)
            elif request.POST['action'] == 'delete':
                if len(Recommendation.objects.filter(book=r.book)) == 1:
                    os.unlink(os.path.join('/opt/infxbooklist/bookcovers/', r.book.cover_image))
                    r.book.delete()
                r.delete()
        else:
            # Make the book if doesn't exist, update if does
            gb = gbooks.get(request.POST['gid'])
            b = Book.objects.get_or_create(gid=gb.gid)[0]
            b.title = gb.title
            b.authors = gb.authors
            b.isbn = gb.isbn
            try:
                # Download the thumbnail image from Google
                req = urllib2.Request(gb.thumbnail_url)
                req.add_header("User-Agent", "Mozilla")
                try:
                    # TODO: These images are never deleted. Write a cron script to
                    #       scrub the dir of images that tables no longer reference.
                    image_link = urllib2.urlopen(req)
                    img_data = image_link.read()
                    image_link.close()
                    rand_fn = datetime.datetime.utcnow().isoformat()+'__'+str(random.randint(0, sys.maxint))
                    rand_pth = os.path.join('/opt/infxbooklist/bookcovers', rand_fn)
                    with open(rand_pth, 'w') as f:
                        f.write(img_data)
                    b.cover_image = rand_fn
                except Exception, e:
                    print >>sys.stderr, "Tried to save thumbnail, but got exception:", repr(e)
            finally:
                b.save()
            # Create a Recommendation, which links User and Book
            Recommendation(user=request.user, book=b).save()
        # Redirect to avoid refresh issues
        return HttpResponseRedirect("/edit/")
    # Go.
    return render_to_response('edit.html', context)