Skip to main content
 首页 » 编程设计

python之在 GAE 中实现 URL slug

2025年05月04日10www_RR

我正在尝试在我的应用程序(基于 python)中实现 URL slugs。我希望 slugged URL 的格式为 myhost/{post_id}/{post_title} .

当我尝试使用上述 slugged URL 格式访问页面时,出现错误(在 Chrome 中,错误显示 - unexpected token <)。如果我删除 /<post_title>从 URL,页面正确加载。具体来说,我注意到一旦我在 <post_id> 之后有一个“正斜杠” ,我有问题。没有那个额外的斜杠(额外的目录)一切正常

我的代码是:

class mainhandler(webapp.RequestHandler): 
    def get(self): 
        if (self.request.path == '/test'): 
            path = os.path.join (os.path.dirname (__file__), 'test.htm') 
            self.response.headers ['Content-Type'] = 'text/html' 
            self.response.out.write (template.render (path, {})) 
        else:                        
            path = os.path.join (os.path.dirname (__file__), 'index.htm')             
            self.response.headers ['Content-Type'] = 'text/html'                  
            self.response.out.write (template.render (path, {})) 
 
    application = webapp.WSGIApplication( [('/.*', mainhandler)],  debug=True)  

基本上,我想加载 index.htm文件,在那个文件上,我有 JavaScript,它应该提取 post-id从 URL 并用它做一些事情。

有人知道我在这里做错了什么吗?

请您参考如下方法:

您将需要修改您在应用程序 中的 URL 路径。如果我的理解正确,你会想做这样的事情:

application = webapp.WSGIApplication( 
    [('/(.*)/(.*)', mainhandler), 
     ('/.*', mainhandler)], 
    debug=True) 

然后将您的 mainhandler 定义为:

class mainhandler(webapp.RequestHandler): 
    def get(self, post_id=None, post_title=None): 

虽然目前您似乎没有对它们做任何事情,但一旦进入您的mainhandler,您就可以使用这些变量。您的第一个映射不起作用的原因是因为它没有设置为处理 URL 中的其他 / 和项目。

根据我们随后的对话,syntaxError(这是一个与 JavaScript 相关的错误)的原因是 include 前面缺少 //load.js。没有该前缀,路径是相对于当前位置的。在 localhost:8080/1234/a-test-case 的情况下,它变成了 /1234/a-test-case/include/load.js,这不t 映射到 app.yaml 中的任何特定内容,因此落入 .* 处理程序(并且不是您定义的 Javascript 处理程序),它将返回到主脚本并遵循那里的处理路径。指向您的 .js. 的链接现在返回您的 index.html 而不是您的 .js 文件,这会导致错误(类似于什么可以找到 here )。