python - 从 Java 到 python 的 POST 请求重制获取 null

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

我对Python Flask完全陌生,在使用requests和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。

我使用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)

我期待来自 Web API 的 XML 对象,其中包括一些基本的生物信息。但是,我得到的结果是 null(或者当我打印 Pantherpost.content\n\n\rnull\n)

看来我从自己的 Web 获取的参数没有正确发送到 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

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

最佳答案

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

一个。如果您想使用requests POST 文件,则应使用关键字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 请求的 body 内,而不是查询字符串中。所以you should use改为 data= 关键字。如果您使用 params=,输出将为 null

SO article on difference between 请求中的dataparams关键字。

<小时/>

所以我花了一些时间阅读他们的手册并制作了一个测试脚本:

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

关于python - 从 Java 到 python 的 POST 请求重制获取 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56223407/

相关文章:

python - 使用具有特征的原始 RDD 项将 Pyspark Python k-means 模型预测插入 DF 中

python - 如何向 numpy 数组添加条件计数器?

python - 以可变精度打印 float

python - 自定义 Flask 应用程序的记录器名称

Flask-SQLAlchemy ArgumentError : Object is not legal as a SQL literal value

python - 如何测试使用上下文参数的 Flask API

python - 使用python请求或类似模块登录www.virtualtrader.co.uk?

python - Python 3.1.1 中的搁置模块

python - 使用 list(filter()) 的程序在 python 3 上运行速度极慢

python3 pip3安装到2.7