Django:通过表单将发布请求发送到另一台服务器 [英] Django: Send a Post Request Through Form to Another Server

查看:175
本文介绍了Django:通过表单将发布请求发送到另一台服务器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在domain1的模板上有一个表单,想向domain2发送POST请求.我正在使用Django作为框架.我只希望domain2接受来自domain1和domain2(本身)的请求.但是,我遇到了csrf问题.

I have a form on a template on my domain1 and want to send a POST request to domain2. I am using Django as the framework. I only want domain2 to accept requests from domain1 and domain2 (itself). However, I run into csrf problems.

推荐答案

您需要一个RESTful API.这是一个非常大的主题,使用我得到的信息在这里为您完成工作是愚蠢的/不可能的,所以这里是一个摘要.

You need a RESTful API. That's a very large topic and would be dumb/impossible to do the work for you here with the info I've been given, so here's a summary.

我建议 Django Rest Framework 用于制作api.

I suggest Django Rest Framework for making api's.

上面的意思是,当您想要做这类事情(来自其他域的POST请求)时,您需要一个令牌.这通常是通过 Json Web令牌完成的. 也称为 JWT的.

What the above means, is that when you want to do this sort of stuff (POST requests from other domains), you need a token. This is usually done with a Json Web Token. Also known as JWT's.

过程如下:

  1. 从其他站点获取访问令牌,以有权使用该站点的API.每次交换数据时,某些http标头,密码等通常都包含在其中.
  2. 获得响应后,您便可以使用所需的数据执行所需的请求类型.

所有这些的数据格式通常都是使用JSON完成的.因此,您将必须导入json,然后导入json.dumps(obj)将其转换为有效的json,然后导入json.loads(obj)将响应转换为python字典,以便可以在模板中或任何需要的位置使用它.

The data format for all this is USUALLY done with JSON. So you will have to import json, then json.dumps(obj) to turn it into valid json, and json.loads(obj) to turn your response into a python dictionary, so you can use it in your template, or wherever you want.

如果您想看一个例子,我最近做了一个免费的GoFundMe克隆.在底部的donate()视图中,它使用了请求库,并显示了如何获取和使用JWT.您可以在那看到它.

If you want to see an example of this, I recently made a free GoFundMe clone on my guthub. In the donate() view at the bottom, it uses the requests library, and shows how a JWT is obtained and used. You can see it there.

这篇关于Django:通过表单将发布请求发送到另一台服务器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆