def ebook(id): ebook = Ebook.query.get_or_404(id) download_users = ebook.users_download.limit(10).all() form = CommentForm() if form.validate_on_submit(): comment = Comment(body=form.body.data, ebook=ebook, author=current_user._get_current_object()) db.session.add(comment) # flash('评论信息成功创建') return redirect(url_for('main.ebook', id=ebook.id, page=1)) page = request.args.get('page', 1, type=int) if page == -1: page = (ebook.comments.count() - 1) / current_app.config['FLASK_BMS_MAX_PER_PAGE'] + 1 pagination = ebook.comments.order_by(Comment.timestamp.desc()).paginate( page, per_page=current_app.config['FLASK_BMS_MAX_PER_PAGE'], error_out=False) tags = [] for i in ebook.tags: tags.append({'name': i.name, 'className': 'info'}) comments = pagination.items can_write_comment = current_user.can(Permission.WRITE_COMMENT) return custom_render_template('book/ebook.html', pagination=pagination, url_point='main.ebook', can_write_comment=can_write_comment, book=ebook, download_users=download_users, Permission=Permission, tags=tags, form=form, comments=comments)
def admin_config(): form = ConfigForm() # 从配置config全局对象读取数据内容到表中 config_name_list = [i for i in dir(form) if i.isupper()] env = os.environ.get('FLASK_BMS_ENV') or 'default' env_path = getattr(config[env],'ENV_PATH') if form.validate_on_submit(): for c in config_name_list: data = ConfigTable.query.filter_by(name=c).first() if data is None: data = ConfigTable(name=c,config_value=str(form[c].data),type_name=type(form[c].data).__name__) else: data.name=c data.config_value = str(form[c].data) data.type_name = type(form[c].data).__name__ db.session.add(data) set_key(env_path,c,form[c].data) setattr(config[env],c,form[c].data) # 保存数据库 db.session.commit() return redirect(url_for('admin.admin_config')) else: # 从配置config全局对象读取数据内容到表中 config_name_list = [i for i in dir(form) if i.isupper()] env = os.getenv('FLASK_BMS_ENV') or 'default' for c in config_name_list: form[c].data = getattr(config[env],c) return custom_render_template('admin/config.html',form=form,app_name='Flask-BMS')
def upload_ebooks(): form = UploadEbookForm() book = Ebook(uploader_id=current_user.id) if form.validate_on_submit(): f = form.ebook_file.data file_name = f.filename file_path = os.path.join(config['default'].UPLOAD_PATH, file_name) f.save(file_path) book.name = file_name book.author = form.author.data book.description = form.description.data or u'暂无介绍' book.category_id = form.category.data book.upload_user = current_user._get_current_object() _, file_type = os.path.splitext(file_name) book.file_type = file_type book.file_size = os.path.getsize(file_path) book.file_path = url_for('static', filename='uploads/' + file_name) # 执行电子书页面生成如果是pdf提取第一页,如果是word则使用默认的图片 if file_type.upper() == '.PDF': image_path = file_path + '.jpg' getImageFromPdf(file_path, image_path) book.image_path = url_for('static', filename='uploads/' + file_name + '.jpg') else: book.image_path = url_for('static.', filename='images/ebooks_default.png') db.session.add(book) flash('上传电子书成功') return redirect(url_for('main.upload_ebooks')) return custom_render_template('book/upload_ebook.html', form=form)
def admin_dashboard(): users_count = User.query.count() # select sum(total_count) as total from books; try: sql = text("select sum(total_count) as total from books") books_count = db.engine.execute(sql).fetchall()[0][0] if books_count is None: books_count =0 except: books_count=0 # 下载最多的图书统计 best_download_books = Ebook.query.order_by(Ebook.downloads.desc()).limit(10).all() best_download_books_name = [b.name for b in best_download_books] best_download_books_downloads = [b.downloads for b in best_download_books] # 下载最多的用户统计 try: most_download_users_sql = text("select user_id,username,count(*) as downloads from ebooks_download inner join users on ebooks_download.user_id=users.id group by user_id order by downloads desc limit 10;") most_download_users_list = db.engine.execute(most_download_users_sql).fetchall() most_download_users_username = [m[1] for m in most_download_users_list] most_download_users_downloads = [m[2] for m in most_download_users_list] except Exception as e: most_download_users_username=[] most_download_users_downloads=[] # 最近7天的下载数据统计 ebooks_count = Ebook.query.count() bookrents_count = BookRent.query.filter_by(active=1).count() try: download_statics_sql = text("select count(*) as downloads from ebooks_download;") download_count = db.engine.execute(download_statics_sql).fetchall()[0][0] except Exception: download_count = 0 count = [users_count,books_count,ebooks_count,bookrents_count,download_count] try: each_day_download_sql = text("select date(download_time) as each_day,count(*) from ebooks_download where download_time > current_date - interval 7 day group by each_day order by each_day asc limit 7;") each_day_download = db.engine.execute(each_day_download_sql).fetchall() each_day_download_date = [str(m[0]) for m in each_day_download] each_day_download_count = [m[1] for m in each_day_download] except Exception as e: print e each_day_download_date = [] each_day_download_count = [] return custom_render_template('admin/index.html', app_name='Flask-BMS', best_download_books_name=json.dumps(best_download_books_name), best_download_books_downloads=json.dumps(best_download_books_downloads), most_download_users_username=json.dumps(most_download_users_username), most_download_users_downloads=json.dumps(most_download_users_downloads), each_day_download_date=json.dumps(each_day_download_date), each_day_download_count=json.dumps(each_day_download_count), count=count)
def admin_user(): roles = Role.query.all() page = request.args.get('page', 1, type=int) search = request.args.get('search','') if search is None or search=='': pagination = User.query.order_by(User.id.asc()).paginate(page,per_page=current_app.config['FLASK_BMS_MAX_PER_PAGE']) else: pagination = User.query.whoosh_search(search).order_by(User.created_at.desc()).paginate(page,per_page=current_app.config['FLASK_BMS_MAX_PER_PAGE']) users_list = pagination.items return custom_render_template('admin/user.html',roles=roles,users = users_list, pagination = pagination, app_name='Flask-BMS')
def user(username): u = User.query.filter_by(username=username).first() sql = text( "select books.* from book_rent inner join books where book_rent.rent_person_id=:x and book_rent.active=1 and book_rent.rent_book_id=books.id" ) book_rent_list = db.engine.execute(sql, x=u.id).fetchall() if u is None: abort(404) return custom_render_template('user/profile.html', user=u, book_rent_list=book_rent_list)
def edit_profile(): form = EditProfileForm() if form.validate_on_submit(): current_user.name = form.name.data current_user.about_me = form.about_me.data db.session.add(current_user) flash('更新信息成功') return redirect( url_for('main.edit_profile', username=current_user.username)) form.name.data = current_user.name form.about_me.data = current_user.about_me return custom_render_template('user/edit_profile.html', form=form)
def editebook(id): form = EditEBookForm() book = Ebook.query.get_or_404(id) tag_string = form.tag.data if form.validate_on_submit(): f = form.ebook_file.data if f is not None: f = form.ebook_file.data file_name = f.filename file_path = os.path.join(config['default'].UPLOAD_PATH, file_name) f.save(file_path) book.name = file_name _, file_type = os.path.splitext(file_name) book.file_type = file_type book.file_size = os.path.getsize(file_path) book.file_path = url_for('static', filename='uploads/' + file_name) # 执行电子书页面生成如果是pdf提取第一页,如果是word则使用默认的图片 if file_type.upper() == '.PDF': image_path = file_path + '.jpg' getImageFromPdf(file_path, image_path) book.image_path = url_for('static', filename='uploads/' + file_name + '.jpg') else: book.image_path = url_for('static.', filename='images/ebooks_default.png') book.tags[:] = [] if tag_string is not None and len(tag_string.split(';')) > 0: for t in tag_string.split(';'): tag = Tag.findOrInsert(t) if tag is None: continue book.tags.append(tag) book.name = form.name.data book.author = form.author.data book.description = form.description.data or u'暂无介绍' book.category_id = form.category.data db.session.add(book) flash('修改电子书成功') return redirect(url_for('main.editebook', id=book.id)) form.name.data = book.name form.author.data = book.author or u'无' form.description.data = book.description or u'暂无介绍' form.category.data = book.category_id tags_list = [] for tag in book.tags: tags_list.append(tag.name) return custom_render_template('book/edit_ebook.html', form=form, tags=';'.join(tags_list))
def book_category(name): try: page = request.args.get('page', 1, type=int) pagination = Category.query.filter_by( name=name).first().books.order_by(Book.id.desc()).paginate( page, per_page=current_app.config['FLASK_BMS_MAX_PER_PAGE']) books_list = pagination.items return custom_render_template('book/books.html', books=books_list, pagination=pagination, app_name='Flask-BMS', tag_name=name) except Exception: return abort(404)
def editbook(id): form = EditBookForm() book = Book.query.get_or_404(id) if form.validate_on_submit(): f = form.book_img.data if f is not None: ts = str(time.time()).split('.')[0] file_name = ts + '_' + f.filename file_path = os.path.join(config['default'].UPLOAD_PATH + '/books/', file_name) f.save(file_path) book.image_path = url_for('static', filename='uploads/books/' + file_name) book.name = form.name.data book.author = form.author.data or u'无' book.description = form.description.data or u'暂无介绍' book.tags = [] tag_string = form.tag.data if tag_string is not None and len(tag_string.split(';')) > 0: for t in tag_string.split(';'): tag = Tag.findOrInsert(t) if tag is None: continue else: book.tags.append(tag) book.category_id = form.category.data book.status_id = form.status.data book.isbn = form.isbn.data or u'无' book.total_count = int(form.total_count.data or 0) book.book_number = form.book_number.data or '无' book.publisher = form.publisher.data or u'无' db.session.add(book) flash('修改图书成功') return redirect(url_for('main.editbook', id=book.id)) form.name.data = book.name form.author.data = book.author or u'无' form.description.data = book.description or u'暂无介绍' form.category.data = book.category_id form.status.data = book.status_id form.isbn.data = book.isbn or u'无' form.total_count.data = int(book.total_count) form.book_number.data = book.book_number or u'无' form.publisher.data = book.publisher or u'无' tags_list = [] for tag in book.tags: tags_list.append(tag.name) return custom_render_template('book/edit_book.html', form=form, tags=';'.join(tags_list))
def books(): page = request.args.get('page', 1, type=int) search = request.args.get('search') if search is None or search == '': pagination = Book.query.order_by(Book.id.desc()).paginate( page, per_page=current_app.config['FLASK_BMS_MAX_PER_PAGE']) else: pagination = Book.query.whoosh_search(search).order_by( Book.id.desc()).paginate( page, per_page=current_app.config['FLASK_BMS_MAX_PER_PAGE']) books_list = pagination.items return custom_render_template('book/books.html', books=books_list, pagination=pagination, app_name='Flask-BMS')
def admin_content_config(): page = request.args.get('page', 1, type=int) new_category_name = request.form.get('new_category_name') print new_category_name if new_category_name is None: pagination = Category.query.order_by(Category.id.asc()).paginate(page,per_page=current_app.config['FLASK_BMS_MAX_PER_PAGE']) category_list = pagination.items else: if new_category_name.strip() == '': flash("提交内容为空") return redirect(url_for("admin.admin_content_config")) else: cat = Category.query.filter_by(name=new_category_name).first() if cat is None: cat = Category(name=new_category_name) db.session.add(cat) flash("新的内容提交成功") return redirect(url_for("admin.admin_content_config")) return custom_render_template('admin/content_admin.html',category = category_list, pagination = pagination, app_name='Flask-BMS')
def addbook(): form = AddBookForm() book = Book(uploader_id=current_user.id) ts = str(time.time()).split('.')[0] if form.validate_on_submit(): if form.book_img.data: f = form.book_img.data file_name = ts + '_' + f.filename file_path = os.path.join(config['default'].UPLOAD_PATH + '/books/', file_name) f.save(file_path) book.image_path = url_for('static', filename='uploads/books/' + file_name) book.name = form.name.data book.author = form.author.data or u'无' book.description = form.description.data or u'暂无介绍' book.category_id = form.category.data if form.tag.data and len(form.tag.data.split(';')) > 0: for i in form.tag.data.split(';'): tag = Tag.findOrInsert(i) if tag == None: continue book.tags.append(tag) book.status_id = form.status.data book.upload_user = current_user._get_current_object() book.isbn = form.isbn.data or u'暂无' book.total_count = int(form.total_count.data or 0) book.book_number = form.book_number.data or u'暂无' book.publisher = form.publisher.data or u'暂无' try: if form.book_img.data is None: id, img_200_200_path, img_350_350_path = download_images_from_bookname( form.name.data, config['default'].UPLOAD_PATH + '/books/') book.description = get_detail_info(id)[0] book.image_path = img_350_350_path.split('/app')[-1] except Exception as e: raise e db.session.add(book) flash('新增图书成功') return redirect(url_for('main.addbook')) return custom_render_template('book/add_book.html', form=form)
def book(id): book = Book.query.get_or_404(id) s = text( "select users.id,users.username,users.avatar_hash from book_rent inner join users where book_rent.rent_person_id=users.id and book_rent.active=1 and book_rent.rent_book_id=:x" ) book_rent_users = db.engine.execute(s, x=id).fetchall() form = CommentForm() rent_book_obj = BookRent.query.filter_by(rent_book_id=4, active=1).first() if rent_book_obj is not None and rent_book_obj.has_key('rent_user'): userlist = rent_book_obj['rent_user'] else: userlist = [] if form.validate_on_submit(): comment = Comment(body=form.body.data, book=book, author=current_user._get_current_object()) db.session.add(comment) return redirect(url_for('main.book', id=book.id, page=1)) page = request.args.get('page', 1, type=int) if page == -1: page = (book.comments.count() - 1) / current_app.config['FLASK_BMS_MAX_PER_PAGE'] + 1 pagination = book.comments.order_by(Comment.timestamp.desc()).paginate( page, per_page=current_app.config['FLASK_BMS_MAX_PER_PAGE'], error_out=False) comments = pagination.items can_write_comment = current_user.can(Permission.WRITE_COMMENT) tags = [] for i in book.tags: tags.append({'name': i.name, 'className': color_picker()}) return custom_render_template('book/book.html', pagination=pagination, can_write_comment=can_write_comment, book=book, Permission=Permission, url_point='main.book', form=form, tags=tags, book_rent_users=book_rent_users, comments=comments)
def index(): return custom_render_template('index.html', app_name='Flask-BMS', username=session.get('username'))
def admin_about(): return custom_render_template('admin/about.html', app_name='Flask-BMS')