制作一个简单的Web服务器和urllib2.request工作

时间:2014-02-28 13:24:01

标签: python urllib2 webapp2

这是我的代码:

服务器

import webapp2
class MainHandler(webapp2.RequestHandler):
    def get(self):
        self.response.write(self.request)
app=webapp2.WSGIApplication([('/',MainHandler)],debug=True)

请求:

import urllib2
url="http://127.0.0.1:8080?content1=take my name"
req=urllib2.Request(url)
print req.has_data()

似乎当我运行我的服务器并点击发送messege的请求时,req.has_data()返回false并且服务器没有收到任何消息,因此没有更改。如何使服务器获得content1的值?

此外,如果我的服务器在端口8080运行,是否需要将其请求端口指定为8080? 感谢。

1 个答案:

答案 0 :(得分:0)

您没有将请求发送到服务器。

你应该使用:

req = urllib2.urlopen(url)

req=urllib2.Request(url)
resp = urllib2.urlopen(req)

请参阅:http://docs.python.org/2/library/urllib2.html#examples


EDITED 我让它在本地工作(自8080被占用以来在8123端口)。服务器很好

我只更改了上面的客户端:

import urllib2                                                                                                                                                 

url = "http://127.0.0.1:8123?content1=take%20my%20name"                                                                                                        
resp = urllib2.urlopen(url)                                                                                                                                    
print resp.read()

这是我的app.yaml

application: myapp                                                                                                                                             
version: 1                                                                                                                                                     
runtime: python27                                                                                                                                              
api_version: 1                                                                                                                                                 
threadsafe: true                                                                                                                                               

handlers:                                                                                                                                                      
- url: /.*                                                                                                                                                     
  script: main.app

我用:

启动了服务器
google_appengine/dev_appserver.py --port 8123 stack/