在django中将数据发送到外部服务器

时间:2014-02-13 18:12:00

标签: python django django-templates django-views

我是django的新手,我正在尝试将数据(表单)发送到外部服务器,但到目前为止我还没有成功。

这是我的观点的简化版本:

def pay(request):    
if request.method == 'POST':
    form = PaymentForm(post_values)
if form.is_valid():       
        return render_to_response('http://externalserver/pay/', RequestContext({'form': form}))

但是它给了我以下错误:

  

/ pay /'dict'对象的AttributeError没有属性'META'

我真的不知道我是否应该/可以使用render_to_response。有谁可以帮我这个?

2 个答案:

答案 0 :(得分:1)

这没有任何意义:

render_to_response('http://externalserver/pay/'...)

此方法需要项目中 html模板的相对路径
https://docs.djangoproject.com/en/1.6/topics/http/shortcuts/#django.shortcuts.render_to_response

你需要考虑会发生什么:

HTML中的表单标记中的action确定数据的发布位置,例如<form action="" method="post">表示“将此表单发布到我已经使用的页面的网址”。 ..换句话说,浏览器将数据发布到用于呈现表单的Django视图。这是最常见的情况。

您可以将表单数据直接发布到外部网址:

<form action="http://externalserver/pay/" method="post">

也许这就是你想要的?但是你的Django视图根本看不到数据。

如果您需要在Django中处理数据,然后将处理后的数据从服务器发布到外部网址,您需要在视图中执行不同的操作。我建议使用the Requests library以一种很好的方式在Python中发布帖子请求。

答案 1 :(得分:0)

Your question does not make your intentions clear, unfortunately. If you mean to relay the form data between the client and a third-party server and then the server’s response back to the client, then that is referred to as proxying.

It is easily achievable using the requests library. You may find it easier to make use of django-proxy instead of writing your own method, as it would take care of rewriting the request headers (also known as the browser signature) in both directions.

If, on the other hand, you only wish to transfer the contents of the form to a third party server without relaying back the server’s response, then you can simply rely on the requests library and then respond to the client using a local template.

Here is a little example:

def pay(request):
    if request.method == 'POST':
        form = PaymentForm(request.post)
    if form.is_valid():
        response = requests.post(third_party_url, data=request.post)
        'process response'
        render_to_response(success_or_failure_template)
    else:
        render_to_response(bad_data_template)