我有一个PHP代码,在python cURL中如何做到这一点

2024-09-28 22:24:11 发布

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

我有一些问题,一个人有一个没有php的ubuntu服务器,这个人不想在这个服务器上安装php,我需要上传文件使用cURL或python为他们,但我只知道如何在php,我没有任何基本步骤与python:(。有人可以帮我用php编写代码。我想试试这样的

Python

with open('plik.csv', 'rb') as csv_file:
    r = requests.post(https://somelink/companies, data=csv_file)

卷曲

curl --header "Content-Type: text/csv" --request POST --data-binary "@test.csv" https://somelink/companies

我做错了什么

$url = 'https://somelink/companies';

$params = array(
    'key' => '8e7bdd23qa1d06b493152ea37cd4ah39',
    'csv' => file_get_contents('test.csv'),
); 

$query = http_build_query($params);

$ctx = stream_context_create(array(
            'http' => array(
                'header' => "Content-Type: application/x-www-form-urlencoded\r\n".
                    "Content-Length: ".strlen($query)."\r\n".
                    "User-Agent: uploader_pmg_companies\r\n",
                'method'  => 'POST',
                'content' => $query,
            ),
        ));

$result = file_get_contents($url, $flags = null, $ctx);

Tags: csvhttpstesturldatatypecontentquery
1条回答
网友
1楼 · 发布于 2024-09-28 22:24:11
Ok I wrote in python some like this

import requests

url = "https://somelink/companies"
files = {'file': open('plik.csv', 'rb')}
payload = {'key': '8e7bdd23qa1d06b493152ea37cd4ah39', 'csv': files}
headers = {'Content-Type: application/x-www-form-urlencoded', 'User-Agent: uploader_pmg_companies'}
r = requests.post(url, params=payload, files=files)
print r.url
print (r.text)
And server answer {"file_csv_content":"file...","status":success"}

So this works?

相关问题 更多 >