Skip to main content
 首页 » 编程设计

python之Flask webapp 中 url 方案的可能改进

2025年05月04日23zengkefu

我正在使用 python 中的 Flask 框架创建一个博客。

我有以下用于显示帖子的 View /url:

    @post_blueprint.route('/post/<int:year>/<int:month>/<title>', methods=['GET']) 
    def get_post(year, month, title): 
    try: 
        title = title.replace('-', ' ') 
        post = Post.query.filter(Post.title == title).one() 
        post.comment_form = UserCommentForm() 
    except NoResultFound: 
        raise 
    return render_template('show_single_post.html', post=post) 

在上面的代码中,我还传递了一个评论表单,让用户发表评论。之后我写了接收这个帖子请求的 View /url:

    @post_blueprint.route('post/<int:post_id/comment/add/', mehtods=['POST']) 
    def add_comment(post_id): 
        post = Post.query.get(post_id) 
        if not post: 
            raise Exception 
        if request.method == 'POST': 
            form = UserCommentForm(request.form) 
            if form.validate(): 
            try: 
               user = User.query.\ 
                    filter(User.email == form.email.data).one() 
            except NoResultFound: 
               user = User(form.username.data, form.email.data, 
                        form.website.data or None) 
 
            try: 
                comment = Comment(form.comment.data, post_id) 
                comment.author = user 
                db_session.add(comment) 
                db_session.commit() 
            except IntegrityError: 
                 raise 
 
            return redirect(url_for('.get_post', year=post.posted_on.year, 
                                                 month=post.posted_on.month, 
                                                 title=post.title.replace(' ','-') 
                                    ) 
                            ) 

在上面的 View 中,我正在从数据库访问帖子对象以确保帖子存在。 如果用户不存在,我会创建用户,然后保存评论。

现在我的问题不是访问完整的 Post 对象,而是我可以通过运行计数查询来简单地测试 post 的存在,但是由于我需要 post 属性,所以我必须获取完整的对象。

我觉得也许我的 url scheme 不是很好,或者这里可以做一些更好的事情!

谁能告诉我这是否可以改进以及如何改进?

请您参考如下方法:

您的 url 架构没问题,应该适用于搜索引擎。你云使用这样的查询 Flask-SQLAlchemy :

title, posted_on = Post.query.get_or_404(post_id).values(Post.title, Post.posted_on) 

我云没有测试它,但它应该可以工作并通过一个不存在的帖子引发 HTTP 404 错误。此外,应该只转移标题和 posted_on 数据,而不是完整的发布。