I am making ajax rest call from ruby and its going to python to do rest call proccess. when i trying to call rest and passing params in json formate, i think its may not passing this as json data.
My ajax call is following:
get '/cnet' do
temp="mynet"
url = URI.parse('http://192.168.1.9:8080/v2.0/networks')
params = {'net_name'=>temp}.to_json
resp = Net::HTTP.post_form(url, params)
resp_text = resp.body
puts resp_text
erb resp_text
end
Python code is following:
#app.route('/v2.0/networks',methods=['POST'])
def net_create():
net_res=request.json
print "======================="
print net_res['net_name']
print "======================="
net_name=net_res['net_name']
when i am trying to read json data from python its giving following error:
File "/network-ui/neutron_plugin.py", line 226, in net_create
net_name=net_res['net_name']
TypeError: 'NoneType' object has no attribute '__getitem__'
I don't know what is exactly happening.
I am following there link for ajax post call:
http://rest.elkstein.org/2008/02/using-rest-in-ruby.html
http://developer.yahoo.com/ruby/ruby-rest.html
Any help much appreciated. Thanks
Don't pass JSON to Net::HTTP. The method requires a simple ruby hash.
In fact, you send POST params - POST params are sent through the HTTP request body, they are not JSON or whatever, just simple strings. This is HTTP basics, so i suggest you read a bit about how things work over this protocol, it will be a lot easier if you understand it.
Regarding the python side, I don't know much Python but if you really need JSON (which i doubt), you will have to somehow parse the params.
Related
I was to automate action using python requests, when encountered strange behavior.
I want to generate reports from a certain domain, to do so I have to send a POST request providing parameters in form of an XML. In devtools it looks like this:
xmlWe: <REPORTPARS><PROC_ID>11</PROC_ID>
..... and so on
when I send report data by python requests, it works perfectly whe provided a with dictionary:
data = dict(xmlWe = '<REPORTPARS><PROC_ID>11</PROC_ID>(...) '
r = s.post(URL_generate, data=data))
IMO, its kind of strange, dictionary is a type in python so why would this server handle or expect this type?
I was trying to send this XML as text or JSON, adding the corresponding header 'Content-type' but without success. The server will return 777 Java nullptr exception, which is the same as in case of sending any other nonsense datatype. So it looks like he was expecting some sort of dictionary.
My problem is, my company uses pl/sql for automation, so I will finally have to use this language. There, in http_utils data can be sent merely by write_text, so I'm restricted to sending string (can be dumped JSON).
What do You think, Is there an option for this server will accept report_pars as a string by any chance?
You need to send a xml directly:
import requests
headers = {'Content-Type': 'application/xml'}
r = requests.post(URL_generate, data=xmlWe, headers=headers)
When sending data through python-requests a GET request, I have a need to specifically add something at the beginning of the query string. I have tried passing the data in through dicts and json strings with no luck.
The request as it appears when produced by requests:
/apply/.../explain?%7B%22......
The request as it appears when produced by their interactive API documentation (Swagger):
/apply/.../explain?record=%7B%22....
Where the key-value pairs of my data follow the excerpt above.
Ultimately, I think the missing piece is the record= that gets produced by their documentation. It is the only piece that is different from what is produced by Requests.
At the moment I've got it set up something like this:
import requests
s = requests.Session()
s.auth = requests.auth.HTTPBasicAuth(username,password)
s.verify = certificate_path
# with data below being a dictionary of the values I need to pass.
r = s.get(url,data=data)
I am trying to include an image of the documentation below, but don't yet have enough reputation to do so:
apply/model/explain documentation
'GET' requests don't have data, that's for 'POST' and friends.
You can send the query string arguments using params kwarg instead:
>>> params = {'record': '{"'}
>>> response = requests.get('http://www.example.com/explain', params=params)
>>> response.request.url
'http://www.example.com/explain?record=%7B%22'
From the comments i felt the need to explain this.
http://example.com/sth?key=value&anotherkey=anothervalue
Let's assume you have a url like the above in order to call with python requests you only have to write
response = requests.get('http://example.com/sth', params={
'key':'value',
'anotherkey':'anothervalue'
})
Have in mind that if your value or your keys have any special character in them they will be escaped thats the reason for the %7B%2 part of url in your question.
I'm trying to do a web application using the OAuthlib to login with google, this is what the google object looks like:
google = oauth.remote_app('google',
request_token_url=None,
access_token_method='POST',
request_token_params={'scope': 'email'},
access_token_url='https://accounts.google.com/o/oauth2/token',
authorize_url='https://accounts.google.com/o/oauth2/auth',
consumer_key="my consumer",
consumer_secret="my secret",
base_url='https://www.googleapis.com/oauth2/v1/'
)
The problem I hve is when I get the user information from google, his is my authorization view:
#app.route('/login/authorized/<provider>')
def authorized():
resp = google.authorized_response()
auth_error(resp)
id_token = json.load(resp['id_token'])
login_user(me, True)
return redirect(url_for('index'))
So, what I try to do with the json.load is to decode the information google gives me, in this particular case, the response has an id_token which is a long string that, according to my research, is a json encoded string that when it is decoded, provides all the user information, no matter how much I try I can't seem to find the correct way to decode it, the error I get is:
AttributeError: 'unicode' object has no attribute 'read'
On the json.load line.
EDIT: after decoding the id_token I would then use it to get or create the user in my own database.
I am using Flask and the library is json.
If anyone could explain the correct way to decode the string into a python object I would appreciate it a lot, or if this is not json but some other type of coded string please do tell. Thank you very much in advance.
json.load reads from a file. To decode a JSON string, use json.loads.
However, according to these docs, id_token is not JSON, but a "JSON Web Token".
If you are looking for the "payload", you might try:
payload = json.loads( resp['id_token'].split('.')[1].decode('base64') )
As #this-vidor said my id_token was a JWT not JSON, and I was finally able to decode it using a library called jwt, I used jwt.decode(resp['id_token'], verify=False) and it worked! Just posting this in case anyone had the same problem and wanted a solution. Thank you very much.
For more information on JWT
I'm trying to include a list of synonyms for words that a user inputs in my program. I want to send the word to the Big Huge Thesaurus API which returns the data. I'm using the requests module to send the term but the API is only returning the HTTP response code. What I am expecting is a json object that I can extract the synonyms from. Can someone help me with this please?
>>import requests
>>term = 'Big'
>>Thesaurus=requests.get("http://words.bighugelabs.com/api/2/mykey/%s/json" % term, auth=('',''))
>>print Thesaurus
<Response [200]>
Pretty sure you have to use Thesaurus.content, Thesaurus.text, or Thesaurus.json. requests.get() returns a requests.Response object, and when you print that, it's just doing an implicit string cast, which for this type of object, just returns the response code formatted in the string you are seeing printed here.
how do I get the whole raw http request in the python framework bottle?
I need something like this:
GET\n
myurl.com\n
/\n
attribute=value
&att2=value2
I need this to sign my http api requests
As far as I can tell from the docs you can't get the data in raw format.
What you can do is reconstruct it using bottle.request.data and bottle.request.headers. That may be enough for your purposes.
If you just want to print the request you can do the following:
headers_string = ['{}: {}'.format(h, request.headers.get(h)) for h in request.headers.keys()]
print('URL={}, method={}\nheaders:\n{}'.format(request.url, request.method, '\n'.join(headers_string)))