Python请求库将PDF传递给Django服务器

时间:2013-04-15 14:39:42

标签: python django http flask python-requests

所以,我知道服务器代码有效,因为这个网站目前正在生产并且工作正常。另一方面,我开发了一个测试脚本来对API进行单元测试。我正在尝试使用HTTP POST方法将PDF文件发送到nginx - > gunicorn - >服务器的烧瓶应用环境。

服务器获取附件:

@app.route('<ObjectId:_id>/attachments', methods=['POST'])
@csrf.exempt
@opportunity_owner_required
@auth.login_required
@nocache
def upload_attachment(_id):
    upload = request.files.get('file')
    if not upload:
        abort(400, "Missing attached file.")

我尝试将pdf文件传递给服务器:

def test_add_opportunity_attachment(self):
    files = {'file': ("mozilla.pdf", open('%s/mozilla.pdf' % PATHTOFILE, 'rb'))}
    headers = {'Content-Type': 'application/pdf', "enctype": "multipart/form-data", "Content-Disposition":"attachment;filename=mozilla.pdf"}
    r=self.session.post(self.formatURL('/attachments'), headers=headers, files=files)
    assert r.status_code == 200

但我总是获得400的状态。

当使用ngrep跟随输出时,我确实看到了似乎是通过网络传递的PDF的编码形式,但是服务器看不到它。

请注意:由于其专有性,缺少部分信息。但是测试功能中使用的所有功能都可以正常工作。 formatURL按预期格式化,网址匹配。

1 个答案:

答案 0 :(得分:1)

所以这个问题比我想象的要模糊一些。服务器上的某些后端逻辑将文件保存到目录中,然后继续到URL位置的@ app.route()。我的本地副本上有一些丢失的权限,因此当它尝试保存PDF文件时,上传将失败。

另一个问题,如上面sigmavirus24所述,自定义标题设置不正确,所以最终版本有效,如下所示:

def test_add_opportunity_attachment(self):
    payload = {"title": "Testing upload title", "description": "Testing upload description"}
    file_contents = open('%s/mozilla.pdf' % PATHTOFILE, 'rb')
    files = {'file': ('mozilla.pdf', file_contents)}
    r=self.session.post(self.formatURL('/attachments'), files=files, data=payload)
    if r.status_code != 200:
        assert r.status_code == 409 #Successful, but no duplicates allowed.