When I post data using Angularjs to a Python CGI script, I have a weird issue where the Python output contains an Angular object that I can't remove.
The Angular Javascript responsible for posting to the Python script:
$http({
method: 'POST',
url: '/cgi-bin/test.py',
data: "test"
})
.then(function(data){
console.log(data)
})
The Python script:
#!/usr/local/bin/python2.7
print "Content-type: application/json"
print
The resulting console log should be empty, but this is what I see in the Chrome console:
I'm new to Python and Angular so I suspect that I've made a simple mistake, but I've been unable to find examples of this kind of behavior anywhere after a day of searching. Any help is appreciated.
Coming from jQuery's ajax, I expected the response from Angular's http function to include only the returned data, so I was thrown off by the presence of config, status, header data, etc.
In order to isolate the data part of the response, I did this:
.then(function(response){
data = response['data']
console.log(data)
})
Related
I want to send API requests to create or update commands in a ,Powershell script, .ps1 file.
I'm using Python requests library.
I followed the microsoft document HERE to construct the api to be send PUT request.
The format of the .ps1 file that I want to link with the request is something like;
$Comp = $env:computername
$Timezone = (Get-Timezone).Id
If ($Timezone -ne "UTC-04:00")
{write-host "Timezone: Problem Occured!" $timezone -backgroundcolor red}89
else {write-host "TimeZone: OK" $timezone}
and allowed to contain other commands. New commands should be created with sent api request.
The function, takes rgName,vmName,CommandName as parameter and forms an API
to send request with
requests.put(url:"",data:{},params:{}) in python.
The function template as follows;
`subscription_id =os.environ['AZURE_SUBSCRIPTION_ID']
source="https://management.azure.com"
token_context=access_token()
tokens=json.loads(token_context.text)
token=tokens['access_token']
url=" {}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.Compute/virtualMachines/{}/
runCommands/{}?api-version==2021-04-01".format(source,subscription_id,vmRG,vmName,command)
data={"location": "West US","commandId":
"RunShellScript","script": "<urlAdress_toScriptFileinBlobStorage>","asyncExecution":
False,"timeoutInSeconds": 3600}
headers = {'Authorization': 'Bearer ' +token,
'Content-Type': 'application/json'}
response = requests.put(url,data=data,headers=headers)
return response`
But I cannnot get a response body.
The error message I got "
"error": {
"code": "InvalidRequestContent",
"message": "The request content was invalid and could not be deserialized:
'Unexpected character encountered while parsing value: l. Path '', line 0, position 0.'."
"
How can I achieve this task? Is it possible to do with an another method?
What're your opinions about source of the error and how could I fix it?
Any suggestions and solution methods would be appreciated. Thanks in Advance,
I would like to make a GET request to one of my Python CGI files and get a response back, is there a way to handle that with raw CGI? if not, what other tool would you recommend that could potentially solve this issue? (Flask maybe?)
This is needed so I can give the backend a string to sign and return the newly created signed string back to me.
test.html -- This is what's making a GET request to gethandle.py
<script>
$.getJSON('gethandle.py', some_data, () => {alert('done')})
</script>
gethandle.py -- This is my CGI script that should do things with the request and send a response, this is the part where I am not sure what to do.
#get some_data and do things with it
#send back other_data
as it is now; when inspecting the Network tab on the browser Inspector, I see the request made to gethandle.py from test.html with a 200 status but the response is raw gethandle.py file
I got an URL like: http://localhost:4284/?session_expired=true
Now I'm sending and AJAX-Request for something and the return should be a HTTPFound with 'http://localhost:4284/'.
Cutting the URL is not the problem, but either Pyramid or the Browser are ignoring the changes, so the keep the parameter session_expired in the window location :(
Thanks
AJAX requests do not affect the window location (I suppose you want the browser to go to a completely new page as a result of the AJAX request, so the address in browser's address bar changes).
You can do this manually in JavaScript when handling the response of the AJAX request:
$.ajax(
...
}.done(function (data) {
if (data.redirect_to) {
window.location = data.redirect_to;
}
});
In the example above the server returned 200 Ok status with a JSON response which looks something like {"redirect_to": "http://localhost:4284/"}. You may prefer to return a different HTTP status and handle it in the error handler instead.
If you are returning an HTTPFound-Object, do not parse it as JSON, but rather parse is as HTML!
I am completely new to Python. I am using GitLab which offers system hook feature wherein i can specify a URL and it will send event details in the form of JSON POST data. When i create a RequestBin URL and provide that URL in GitLab's system hook, then in case of any event such as project creation, it sends the event details and i can see the same in RequestBin as shown in the snapshot below.
Now, i want to fetch this JSON data in some variable so i can process it as per my need but i'm not sure how to do read that data.
I've seen some posts which explain how to read JSON data but as you can see below in the screenshot, the FORM/POST PARAMETERS is showing as None. It's the raw body that contains all the details (in JSON format):
I have tried reading the data using Java and it works with the code shown below:
String recv;
String recvbuff="";
BufferedReader buffread = new BufferedReader(new InputStreamReader(request.getInputStream()));
while ((recv = buffread.readLine()) != null)
recvbuff += recv;
buffread.close();
System.out.println(recvbuff);
out.println(recvbuff);
Looking for something similar in Python.
I would suggest using CherryPy. It's a neat Python library that allows you to build a simple webserver application, it's fits pretty nicely in your use case: it can easily accept JSON requests (http://docs.cherrypy.org/en/latest/basics.html#dealing-with-json).
If you write a file called myserver.py with the following code:
#!/usr/bin/python3
import cherrypy
class Root(object):
#cherrypy.expose
#cherrypy.tools.json_in()
def index(self):
data = cherrypy.request.json
# You can manipulate here your json data as you wish
print(data['name'])
if __name__ == '__main__':
cherrypy.quickstart(Root(), '/')
You can simply launch the server with the command line:
python3 myserver.py
And test it with the following curl command:
curl -H "Content-Type: application/json" -POST http://127.0.0.1:8080 -d '{"name": "test", "path": "/"}'
You will then see test printed in your server log.
Your Flask application doesn't return any data so you're not going to see anything returned. You need to return something like:
return "test data"
Your screenshot is only showing the request not the response. You sent no form encoded parameters, which is why it's showing "None".
The correct Content-type for JSON is: application/json
I'm trying to create a super-simplistic Virtual In / Out Board using wx/Python. I've got the following code in place for one of my requests to the server where I'll be storing the data:
data = urllib.urlencode({'q': 'Status'})
u = urllib2.urlopen('http://myserver/inout-tracker', data)
for line in u.readlines():
print line
Nothing special going on there. The problem I'm having is that, based on how I read the docs, this should perform a Post Request because I've provided the data parameter and that's not happening. I have this code in the index for that url:
if (!isset($_POST['q'])) { die ('No action specified'); }
echo $_POST['q'];
And every time I run my Python App I get the 'No action specified' text printed to my console. I'm going to try to implement it using the Request Objects as I've seen a few demos that include those, but I'm wondering if anyone can help me explain why I don't get a Post Request with this code. Thanks!
-- EDITED --
This code does work and Posts to my web page properly:
data = urllib.urlencode({'q': 'Status'})
h = httplib.HTTPConnection('myserver:8080')
headers = {"Content-type": "application/x-www-form-urlencoded",
"Accept": "text/plain"}
h.request('POST', '/inout-tracker/index.php', data, headers)
r = h.getresponse()
print r.read()
I am still unsure why the urllib2 library doesn't Post when I provide the data parameter - to me the docs indicate that it should.
u = urllib2.urlopen('http://myserver/inout-tracker', data)
h.request('POST', '/inout-tracker/index.php', data, headers)
Using the path /inout-tracker without a trailing / doesn't fetch index.php. Instead the server will issue a 302 redirect to the version with the trailing /.
Doing a 302 will typically cause clients to convert a POST to a GET request.