从Java到python的POST请求重制为空

时间:2019-05-20 14:50:37

标签: python python-3.x flask python-requests

我对python flask完全陌生,使用请求和flask模块编写一些代码时遇到问题。

我正在使用Panther平台提供的Web API进行项目。该项目提供了一个使用Apache Java的示例。

源代码如下(详细信息{see more)。

public class TestProject {

public static void main(String args[]) throws Exception {
    CloseableHttpClient httpclient = HttpClients.createDefault();
    try {
        HttpPost httppost = new HttpPost("http://pantherdb.org/webservices/garuda/tools/enrichment/VER_2/enrichment.jsp?");

        StringBody organism = new StringBody("Homo sapiens", ContentType.TEXT_PLAIN);
        FileBody fileData = new FileBody(new File("c:\\data_files\\gene_expression_files\\7_data\\humanEnsembl"), ContentType.TEXT_PLAIN);
        StringBody enrichmentType = new StringBody("process", ContentType.TEXT_PLAIN);       
        StringBody testType = new StringBody("FISHER", ContentType.TEXT_PLAIN);    
        //StringBody cor = new StringBody("FDR", ContentType.TEXT_PLAIN);
        //StringBody cor = new StringBody("BONFERRONI", ContentType.TEXT_PLAIN);
        //StringBody cor = new StringBody("NONE", ContentType.TEXT_PLAIN);
        StringBody type = new StringBody("enrichment", ContentType.TEXT_PLAIN);

        HttpEntity reqEntity = MultipartEntityBuilder.create()
                .addPart("organism", organism)
                .addPart("geneList", fileData)
                .addPart("enrichmentType", enrichmentType)
                .addPart("test_type", testType)
                .addPart("type", type)
                //.addPart("correction", cor)
                .build();
        httppost.setEntity(reqEntity);

        CloseableHttpResponse response = httpclient.execute(httppost);
        try {
        //System.out.println("----------------------------------------");
       //System.out.println(response.getStatusLine());
            HttpEntity resEntity = response.getEntity();
            if (resEntity != null) {
                System.out.println(IOUtils.toString(resEntity.getContent(), StandardCharsets.UTF_8));

            }
            EntityUtils.consume(resEntity);
        } finally {
            response.close();
        }
    } finally {
        httpclient.close();
    }
  }
}

我最感兴趣的部分是.addPart("organism", organism)以及所有其他具有类似结构的代码。他们将帮助将参数从第三方网站传递到Panther提供的Web API。

我使用python3将Java代码重新制作为requests。代码如下:


uploadTemp = {'file':open('./app/static/data_temp/temp.txt','rb')}

url="http://pantherdb.org/webservices/garuda/tools/enrichment/VER_2/enrichment.jsp?"
params = {"organism":organism,"geneList":pantherName,"enrichmentType":"fullGO_process","test_type":"BINOMIAL","type":"enrichment","correction":"BONFERRONI"}

# or params = {"organism":organism,"geneList":uploadTemp,"enrichmentType":"fullGO_process","test_type":"BINOMIAL","type":"enrichment","correction":"BONFERRONI"} 

Pantherpost= requests.post(url, params = params)
print(Pantherpost.text)

我期望Web API提供一个XML对象,其中包括一些基本的生物学信息。但是,我得到的结果为空(或在打印\n\n\rnull\n时为Pantherpost.content

似乎我从自己的网站获得的参数未正确发送到Web API。

除了这个空问题,作为一个初学者,我也不太确定“ geneList”部分应该接收纯文本对象还是文件。手册说它正在等待文件,但是,该命令可能已将其重新格式化为纯文本

FileBody fileData = new FileBody(new File("c:\\data_files\\gene_expression_files\\7_data\\humanEnsembl"), ContentType.TEXT_PLAIN);

无论如何,我都尝试了两种解释:pantherName是名称正确以明文格式设置的列表,而uploadTemp是为项目生成的.txt文件。由于在两种情况下它都返回null,所以我的代码中肯定还有一些其他错误。

有人可以帮忙吗?非常感谢。

1 个答案:

答案 0 :(得分:1)

我发现您的python代码存在以下问题:

一个。如果要使用requests发布文件,则应使用关键字files=

两个files对象中的键应匹配请求的各个参数(您正在使用file)。

三个。通过编写params=params,将参数放在请求的错误位置。

requests源代码中的功能注释:

  

:param params :(可选)要在查询字符串中为:class:Request发送的字典或字节。

在示例Java代码StringBody中用于创建参数,这意味着参数应放置在HTTP请求的主体内部,而不是查询字符串。因此,改为使用you should use data=关键字。如果您使用params=,则输出将为null

data中的{p> SO article on difference between paramsrequests关键字。


所以我花了一些时间阅读手册并编写了测试脚本:

import requests


url = "http://pantherdb.org/webservices/garuda/tools/enrichment/VER_2/enrichment.jsp?"
filepath = "C:\\data\\YOUR_DATA.txt"  # change to your file location

# all required parameters according to manual, except geneList which is a file (see below)
params = {  # using defaults from manual
    "type": "enrichment",
    "organism": "Homo sapiens",
    "enrichmentType": "process",
    "test_type": "FISHER",
    "correction": "FDR",
}

# note that the key here is the name of paramter: geneList
files = {'geneList': open(filepath, 'rb')}  

# it outputs null, when 'params=params' is used
r = requests.post(url, data=params, files=files)  
print(r.status_code)
print(r.text)

输出:

200
Id  Name    GeneId  raw P-value FDR