I want to search the Google Drive folder.
To check if there is not a folder with the name of the folder to create.
I have this code:
request_url = "https://www.googleapis.com/drive/v2/files?access_token=%s" % (access_token)
data = {"q": "title=filename"}
data_json = json.dumps(data)
print data_json
req = urllib2.Request(request_url,data_json, headers)
print request_url
print data_json
content = urllib2.urlopen(req).read()
print content
content = json.loads(content)
Unfortunately, there is no research but creates a no name file.
Thank you in advance for your help
Basically with urllib2, when you specify the data while using Request(), it automatically considers your request as a POST request, and that's why it creates a file with no name.
If you want it to be a GET request, you have to encode the data in the URL before calling Request()
Related
I am trying to retrieve an xml file from the github using python program. I am trying different url but for each of them it say content not found. What are different options to retrieve the file from github? Any help on this would be much appreciated!!
import requests
from github import Github
import base64
g = Github("access_token")
#url = 'https://api.github.com/repos/{username}/{repos_name}/contents/{path}/{filename}.xml'
#url = 'https://git.<company domain>.com/raw/IT/{repos_name}/{path}/{filename}.xml?token<value>'
url = 'https://git.<company domain>.com/raw/IT/{repos_name}/{path}/{filename}.xml?token=<value>'
req = requests.get(url)
#print ('Keep Going!', req.content)
if req.status_code == requests.codes.ok:
req = req.json()
`. `# the response is a JSON
# req is now a dict with keys: name, encoding, url, size ...
# and content. But it is encoded with base64.
content = base64.decodestring(req['content'])
else:
print('Content was not found.')
output:
Keep Going! b'{"message":"Not Found","documentation_url":"https://developer.github.com/v3/repos/contents/#get-contents"}'
Content was not found.
Replace all the <> and {} variable in your url with the actual path to the file you're trying to retrieve.
I need to download a file from an external source, I am using Basic authentication to login to the URL
import requests
response = requests.get('<external url', auth=('<username>', '<password>'))
data = response.json()
html = data['list'][0]['attachments'][0]['url']
print (html)
data = requests.get('<API URL to download the attachment>', auth=('<username>', '<password>'), stream=True)
print (data.content)
I am getting below output
<url to download the binary data>
\x00\x00\x13\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x0f\xcb\x00\x00\x1e\x00\x1e\x00\xbe\x07\x00\x00.\xcf\x05\x00\x00\x00'
I am expecting the URL to download the word document within the same session.
Working solution
import requests
import shutil
response = requests.get('<url>', auth=('<username>', '<password>'))
data = response.json()
html = data['list'][0]['attachments'][0]['url']
print (html)
data = requests.get('<url>', auth=('<username>', '<password>'), stream=True)
with open("C:/myfile.docx", 'wb') as f:
data.raw.decode_content = True
shutil.copyfileobj(data.raw, f)
I am able to download the file as it is.
When you want to download a file directly you can use shutil.copyfileobj():
https://docs.python.org/2/library/shutil.html#shutil.copyfileobj
You already are passing stream=True to requests which is what you need to get a file-like object back. Just pass that as the source to copyfileobj().
I am trying to work with RestfulAPI's on python.
After OCR a pdf, I want to send the text to an restfulAPI to get back retrieve specific words along with their position within the text. I have not manage to send the string of text to the API yet.
Code follows:
import requests
import PyPDF2
import json
url = "http://xxapi.xxapi.org/xxx.util.json"
pdfFileObj = open('/Users/xxx/pdftoOCR.pdf','rb')
pdfReader = PyPDF2.PdfFileReader(pdfFileObj)
pageObj = pdfReader.getPage(1) # To try with the text found in the first page
data = {"text": pageObj.extractText()}
data_json = json.dumps(data)
params = {'text':'string'}
r = requests.post(url, data=data_json, params=params)
r1 = json.loads(r.text)
Although I get a response 200 from the request, The data should come in Json format with the need to poll some token URL (Which I don`t know how to do it either) Also I don't think the request is correct as when I paste the token url to the browser I see an empty Json file (No words, no position) even if I know the piece of text I'm trying to send contains the desired words.
Thanks in advance! I work with OS X , python 3.5
Well, many thanks to #Jose.Cordova.Alvear for resolving this issue
import json
import requests
pdf= open('test.pdf','rb')
url = "http://xxapi.xxapi.org/xxx.util.json"
payload = {
'file' :pdf
}
response = requests.post(url, files=payload)
print response.json()
I am trying to download a file over https using python requests. I wrote a sample code for this. When i run my code it doesnot download the pdf file given in link. Instead downloads the html code for the login page. I checked the response status code and it is giving 200. To download the file login is necessary. How to download the file?
My code:
import requests
import json
# Original File url = "https://seller.flipkart.com/order_management/manifest.pdf?sellerId=8k5wk7b2qk83iff7"
url = "https://seller.flipkart.com/order_management/manifest.pdf"
uname = "xxx#gmail.com"
pwd = "xxx"
pl1 = {'sellerId':'8k5wk7b2qk83i'}
payload = {uname:pwd}
ses = requests.Session()
res = ses.post(url, data=json.dumps(payload))
resp = ses.get(url, params = pl1)
print resp.status_code
print resp.content
I tried several solutions including Sending a POST request with my login creadentials using requests' session object then downloading file using same session object. but it didn't worked.
EDIT:
It still is returning the html for login page.
Have you tried to pass the auth param to the GET? something like this:
resp = requests.get(url, params=pl1, auth=(uname, pwd))
And you can write resp.content to a local file myfile.pdf
fd = open('myfile.pdf', 'wb')
fd.write(resp.content)
fd.close()
I'm trying to rewrite some old python code with requests module.
The purpose is to upload an attachment.
The mail server requires the following specification :
https://api.elasticemail.com/attachments/upload?username=yourusername&api_key=yourapikey&file=yourfilename
Old code which works:
h = httplib2.Http()
resp, content = h.request('https://api.elasticemail.com/attachments/upload?username=omer&api_key=b01ad0ce&file=tmp.txt',
"PUT", body=file(filepath).read(),
headers={'content-type':'text/plain'} )
Didn't find how to use the body part in requests.
I managed to do the following:
response = requests.put('https://api.elasticemail.com/attachments/upload',
data={"file":filepath},
auth=('omer', 'b01ad0ce')
)
But have no idea how to specify the body part with the content of the file.
Thanks for your help.
Omer.
Quoting from the docs
data – (optional) Dictionary or bytes to send in the body of the Request.
So this should work (not tested):
filepath = 'yourfilename.txt'
with open(filepath) as fh:
mydata = fh.read()
response = requests.put('https://api.elasticemail.com/attachments/upload',
data=mydata,
auth=('omer', 'b01ad0ce'),
headers={'content-type':'text/plain'},
params={'file': filepath}
)
I got this thing worked using Python and it's request module. With this we can provide a file content as page input value. See code below,
import json
import requests
url = 'https://Client.atlassian.net/wiki/rest/api/content/87440'
headers = {'Content-Type': "application/json", 'Accept': "application/json"}
f = open("file.html", "r")
html = f.read()
data={}
data['id'] = "87440"
data['type']="page"
data['title']="Data Page"
data['space']={"key":"AB"}
data['body'] = {"storage":{"representation":"storage"}}
data['version']={"number":4}
print(data)
data['body']['storage']['value'] = html
print(data)
res = requests.put(url, json=data, headers=headers, auth=('Username', 'Password'))
print(res.status_code)
print(res.raise_for_status())
Feel free to ask if you have got any doubt.
NB: In this case the body of the request is being passed to the json kwarg.