谷歌应用引擎(python27)获取请求网址

时间:2012-07-21 16:13:46

标签: python google-app-engine webapp2

我一直试图获取请求网址如下

import webapp2

class MainPage(webapp2.RequestHandler):
    def get(self):
        print self.request.get('url')

app = webapp2.WSGIApplication([('/.*', MainPage)], debug=True)

请求

http://localhost:8080/index.html
它给了我类似的东西

Status: 200 Content-Type: text/html; charset=utf-8 Cache-Control: no-cache Content-Length: 70

我需要得到的是像

index.html

编辑,以便我可以检查字符串并相应地显示正确的html /模板文件。

我已经检查了Request documentation并尝试了很多替代方案但我似乎无法找到解决方案。我对网络开发很陌生。我错过了什么?

3 个答案:

答案 0 :(得分:6)

你应该从这里开始:https://developers.google.com/appengine/docs/python/gettingstartedpython27/helloworld

您没有使用模板或模板模块/引擎因此与您正在访问的路径无关,因为您使用/.*

映射所有内容

使用self.response.write()而非print 如果你在检查请求类之前从头开始阅读文档,那么对你来说再好一点。

修改

如果你想在requesthandler中获取urlpath并根据urlpath提供不同的模板,那么就这样做:

def get(self):
    if self.request.path == '/foo':
        # here i write something out
        # but you would serve a template
        self.response.write('urlpath is /foo')
    elif self.request.path == '/bar':
        self.response.write('urlpath is /bar')
    else:
        self.response.write('urlpath is %s' %self.request.path)

更好的方法是拥有多个ReqeustHandler并将它们映射到WSGIApplication

app = webapp2.WSGIApplication([('/', MainPage),
                               ('/foo', FooHandler),
                               ('/bar', BarHandler),
                               ('/.*', CatchEverythingElseHandler)], debug=True)

答案 1 :(得分:2)

而不是:

self.request.get('url')

使用:

self.request.url

您可能会发现有用的其他选项包括:

self.request.path
self.request.referer

尝试这些更改以获得您要查找的结果。

答案 2 :(得分:1)

您也可以使用它:

def get(self):
     self.request.GET['name']
     self.request.GET['sender']