Как я могу выполнить этот запрос PHP curl, чтобы получить ответ от API с Python? - PullRequest
0 голосов
/ 02 сентября 2018

Рассмотрим следующий код PHP, который суммирует текст из URL:

$url = 'http://www.my-website.com/article-123.php';
$webService = 'https://resoomer.pro/websummarizer/';
$datasPost = 'API_KEY=MY_API_KEY&url='.$url;
$ch = curl_init();
curl_setopt($ch,CURLOPT_URL, $webService);
curl_setopt($ch,CURLOPT_POST, 2);
curl_setopt($ch,CURLOPT_POSTFIELDS, $datasPost);
$result = curl_exec($ch);
curl_close($ch);
echo $result;

Возвращает результат в формате JSON, например:

{
"ok":1,
"message":"Resoomer ok",
"longText":{
"size":45,
"content":"Votre texte résumé à 45%..."
},
"mediumText":{
"size":25,
"content":"Votre texte résumé à 25%..."
},
"smallText":{
"size":15,
"content":"Votre texte résumé à 15%..."
},
"codeResponse":200
}

Я пытался:

response=requests.get("https://resoomer.pro/websummarizer/?API_KEY=MY_API_KEY&url=https://en.wikipedia.org/wiki/Statistical_hypothesis_testing")

Это прекрасно работает.

Итак, я попробовал суммировать текст Resoomer API:

$MyText = 'My text plain...';
$webService = 'https://resoomer.pro/summarizer/';
$datasPost = 'API_KEY=MY_API_KEY&text='.$MyText;
$ch = curl_init();
curl_setopt($ch,CURLOPT_URL, $webService);
curl_setopt($ch,CURLOPT_POST, 2);
curl_setopt($ch,CURLOPT_POSTFIELDS, $datasPost);
$result = curl_exec($ch);
curl_close($ch);
echo $result;

Это даст ответ JSON в ответ:

{
"ok":1,
"message":"ok",
"text":{
"size":45,
"total_words":219,
"content":"Your text summarize to 45%..."
},
"codeResponse":200
}

Я хочу сделать это в Python 3.5 или Python 3.6.

Я пытался:

url = 'https://resoomer.pro/summarizer/'
Text="'A statistical hypothesis, sometimes called confirmatory data analysis, is a hypothesis that is testable on the basis of observing a process that is modeled via a set of random variables.[1] A statistical hypothesis test is a method of statistical inference. Commonly, two statistical data sets are compared, or a data set obtained by sampling is compared against a synthetic data set from an idealized model. A hypothesis is proposed for the statistical relationship between the two data sets, and this is compared as an alternative to an idealized null hypothesis that proposes no relationship between two data sets. The comparison is deemed statistically significant if the relationship between the data sets would be an unlikely realization of the null hypothesis according to a threshold probability—the significance level. Hypothesis tests are used in determining what outcomes of a study would lead to a rejection of the null hypothesis for a pre-specified level of significance. The process of distinguishing between the null hypothesis and the alternative hypothesis is aided by identifying two conceptual types of errors, type 1 and type 2, and by specifying parametric limits on e.g. how much type 1 error will be permitted.An alternative framework for statistical hypothesis testing is to specify a set of statistical models, one for each candidate hypothesis, and then use model selection techniques to choose the most appropriate model.[2] The most common selection techniques are based on either Akaike information criterion or Bayes factor.Confirmatory data analysis can be contrasted with exploratory data analysis, which may not have pre-specified hypotheses.'"
datasPost = r'API_KEY=MY_API_KEY&text='+Text
response = requests.get(url+r"?"+datasPost)

Не работает.

Кто-нибудь знает, как это исправить?

Я проверил наличие текста, но ничего не нашел.

Для получения дополнительной информации об API, пожалуйста, посетите resoomer API .

Ответы [ 2 ]

0 голосов
/ 04 сентября 2018

Вы делаете несколько вещей по-разному с запросами:

  1. Это должен быть POST, а не GET - requests.post

  2. Вы хотели отправить ключ API и текст в виде данных POST, а не в качестве параметров URL.

Это должно работать вместо: (или, по крайней мере, соответствовать тому, что вы делаете с PHP / curl)

requests.post(url, data=datasPost)

Если вы по-прежнему получаете неверный ответ токена, вам придется перепроверить, что вы действительно отправляете то, что ожидали.

0 голосов
/ 03 сентября 2018

мне удалось решить эту проблему, используя pycurl

вот код для ноутбука Jupyter - Python 3.x

установка Pycurl

!apt-get install libcurl4-openssl-dev
!apt-get install libssl-dev
!pip install pycurl

код для получения ответа

import pycurl
from io import BytesIO
datasPost='API_KEY='+API+'&text='+str(article)
response= BytesIO()
c = pycurl.Curl()
c.setopt(pycurl.URL, 'https://resoomer.pro/summarizer/')
c.setopt(pycurl.POST, 2)
c.setopt(pycurl.POSTFIELDS, datasPost)
c.setopt(c.WRITEFUNCTION, response.write)
c.perform()
content = response.getvalue().decode('UTF-8')
...