Python路径操作 [英] Python path manipulation

查看:50
本文介绍了Python路径操作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用GAE和webapp2创建一个简单的PM应用程序.

I am using GAE and webapp2 to create a simple PM application.

这是我的代码的一部分,用于添加与我的项目相关联的任务.

This is part of my code for adding a task, associated to my project.

class AddTask(webapp2.RedirectHandler):
    def get(self):
        project_id = self.request.path.split('/')[-1]
        print project_id
        project = Project.get_by_id(int(project_id))
        print project
        template_values = {
            'project': project,
            'project_id': project_id
            }
        path = os.path.join(os.path.dirname(__file__), '../templates/project-task-add.html')
        self.response.write(template.render(path, template_values))

以这种方式处理网址 http://localhost:8080/projects/5812155903377408/tasks/add

我遇到的问题是我无法正确获取project_id.拆分功能仅拆分成最后一个斜杠之后的所有内容以及其后的所有内容,因此我无法使用拆分.还有其他方法可以解决此问题,还是必须重新构造 main.py ?并在网址中添加密钥ID是不正确的做法吗?

The problem I am having is that I cannot get the project_id right. Split function only splits into everything after the last slash and everything behind it, so I cannot use split. Is there any other way of handling this, or do I have to restructure my main.py? And is putting a key id in the url a bad practice?

推荐答案

您不应该尝试通过拆分URL来提取参数.您应该让webapp2路由匹配器完成工作,然后将参数传递给处理程序.

You shouldn't be trying to extract parameters by splitting URLs. You should let the webapp2 route matcher do the work, and pass the parameters to your handler.

文档相当全面,但针对您的情况进行了总结:

The documentation is fairly comprehensive, but to summarise for your case:

class AddTask(webapp2.RedirectHandler):
    def get(self, project_id):
        project = Project.get_by_id(int(project_id))

app = webapp2.WSGIApplication([
    ...
    (r'/projects/(\d+)/tasks/add', AddTask),
])

这篇关于Python路径操作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆