我正在学习 Python,我正在尝试做一些非常简单的事情:从一个应用程序发送一个 HTTP POST 并在另一个应用程序中接收它,不仅我不能让它工作,我不能使用 def post(self) 让它以看似合理的方式工作。这是我的代码,它不会出错,但也不会执行任务: 发件人申请:
import cgi
import webapp2
import urllib
import urllib2
import json
from google.appengine.api import urlfetch
from google.appengine.ext import webapp
senddata = {}
senddata["message"] = 'Testing the Sender'
class MainPagePost(webapp2.RequestHandler):
def get(self):
txt_url_values = urllib.urlencode(senddata)
txturl = 'http://localhost:10080'
result = urllib.urlopen(txturl, txt_url_values)
self.redirect('http://localhost:10080')
application = webapp2.WSGIApplication([
('/', MainPagePost),
], debug=True)
接收申请:
import cgi
import webapp2
import urllib
import urllib2
import json
from google.appengine.api import urlfetch
from google.appengine.ext import webapp
class MainPageGet(webapp2.RequestHandler):
def get(self):
self.response.write('you sent:')
con = self.request.get("message")
self.response.write(con)
application = webapp2.WSGIApplication([
('/', MainPageGet),
], debug=True)
我在本地主机上得到的只是“你发送的:”:( 最糟糕的是,我不明白为什么两个 def 都需要是“get(self)”,这样我就不会收到 405 错误... 谢谢大家:)
这是"new"代码,发件人没有变化:
import cgi
import webapp2
import urllib
import urllib2
import json
from google.appengine.api import urlfetch
from google.appengine.ext import webapp
senddata = {}
senddata["message"] = 'Testing Tester'
class MainPagePost(webapp2.RequestHandler):
def get(self):
txt_url_values = urllib.urlencode(senddata)
txturl = 'http://localhost:10080'
result = urllib.urlopen(txturl, txt_url_values)
self.redirect('http://localhost:10080')
application = webapp2.WSGIApplication([
('/', MainPagePost),
], debug=True)
按照 Sam 的建议,我更改为发布的接收器,但我收到 405:
# -*- coding: utf-8 -*-
import cgi
import webapp2
import urllib
import urllib2
import json
from google.appengine.api import urlfetch
from google.appengine.ext import webapp
class MainPageGet(webapp2.RequestHandler):
def post(self):
# self.response.write('you sent:')
con = self.request.get("message")
self.response.write('you sent: ' + con)
application = webapp2.WSGIApplication([
('/', MainPageGet),
], debug=True)
谢谢:)
最佳答案
检查这个example :
self.response.write("<html><body><p>Hi there!</p></body></html>")
The response buffers all output in memory, then sends the final output when the handler exits. webapp2 does not support streaming data to the client.
所以基本上,response.write 必须是您调用的最后一件事:
def get(self):
con = self.request.get("message")
self.response.write("you sent: " + con )
此外,我建议您查看此 link阅读更多关于在 Appengine 上使用表单的 POST 和 GET 请求。我不明白你想用这两种观点做什么,但它们相互冲突
关于Python发送和接收HTTP POST,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17411450/