I am writing a script in Python that detects the language of a provided text.
I found the following command line that works in a terminal, but I would like to use it in my script.
Command :
**curl -X POST "https://api.cognitive.microsofttranslator.com/detect?api-version=3.0" -H "Ocp-Apim-Subscription-Key: <client-secret>" -H "Content-Type: application/json" -d "[{'Text':'What language is this text written in?'}]"**.
In the script, elements like the client-secret, the "text", and so on... should be in variables. And I would like to catch the result of the whole command line in a variable and then print it to the user.
How can I do this?
I found the command line here.
The command in Command Line is essentially sending http request. So you just need to use the python code I provide below, just for reference.
import requests
import json
url = 'https://api.cognitive.microsofttranslator.com//Detect?api-version=3.0'
body =[{"text": "你好"}]
headers = {'Content-Type': 'application/json',"Ocp-apim-subscription-key": "b12776c*****14f5","Ocp-apim-subscription-region": "koreacentral"}
r = requests.post(url, data=json.dumps(body), headers=headers)
result=json.loads(r.text)
a=result[0]["language"]
print(r.text)
print("Language = " + a)
i have made a simple python file which want to submit in Livy.Livy is currently running in local mode.Also I have mentioned following property in livy.conf file.
Property name: livy.file.local-dir-whitelist,
value "/usr/local/livy/scripts"
My file is kept in following path "/usr/local/livy/scripts"
import json, pprint, requests, textwrap
host = 'http://localhost:8998'
data = {'kind': 'spark'}
headers = {'Content-Type': 'application/json'}
r = requests.post(host + '/sessions', data=json.dumps(data), headers=headers)
r.json()
I am submitting it using curl as follows:
curl -X POST --data '{"file": "/usr/local/livy/scripts/pi.py"}' -H "Content-Type: application/json" 10.140.178.24:8999/batches
It is giving me following error:
requirement failed: Local path /usr/local/livy/scripts/pi.py cannot be added to user sessions.
My Ubuntu system only have following things:
a)Spark
b)Livy
c)Java
What am I doing wrong here?
For people using incubating mode of livy for first time,kindly check that the template file is renamed with stripping off .template in livy.conf.template.Then make sure that the following configurations are present in it.
livy.spark.master = local
livy.file.local-dir-whitelist = /path/to/script/folder/
Kindly make sure that forward slash is present in end of path
Then write url in following manner for
Python:
curl -v -X POST --data '{"file": "/path/to/script/folder/name-of-python-file.py"}' -H "Content-Type: application/json" localhost:8998/batches
Note:It will not accept relative path,whole absolute path needs to be defined in it.
curl -X POST --data '{"file": "/usr/local/livy/scripts/pi.py"}' -H "Content-Type: application/json" 10.140.178.24:8999/batches
{"id":2,"state":"starting","log":[]}
I am trying to convert curl commands to python requests using python scripts. I could find the uncurl modules and could use it to convert few curl commands successfully. But I am facing issues to make my script generic for all curl commands. Following issues are holding back my work. I am trying to write the utility in python which will take curl commands from the text file and will convert commands to python requests one by one.
Commands types like GET / POST etc are not accepted by uncurl.
Curl command options like -u , -X etc are rejected.
For DELETE requests, how should I use uncurl.
curl -v -k -H "Content-Type: application/json" -H "sync_id: 00000000-
0000-0000-0000-000000000001" -H "sync_token:
NhbSzPhbtFlZ9Gm1nLr5f8e0WLGQitG4o00jb006m5Vcs00XVqzRdHcFtyv4YOzd5S02Z3x1iR5OWQINgLP2Og" -H "instance_id: instance_id" -X GET 'example.com'
curl -v -k -H "Content-Type: application/json" -H "sync_id: 00000000-0000-0000-0000-000000000001" -H "sync_token: NhbSzPhbtFlZ9Gm1nLr5f8e0WLGQitG4o00jb006m5Vcs00XVqzRdHcFtyv4YOzd5S02Z3x1iR5OWQINgLP2Og" -H "instance_id: instance_id" -X POST -d '[{"id":"1", "name":"1", "env_mapping_name":"a", "env_mapping_id":"a1"}]' example.com'
The python code which I used for convertsion.
import uncurl
command = 'curl -v -k -H "Content-Type: application/json" -H "sync_id: 00000000-0000-0000-0000-000000000001" -H "sync_token: NhbSzPhbtFlZ9Gm1nLr5f8e0WLGQitG4o00jb006m5Vcs00XVqzRdHcFtyv4YOzd5S02Z3x1iR5OWQINgLP2Og" -H "instance_id: instance_id" -X GET 'example.com'
print uncurl.parse(command)
I have stripped off the tags and curl options which were giving me exceptions as follows.
def stripTags(command):
'''Strip off the unwanted tags from the curl command'''
print '\nCommand is *********************************', command
command = command.replace('-X', '')
command = command.replace('-k', '')
command = command.replace('-v', '')
command = command.replace(' \'', ' \"')
command = command.replace('\' ', '\" ')
command = command.replace('\'', '\"')
command = command.replace(' GET ', '')
command = command.replace(' POST ', '')
command = command.replace(' PUT ', '')
command = command.replace(' POST ', '')
command = command.replace(' DELETE ', '')
print '\nStripped string is =============', command
return command
When I used the following curl command for conversion, I got an exception.
'curl -v --proxy-user "00dcf6e7-4513-4e46-bbaf-ef4cac8f8d47":"XUmh8pIG68Zo" -X GET "example.com" --proxy 127.0.0.1:8080 -k'
The -U option here is bothering. Likewise there are other options which I observed exceptions on. So I am not sure if I am using uncurl correctly or not.
All the curl commands are converted when I used online convertor from curl.trillworks.com.
Can you please provide me the pointer on how to convert curl commands in to python requests?
**** :- I could able to send the curl command using 'runcurl' package. As per my understanding, the uncurl package has limitation of sending the curl request which the runcurl bridges by providing the 'execute' method. I used the following code to do so.
import runcurl
cmd = "curl -v -u "00dcf6e7-4513-4e46-bbaf-ef4cac8f8d47":"XUmh8pIG68Zo" -X GET "https://example.com" -k"
#strip off the curl options like -k, -v, -X, GET which causes runcurl to #throw exception.
try:
code = runcurl.execute(command)
except:
code = 400
//Write the failed cases in some file for further references
As earlier, I have to strip off the options supported by curl like '-k', '-v'. In the above curl command, the option for authentication is provided with the '-u' option. But the runcurl is throwing an exception.
I am seeking help on this point. My expectation is that 'runcurl' should not error out for the required options supported by curl. For ex:- '-u' option. Did I miss anything here? Is there any better way of handling curl command above?
Note :- I am trying to avoid the use of 'subprocess.call()' to call the curl command in my code.
I have the curl command, but not sure about how to run that in python script.
curl -H "Content-Type: application/json" -u "username:password" -d '{ "name":"something" }' "https://xxxxxxxx"
I'm planning to use subprocess, but the api documents aren't very helpful.
Also does anyone know how to get the sectionId from testrail?
Bill from TestRail here. You can find a link to our Python bindings here:
http://docs.gurock.com/testrail-api2/bindings-python
Regarding getting the section ID, you can use the get_sections method for a project/suite to return all the section details including IDs. You can find more info on that here:
http://docs.gurock.com/testrail-api2/reference-sections#get_sections
If you're looking for the section ID for a specific test case, you can get that from the get_case method.
You probably want to use the requests package for this. The curl command translates to something like this:
import json
import requests
response = requests.post('https://xxxxxxxx',
data=json.dumps({'name': 'something'}),
headers={'Content-Type': 'application/json'},
auth=('username', 'password'))
response_data = response.json()
If you really want to use subprocess, you can do something like this:
import subprocess
curl_args = ['curl', '-H', 'Content-Type: application/json', '-u', 'username:password',
'-d', '{ "name":"something" }', 'https://xxxxxxxx']
curl_output = subprocess.check_output(curl_args)
I consider the latter approach less "Pythonic".
I want to execute a curl command in Python.
Usually, I just need to enter the command in the terminal and press the return key. However, I don't know how it works in Python.
The command shows below:
curl -d #request.json --header "Content-Type: application/json" https://www.googleapis.com/qpxExpress/v1/trips/search?key=mykeyhere
There is a request.json file to be sent to get a response.
I searched a lot and got confused. I tried to write a piece of code, although I could not fully understand it and it didn't work.
import pycurl
import StringIO
response = StringIO.StringIO()
c = pycurl.Curl()
c.setopt(c.URL, 'https://www.googleapis.com/qpxExpress/v1/trips/search?key=mykeyhere')
c.setopt(c.WRITEFUNCTION, response.write)
c.setopt(c.HTTPHEADER, ['Content-Type: application/json','Accept-Charset: UTF-8'])
c.setopt(c.POSTFIELDS, '#request.json')
c.perform()
c.close()
print response.getvalue()
response.close()
The error message is Parse Error. How to get a response from the server correctly?
For the sake of simplicity, you should consider using the Requests library.
An example with JSON response content would be something like:
import requests
r = requests.get('https://github.com/timeline.json')
r.json()
If you look for further information, in the Quickstart section, they have lots of working examples.
For your specific curl translation:
import requests
url = 'https://www.googleapis.com/qpxExpress/v1/trips/search?key=mykeyhere'
payload = open("request.json")
headers = {'content-type': 'application/json', 'Accept-Charset': 'UTF-8'}
r = requests.post(url, data=payload, headers=headers)
Use curlconverter.com. It'll convert almost any curl command into Python, Node.js, PHP, R, Go and more.
Example:
curl -X POST -H 'Content-type: application/json' --data '{"text":"Hello, World!"}' https://hooks.slack.com/services/asdfasdfasdf
becomes this in Python
import requests
json_data = {
'text': 'Hello, World!',
}
response = requests.post('https://hooks.slack.com/services/asdfasdfasdf', json=json_data)
curl -d #request.json --header "Content-Type: application/json" https://www.googleapis.com/qpxExpress/v1/trips/search?key=mykeyhere
its Python implementation looks like this:
import requests
headers = {
'Content-Type': 'application/json',
}
params = {
'key': 'mykeyhere',
}
with open('request.json') as f:
data = f.read().replace('\n', '')
response = requests.post('https://www.googleapis.com/qpxExpress/v1/trips/search', params=params, headers=headers, data=data)
Check this link, it will help convert cURL commands to Python, PHP and Node.js
import requests
url = "https://www.googleapis.com/qpxExpress/v1/trips/search?key=mykeyhere"
data = requests.get(url).json
maybe?
if you are trying to send a file
files = {'request_file': open('request.json', 'rb')}
r = requests.post(url, files=files)
print r.text, print r.json
ahh thanks #LukasGraf now i better understand what his original code is doing
import requests,json
url = "https://www.googleapis.com/qpxExpress/v1/trips/search?key=mykeyhere"
my_json_data = json.load(open("request.json"))
req = requests.post(url,data=my_json_data)
print req.text
print
print req.json # maybe?
My answer is WRT python 2.6.2.
import commands
status, output = commands.getstatusoutput("curl -H \"Content-Type:application/json\" -k -u (few other parameters required) -X GET https://example.org -s")
print output
I apologize for not providing the required parameters 'coz it's confidential.
I had this exact question because I had to do something to retrieve content, but all I had available was an old version of Python with inadequate SSL support. If you're on an older MacBook, you know what I'm talking about. In any case, curl runs fine from a shell (I suspect it has modern SSL support linked in) so sometimes you want to do this without using requests or urllib.request.
You can use the subprocess module to execute curl and get at the retrieved content:
import subprocess
# 'response' contains a []byte with the retrieved content.
# use '-s' to keep curl quiet while it does its job, but
# it's useful to omit that while you're still writing code
# so you know if curl is working
response = subprocess.check_output(['curl', '-s', baseURL % page_num])
Python 3's subprocess module also contains .run() with a number of useful options.
I use os library.
import os
os.system("sh script.sh")
script.sh literally only contains the curl.
PYTHON 3
Only works within UNIX (Linux / Mac) (!)
Executing a cURL with Python 3 and parsing its JSON data.
import shlex
import json
import subprocess
# Make sure that cURL has Silent mode (--silent) activated
# otherwise we receive progress data inside err message later
cURL = r"""curl -X --silent POST http://www.test.testtestest/ -d 'username=test'"""
lCmd = shlex.split(cURL) # Splits cURL into an array
p = subprocess.Popen(lCmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
out, err = p.communicate() # Get the output and the err message
json_data = json.loads(out.decode("utf-8"))
print(json_data) # Display now the data
Sometimes you also need to install these dependencies on UNIX if you experience strange errors:
# Dependencies
sudo apt install libcurl4-openssl-dev libssl-dev
sudo apt install curl
use requests lib.. this code is :
curl -LH "Accept: text/x-bibliography; style=apa" https://doi.org/10.5438/0000-0C2G
equal to this:
import requests
headers = {
'Accept': 'text/x-bibliography; style=apa',
}
r = requests.get('https://doi.org/10.5438/0000-0C2G', headers=headers)
print(r.text)
if you os supporting curl you can do something like this:
import os
os.system("curl -d #request.json --header "Content-Type: application/json" https://www.googleapis.com/qpxExpress/v1/trips/search?key=mykeyhere")
I'm using this way... And I think you can use this too!
by the way.. the module "os" is auto-installing when you install python.
soo, you don't need to install packages ;)
This is one approach:
Import os
import requests
Data = os.execute(curl URL)
R= Data.json()