【问题标题】:Webapp2 routing regex failingWebapp2路由正则表达式失败
【发布时间】:2015-07-09 08:06:10
【问题描述】:

我一直无法让 webapp2 识别路径:

app = webapp2.WSGIApplication([
    (r'/welcome\?username=([a-zA-Z0-9_-]{3,20})$', WelcomePage), # FAILS
    (r'/', MainPage),
    ], debug=True)

我在调用函数(MainPage)中插入了一些打印来检查正则表达式:

            welcome_path = "/welcome?username=" + username
            print welcome_path   #debug stuff: check to if regex matches
            m = re.match(r'/welcome\?username=([a-zA-Z0-9_-]{3,20})$', welcome_path)                     
            print m.groups(0)
            self.redirect(welcome_path) #

根据服务器日志,它看起来不错:

INFO     2015-04-29 20:07:23,667 module.py:788] default: "GET / HTTP/1.1" 200 1287
/welcome?username=fred  # printed by debug lines above
(u'fred',)              # indicates match and captured group
INFO     2015-04-29 20:07:34,588 module.py:788] default: "POST / HTTP/1.1" 302 -
INFO     2015-04-29 20:07:34,614 module.py:788] default: "GET /welcome?username=fred HTTP/1.1" **404** 154

来自 WSGIApplication (a) 和插入调用函数的正则表达式是相同的 - 复制粘贴在这里:

r'/welcome\?username=([a-zA-Z0-9_-]{3,20})$' # a
r'/welcome\?username=([a-zA-Z0-9_-]{3,20})$' # b

为了完整性:

class WelcomePage(webapp2.RequestHandler):
    def get(self, username):
        self.response.write("<h1>Welcome, {}!</h1>".format(username))

但是出现 404 错误...为什么 WSGIApplication 无法匹配路径?

(注意:这不是生产代码 - 只是 Udacity 上的 MOOC 的一个练习,其论坛已经关闭了一周......)

【问题讨论】:

  • 请同时发布WelcomePage课程代码。

标签: regex routes webapp2


【解决方案1】:

发生这种情况是因为重定向触发了一个 GET 请求,该请求根据路径匹配:在主机名之后,但在“?”之前,而不是我假设的主机名之后的所有内容。

这样就成功了:

app = webapp2.WSGIApplication([
    (r'/welcome', WelcomePage),
    (r'/', MainPage),
    ], debug=True)


class WelcomePage(webapp2.RequestHandler):
    def get(self):
        username = self.request.get('username')
        if check_username(username) == "": # returns "" if no error
            self.response.write("<h1>Welcome, {}!</h1>".format(username))
        else:
            self.redirect('/')

【讨论】:

    猜你喜欢
    • 2012-03-22
    • 2013-02-17
    • 2012-01-17
    • 1970-01-01
    • 2016-11-21
    • 2013-03-17
    • 2018-04-24
    • 2020-10-10
    相关资源
    最近更新 更多