4

我正在学习 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 错误......谢谢大家:)

这是“新”代码,对于发件人没有变化:

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)

谢谢 :)

4

3 回答 3

0

检查这个例子

self.response.write("<html><body><p>Hi there!</p></body></html>")

响应将所有输出缓冲在内存中,然后在处理程序退出时发送最终输出。webapp2 不支持将数据流式传输到客户端。

所以基本上, response.write 必须是你调用的最后一件事:

def get(self):            
        con = self.request.get("message")
        self.response.write("you sent: " + con )

另外,我建议您查看此链接以阅读有关 Appengine 上的表单的 POST 和 GET 请求的更多信息。我不明白你想用这两种观点做什么,但它们相互冲突

于 2013-07-01T21:31:50.643 回答
0

我也是新手。从上周末开始学习Python,你的问题一直是我学习的参考。

发送应用

==============================

import webapp2
import urllib
import urllib2
import json
import os
import random
import time
i=0


class MainHandler(webapp2.RequestHandler):
    def get(self):

        url = "http://localhost:12080/"


        response = urllib2.urlopen(url)
        html_string = response.read()
        self.response.write(html_string)
        self.response.write(os.environ.get("HTTP_USER_AGENT", "N/A"))
        self.response.write(random.uniform(1,10))

        """


        while True:
            self.post()
            global i
            i+=1
            time.sleep(2)

        """




    def post(self):

        url = "http://localhost:12080/receive"

        name = random.uniform(1,10)
        post_data_dictionary = {'name':str(name), "age":i, "favorite OS":"Ubuntu"}
        http_headers = {'User-Agent':'OWN'}
        post_data_encoded = urllib.urlencode(post_data_dictionary)
        request_object = urllib2.Request(url, post_data_encoded,http_headers)
        response = urllib2.urlopen(request_object)



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

接收应用程序

import webapp2

import cgi
import webapp2
import urllib
import urllib2
import json

from google.appengine.api import urlfetch
from google.appengine.ext import webapp
from google.appengine.ext import db
import os

class Message(db.Model):
    msg=db.StringProperty()
    #user_agent=db.StringProperty()
    age=db.StringProperty()
    fOS=db.StringProperty()
    useragent=db.StringProperty()


class Receive(webapp2.RequestHandler):
    #def get(self):
        #self.response.write('Rececive!')
        #self.post()

    def post(self):
        var1 = self.request.get("name")
        var2 = self.request.get("age")
        var3 = self.request.get("favorite OS")
        var4 = os.environ.get("HTTP_USER_AGENT")





        mes=Message()
        mes.msg=var1
        mes.age=var2
        mes.useragent=var4
        mes.fOS=var3



        mes.put()
        #self.response.write('you sent: ' + con)

class MainHandler(webapp2.RequestHandler):
    def get(self):

        #req=datastore.RunQueryRequest()
        #gql_query= req.gql_query

        self.response.write(os.environ.get("HTTP_USER_AGENT"))








        #a=Message()







app = webapp2.WSGIApplication([
    ('/', MainHandler),
    ('/receive', Receive)
        ], debug=True)
于 2013-11-13T13:34:01.627 回答
0

您最后的评论提到了 3 个联系点:

  • application-1响应 GET 请求 POSTing to application-2
  • application-2响应 POST 请求 POSTing toapplication-3
  • application-3响应 POST 请求,显示对屏幕的响应

如果您必须在服务器端进行所有工作和消息传递,我建议使用 App Engine 的URL Fetch服务 fromapplication-1发出POST请求 to ,application-2然后发出POST请求 to application-3。这是因为根据大多数浏览器实现重定向的方式,您无法通过服务器发起的请求可靠地从application-2to重定向。application-3POST

服务器端示例

# Application 1
import webapp2
import urllib
from google.appengine.api import urlfetch

url_app_2 = 'http://application-2.com/'
url_app_3 = 'http://application-3.com/'

class MainPage(webapp2.RequestHandler):
  def get(self):
    data_to_post = {
      'message': 'Important data to pass on'
    }
    encoded_data = urllib.urlencode(data_to_post)
    # Send encoded data to application-2
    result = urlfetch.fetch(url_app_2, encoded_data, method='POST')

    data_to_post = {
      'message': result.content
    }
    encoded_data = urllib.urlencode(data_to_post)
    # Send encoded application-2 response to application-3
    result = urlfetch.fetch(url_app_3, encoded_data, method='POST')

    # Output response of application-3 to screen
    self.response.headers['Content-Type'] = 'text/plain'
    self.response.write(result.content)

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


# Application 2
import webapp2

response_template = 'The message sent was:\n{0}'

class MainPage(webapp2.RequestHandler):
  def post(self):
    message = self.request.get('message')
    self.response.headers['Content-Type'] = 'text/plain'
    self.response.write(response_template.format(message))

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


# Application 3
import webapp2

class MainPage(webapp2.RequestHandler):
  def post(self):
    message = self.request.get('message')
    self.response.headers['Content-Type'] = 'text/plain'
    self.response.write(message)

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

这样做的主要缺点是初始 GET 请求在两个连续的 POST 请求都返回之前不会收到响应。这可能会导致响应时间变长。

客户端示例

这个版本可以XMLHttpRequest从客户端使用。这里的优点是客户端从初始GET请求中获得即时响应,而后续POST请求在客户端的浏览器中处理。application-2并且application-3应该以相同的方式提供响应。只application-1需要更改,并且只需要向客户端提供以下 HTML 和 Javascript,如本例所示

于 2016-03-04T18:11:40.150 回答