看F-W开发这本书时,遇到了一个关于分页面渲染的问题
用于渲染分页的视图函数:
@main .route('/',methods=['GET','POST'])
def index():
form = PostForm()
if current_user.can(Permission.WRITE_ARTICLES) and form.validate_on_submit():
post=Post(body=form.body.data,author=current_user._get_current_object())
db.session.add(post)
return redirect(url_for('.index'))
page=request.args.get('page',1,type = int)
pagination=Post.query.order_by(Post.timestamp.desc()).paginate(page,per_page=current_app.config['FLASKY_POSTS_PER_PAGE'],error_out=False)
posts=pagination.items
return render_template('index.html',form=form,posts=posts,pagination=pagination)
config中的配置:
FLASKY_POSTS_PER_PAGE=os.environ.get('FLASKY_POSTS_PER_PAGE') or 20
当我未设置FLASKY_POSTS_PER_PAGE时,能够一切正常的显示分页数据,并且在URL后添加?page=x,能相应的显示x页的posts,并且是以默认情况下per_page=20显示的;
当我在环境中设置了FLASKY_POSTS_PER_PAGE=20时,localhost主页发生错误,显示ValueError: invalid literal for int() with base 10: ''并且,在添加?page=2时可以显示20篇的posts,而在之后?page=3,4,5....等一系列均是空列表了。
这是为什么?
关于ValueError的异常这一部分,per_page应该传入是int型参数吧?current_app.config[xxx]得到的是字符串,我将代码改为:pagination=Post.query.order_by(Post.timestamp.desc()).paginate(page,per_page=int(current_app.config['FLASKY_POSTS_PER_PAGE']),error_out=False)后,就能正常的访问分页界面了。
但为什么没有加int的情况下,访问除主页外能够成功,并且除第二页外均没有post显示。
不知楼主是否开了virtualenv虚拟环境,还有楼主是什么系统下运行,因为windows系统下我在环境中设置不了FLASKY_POSTS_PER_PAGE=20,所以我都是直接写的,不在环境下设置。目测楼主问题出现在你这句话当中“当我在环境中设置了FLASKY_POSTS_PER_PAGE=20时”