zl程序教程

您现在的位置是:首页 >  后端

当前栏目

python web py入门(14)- 实现从论坛里查看某一主题

PythonWeb入门 实现 查看 14 主题 py
2023-09-14 09:10:43 时间
前面介绍了怎么样发贴到论坛,其实论坛之所以吸引人,是因为论坛可以让所有人围绕这一个主题进行深入的讨论和学习。因此,实现论坛里,必须有查看一个主题内容和它所有的评论,在这里就介绍这个过程的实现。


与前面的介绍一样,WEB服务器主要从URL来服务的,那么URL还是它的入口点,这里查看议题的实现也不例个,如下:
 '/view/(\d+)', 'View', #看贴/回贴
 从这个URL关联里,就会发现当浏览器输入: 
 http://127.0.0.1:8080/view/7

 因而从正则表达式里,就匹配到/view/(\d+), 后面识别(\d+)是识别数字7,这样就把参数传送代码里了。处理这个连接是View类,它定义如下:

 class View:
    def GET(self, post_id):
        post_id = int(post_id)
        post = model.Post().view(post_id)
        if post:
            comment = model.Comment(int(post_id))
            comments = comment.quote(comment.list())
            comment_lis = util.comments_to_lis(comments)
            return titled_render(post.title).view(post, comment_lis)
        else:
            raise web.seeother('/')
在这里就先处理GET的方法,参数post_id就是上面分离出来的参数数字7,这样把这个id转换为整数,传送逻辑处理模块model.Post(),在Post类通过数据库来查看这个议题的相关内容,比如标题、内容、作者等等。


接着下来通过后面model.Comment类查询这个相关评论。如果用户看了这个之后,还想添加评论,就可以再接提交,那么这里的代码响应:

   def POST(self, post_id):
        # jQuery+Ajax实现无刷新回帖
        i = web.input()
        cur_user_id = model.User().current_id()
        web.header('Content-Type', 'application/json')
        if cur_user_id:
            comment = model.Comment(int(post_id))
            # 回帖成功:返回"回帖"+"引用贴"信息
            if comment.new(i.content, cur_user_id, i.quote_id):
                comments = comment.quote([comment.last()])
                return json.dumps(util.comments_to_lis(comments))
        # 无权限:返回空
        return json.dumps([])
上面这段代码是处理 http://127.0.0.1:8080/view/7 连接使用POST方法提交数据的功能。

到这里,就实现看一个主题和评论的所有过程。

比特币源码入门教程

https://edu.csdn.net/course/detail/6998

深入浅出Matplotlib
https://edu.csdn.net/course/detail/6859

深入浅出Numpy
http://edu.csdn.net/course/detail/6149 

Python游戏开发入门

你也能动手修改C编译器

纸牌游戏开发

http://edu.csdn.net/course/detail/5538 

五子棋游戏开发

http://edu.csdn.net/course/detail/5487
RPG游戏从入门到精通
http://edu.csdn.net/course/detail/5246