从Java到python的POST请求重制

2024-06-01 11:22:34 发布

您现在位置:Python中文网/ 问答频道 /正文

我对python flask完全陌生,在使用请求和flask模块编写代码时遇到了一个问题。你知道吗

我正在使用Panther平台提供的webapi进行一个项目。该项目提供了一个使用apachejava的示例。你知道吗

源代码如下(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提供的webapi。你知道吗

我使用requests将JAVA代码重新编写成python3。代码如下:


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)

我期望从webapi得到一个XML对象,其中包含一些基本的生物学信息。但是,我得到的结果是空的(或者当我打印Pantherpost.content\n\n\rnull\n

似乎我从自己的web上获得的参数没有正确地发送到webapi。你知道吗

除了这个获取空值的问题之外,作为一个初学者,我也不太确定“geneList”部分应该接收纯文本对象还是文件。手册上说需要一个文件,但是,这个命令可能已经将它重新格式化为纯文本

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

无论如何,我尝试了这两种解释:pantherName是一个名称格式正确的纯文本列表,uploadTemp是为项目生成的.txt文件。我的代码中肯定有一些额外的bug,因为它在这两种情况下都返回了null。你知道吗

有人能帮忙吗?非常感谢你。你知道吗


Tags: 代码textnewdatatypefileswebapicontenttype
1条回答
网友
1楼 · 发布于 2024-06-01 11:22:34

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

一个。如果要使用requests发布文件,应该使用关键字files=。你知道吗

两个files对象中的键应该与请求的相应参数匹配(您使用的是file)。你知道吗

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

来自requests源代码的函数注释:

:param params: (optional) Dictionary or bytes to be sent in the query string for the :class:Request.

在示例中,Java代码StringBody用于创建参数,这意味着参数应该放在HTTP请求的主体中,而不是查询字符串中。所以you should usedata=关键字代替。如果使用params=,输出将是null。你知道吗

SO article on difference betweendataparams关键字。你知道吗


因此,我花了一些时间阅读了他们的手册并编写了一个测试脚本:

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

相关问题 更多 >