sync call using request libraries instead curl - python

I have a code in python:
cmd = "curl -d 'protection={protection}&Code={Code}' -X POST https://example.com/web/services/toaf6.php"
os.system(cmd.format(protection=protection, Code=Code))
I want to transform this so it uses pythons request libraries???
This request should be sync, but endpoint will return immediately response and I will store transaction ID so I can ask some other endpoint for job status.

Related

Retrieving value of options flags from curl command in Flask

I'm sending a curl command to a HTTP Flask server I've created. The command I'm sending is as follows:
curl -X POST --data-binary #africa-toto.wav http://localhost:5000/
Is there a way to parse the actual name of the file from this command using Flask (i.e. "africa-toto.wav")? I can receive the binary data just fine, but I'm not able to find the actual filename referenced in any of the attributes of Flask's request object
I have tried checking request.files, and a few others, but no filenames seem to be getting stored anywhere

How to get status of a job running on another machine?

I have 2 machines A and B and A can send restful request to B as follows:
curl -XPOST -H "Content-type: application/json" -d '{"data":"python /tmp/demo.py","action":"demo"}' 'http://192.168.95.8:51888/api/host'
I have deployed an api service on B and when such request is received, B will execute the python script /tmp/demo.py and the execution may last 0.5-3 hours.
My question is:
1) How to write a job on A that keeps tracking the status of the task running on B and end it self when the task finishes successfully or failed?
2) In the tracking job, how to add a module that can kill itself after exceeding a pre-set time threshold?
Treat the job as an HTTP resource. When you do POST /api/host, that request creates a new id for that job and returns it. For good use of HTTP, the response would contain a Location header with the URL of the resource where the job's status can be checked, e.g.:
POST /api/hosts
Content-type: application/json
{"data":"python /tmp/demo.py","action":"demo"}
HTTP/1.1 201 Created
Location: /api/host/jobs/c2de232b-f63e-4178-a053-d3f3459ab538
You can now GET /api/host/jobs/c2de232b-f63e-4178-a053-d3f3459ab538 at any time and see what status the job has, e.g.:
{"status": "pending"}
You may POST commands to that resource, e.g. for cancelling it.
How exactly your HTTP API would get the status of that Python script is obviously up to you. Perhaps it can communicate with it over a socket, or the job itself will periodically write its status to some database or file.

how to get session id from curl and reuse it again for next GET request

Im doing this curl request to get some data in python , how can i get session id of curl request so that i can reuse again.
commands.getoutput("curl -H \"Content-Type:application/json\" -k -u username:password -X GET https://10.39.11.4/wapi/v2.7/member -s"
curl has a built-in cookie jar meant for storing just the cookies and sending them back to the server.
To store cookies in the cookie jar we use the -c flag and give it the name of a file we wish to store the cookies in.
$ curl -X POST -c cookies.txt -u "user1:password1" website.com/login
$ cat cookies.txt
# Netscape HTTP Cookie File
# http://curl.haxx.se/docs/http-cookies.html
# This file was generated by libcurl! Edit at your own risk.
#HttpOnly_quiet-waters-1228.herokuapp.com FALSE / FALSE 0 _curl_test_app_rails_
session cm53d2RJN1VncV........
There you can find session ID .
As Mentioned by Daniel Stenberg (founder of cURL):
use -b cookies.txt in the subsequent curl command line to make use of those cookies
You should check out the requests library, it has a Session management described here: http://docs.python-requests.org/en/master/user/advanced/#session-objects
s = requests.Session()
s.auth = ('username', 'password')
s.headers.update({'Content-Type': 'application/json'})
r = s.get('https://10.39.11.4/wapi/v2.7/member')
If you want to save a session and then load it, you should use dict_from_cookiejar and cookiejar_from_dict like this:
# Save session
s_dict = requests.utils.dict_from_cookiejar(s.cookies)
# Load session
cookies = requests.utils.cookiejar_from_dict(s_dict)
s = requests.session(cookies=cookies)

How to send data on a curl redirect?

I have an API which is currently on HTTP, I moved the API using SSLify library in python flask.
Now when I send data using curl request
curl -v -k -H "Content-Type: application/json" -X POST \
--data '{"title":"foobar","body": "This body"}' \
-L http://X.Y.Z.W.us-west-2.compute.amazonaws.com/test
It returns an empty string to me by using request.data
If I make the request to begin with https it returns correct value. If there is a redirect how can I send data ?
SSLify issues a 301 or 302 redirect status code depending on your configuration. So you need to pass --post301 or --post302 to curl.
The reason for this can be found in the curl man page:
When curl follows a redirect and the request is not a plain GET (for
example POST or PUT), it will do the following request with a GET
if the HTTP response was 301, 302, or 303. If the response code was
any other 3xx code, curl will re-send the following request using
the same unmodified method.
You can tell curl to not change the non-GET request method to GET
after a 30x response by using the dedicated options for that: --post301, --post302 and -post303.

Passing arguments to a Flask Application/Celery Task Queue

I have a Flask app that uses Celery to run tasks. To start the environment I start a redis server (to store results), then Celery, then my app (python app.py). To kick off a job, I want to issue a POST request with cURL, and I want to pass in a parameter, which will be stored in the key-value:
curl ... -X POST -d '{"key": "value"}'
How does my Python program receive that parameter? Normally you'd use argv when you're just running python app.py, but that doesn't seem to work.
You would curl to the address with post variables.
app.py would try to parse if the request type is POST AND to parse the post variables.
post request
curl ... -X POST -d '{"type": "sendemail","who":"foo#bar.42"}'
curl ... -X POST -d '{"type": "sendsms","who":"+1297581234"}'
app.js (I don't know flask)
if request.type == 'POST':
if post['type'] == 'sendemail':
celery.createjob('sendemail',post['who'])
elif post['type'] == 'sendsms'
celery.createjob('sendsms',post['who'])
learn more about flask and refer to this SO question
If you want to make a POST request, then you can use requests.post()
While on the receiving end. You can use request object provided by flask.
For example:
On the client end:
from requests import post
import json
payload = {'product_id': 'B014F6U5N6', 'website_name': 'amazonIN', 'url': 'xyz'}
r = post("http://localhost:5000", json.dumps(payload), headers={'Content-Type': 'application/json'})
print r.text
On the receiving end:
from flask import request
product_id = request.json['product_id']
url = request.json['url']
website_name = request.json['website_name']

Categories

Resources