Recently I have migrate my application from python2/pylons to python3/pyramid.
In my plyons app, I was using below code to make POST request to third party php website (also maintained by me).
register_openers()
datagen, headers = multipart_encode({
"biosamples_metadata": open(file_bs_md, "rb"),
"metastore": open(file_ds_md, "rb"),
"annotation-submit": "Validate Annotation Files"
})
# Create the Request object
url = config['php_website_url']
request = urllib.request.Request(url, datagen, headers)
# Actually do the request, and get the response
return_text = urllib.request.urlopen(request).read()
return return_text
This above code worked perfectly fine. However on python3, poster is not supported and I cannot use register_openers()
which I don't even know do what.
In python3, I am using requests module.
import requests
from requests_toolbelt import MultipartEncoder
url = config['php_website_url']
m = MultipartEncoder(
fields={'biosamples_metadata': open(file_bs_md, 'rb'),
"metastore":open(file_ds_md, "rb"),
"annotation-submit": "Validate Annotation Files"
}
)
request = requests.post(url, data=m)
return_text = request.text
However, this code does not work properly. It goes to php app and executes the part of the code that is supposed to be executed when you do get request.
Here is what php code look like
public function handle_request () {
$TEMPLATE = 'content_main';
// Process POST
if ($this->isPOST()) {
$this->_annotationFiles = array();
return $this->error_span('This is Get');
}
else ($this->isGET()) {
$this->_annotationFiles = array();
return $this->error_span('This is Post')
}
Any help appreciated
I am not sure about your PHP code, but the below is the correct way to post files & data to a remote url with Python 3 and requests:
import requests
post_addr = "https://example.com/post_url"
data = {
'foo': 'bar',
'foo_a': 'bar_a':
}
files = {'file': open('report.xls', 'rb')}
r = requests.post(post_addr, data=data, files=files)