I will summarize it instead of a memo of communication method in Python
The sample code looks like this
python
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import urllib
#Destination URL
url = "http://test.test"
#get parameter
param = [
( "id", 0),
( "param", "dammy"),
]
url += "?{0}".format( urllib.urlencode( param ) )
#API execution
result = None
try :
result = urllib.urlopen( url ).read()
except ValueError :
print "Access failed."
As you can see, Send url to url The get parameter is set in param.
urllib.urlencode( param )
Converted to the form of url parameter with
http://test.test?id=0¶m=dammy
It will be converted like this.
At first I was planning to use requests, It didn't work, so I decided to use urllib and urllib2.
Sample code
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import urllib
import urllib2
url = "http://test.test"
params = {"id":0, "param" : "dammy" }
params = urllib.urlencode(params)
req = urllib2.Request(url)
#Header setting
req.add_header('test', 'application/x-www-form-urlencoded')
#parameter settings
req.add_data(params)
res = urllib2.urlopen(req)
r = res.read()
print r
Parameters
urllib.urlencode( param )
The place to convert with is the same.
req.add_header('test', 'application/x-www-form-urlencoded')
req.add_data(params)
The header and parameters are set in.
~~ By the way, if you do it with requests, it looks like the following. I sent it to CakePHP's web server in my environment, It did not become post communication. ~~
As pointed out by mursts, post communication is now possible. Thank you!
For post communication
r = s.post(url, params=params)
You have to pass it to deta in part. So I modified the above part as follows
r = s.post(url, data=params)
Again, thank you for pointing out!
By the way, in the case of params, it seems to be get communication.
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import requests
url = "http://test.test"
s = requests.session()
params = {"id":0, "param" : "dammy" }
r = s.post(url, data=params)
print r.text.encode("utf-8");
This is easier to implement, so if you can use it, this one is better
It was good.
Oh, requests need to be installed, so if you want to use it, use the following command
Please install.
pip install requests
that's all.
Recommended Posts