I need to submit an image to the site https://zxing.org/w/decode.jspx, and read the result page : https://zxing.org/w/decode.
I tried this, but it does not work :
def decode_qrcode(path):
s = requests.Session()
url = "https://zxing.org/w/decode.jspx"
files = {'file': open(path, 'rb')}
s.post(url, files=files)
return s.get("https://zxing.org/w/decode").text
I know that there are librairies to read QR code, but I did not find any that works for the kind of QR codes that I work with (they might have an error rate not supported).
You have to use the allow_redirects argument when making the POST request
import requests
def decode_qrcode(path):
s = requests.Session()
url = "https://zxing.org/w/decode.jspx"
files = {'file': open(path, 'rb')}
s.post(url, files=files, allow_redirects = True)
return s.get("https://zxing.org/w/decode").text
Related
I'm currently struggling with a really simple problem, but cant spot the problem in detail.
I want to upload a file via requests.post, the current approach looks kinda like:
fin = open(f"{path_dtl}{filename}.dtl", "rb")
files = {"file": fin}
headers = CaseInsensitiveDict()
headers["Authorization"] = f"Bearer {auth_token}"
headers["Content-Type"] = "application/octet-stream"
headers["Content-Disposition"] = f"form-data;filename ='{filename}.dtl'"
upload_dtl = requests.post(url, headers=headers, files=files)
The result is a {'error': 'Invalid Media Type/Mime Type'} response. Is there a need to open a .dtl file in different manner? The usage of a request with this configuration via Postman works fine so I guess I missed a silly mistake. Thanks in advance.
UPDATE
Alright... for anyone interested. The cause of the issue was the default key-value "file" in files = {"file": fin} is different for my API. Following workaround fixed my issue.
with open(f"{path_dtl}{filename}.dtl", "rb") as f: files = f.read()
...
upload_dtl = requests.post(url, headers=headers, files=files)
Have you tried specifying a type? You can do so like this:
files = {'file': ('aaa.csv', open('aaa.csv', 'rb'),'text/csv')}
I am trying to download file from steamworkshopdownloader.io with requests but it always returns 500 error. What am I doing wrong? I am not very familiar with requests.
Code:
import requests
def downloadMap(map_id):
session = requests.session()
file = session.post("https://backend-02-prd.steamworkshopdownloader.io/api/details/file",
data={"publishedfileid": map_id})
print(file)
downloadMap("814218628")
If you want to download a file from this API try this code, it's adapted from the link in the comment I posted earlier (https://greasyfork.org/en/scripts/396698-steam-workshop-downloader/code) and converted into Python:
import requests
import json
import time
def download_map(map_id):
s = requests.session()
data = {
"publishedFileId": map_id,
"collectionId": None,
"extract": True,
"hidden": False,
"direct": False,
"autodownload": False
}
r = s.post('https://backend-01-prd.steamworkshopdownloader.io/api/download/request', data=json.dumps(data))
print(r.json())
uuid = r.json()['uuid']
data = f'{{"uuids":["{uuid}"]}}'
while True:
r = s.post('https://backend-01-prd.steamworkshopdownloader.io/api/download/status', data=data)
print(r.json())
if r.json()[uuid]['status'] == 'prepared':
break
time.sleep(1)
params = (('uuid', uuid),)
r = s.get('https://backend-01-prd.steamworkshopdownloader.io/api/download/transmit', params=params, stream=True)
print(r.status_code)
with open(f'./{map_id}.zip', 'wb') as f:
for chunk in r.iter_content(chunk_size=1024):
if chunk:
f.write(chunk)
download_map(814218628)
The code demonstrates how to use the API and downloads a file named 814218628.zip (or whatever map_id was provided) into the directory the script is run from, the zip archive contains the .udk file (Game map design created by the Unreal Engine Development Kit).
I'm encountering an error code: 400 when trying to post a video file.
Error:
400 Bad Request
b'{
"ok":false,
"error_code":400,
"description":"Bad Request: there is no video in the request"
}'
please advice what's wrong (the video file works and exist in the mentioned path)
def sendVideo(bot_token,bot_chatID):
url = "https://api.telegram.org/bot"+ bot_token +"/sendVideo";
files = {'file': open('C:/Users/myUser/Desktop/telegram/t_video.mp4', 'rb')}
data = {'chat_id' : bot_chatID}
r = requests.post(url, files=files)
print(r.status_code, r.reason, r.content)
Just change this
files = {'file': open('C:/Users/myUser/Desktop/telegram/t_video.mp4', 'rb')}
to that
files = {'video': open('C:/Users/myUser/Desktop/telegram/t_video.mp4', 'rb')}
Because Bot API needs that video parameter name to determine the type of media.
And you forgot to add data=data (or params=data) to requests.post() to pass chat_id.
I'm having problems with a CSV file upload with requests.post method in python 3.
from requests.auth import HTTPBasicAuth
import csv
import requests
user='myuser'
pw='mypass'
advertiserid='10550'
campaignid='12394'
url='http://example.example.com/api/edc/upload/'+advertiserid+'/'+campaignid+'/'+'?encoding=utf-8&fieldsep=%3B&decimalsep=.&date=DD%2FMM%2FYYYY&info=1&process=1'
csv="myfile.csv"
with open(csv, 'r') as f:
r = requests.post(url, files={csv: f})
print(r)
The output is 'Response [502]'
Any idea of what could be the problem?
Many thanks!
You can refer the documentation of Requests library here: post-a-multipart-encoded-file
Change your request line to:
r = requests.post(url, files={'report.csv': f})
Try opening it in binary mode? And with specific 'text/csv' mime type?
with open(csv, 'rb') as f:
r = requests.post(url, files={'file': ('myfile.csv', f, 'text/csv', {'Expires': '0'})})
print(r.text)
If it still does not work, try without the binary, but still with the rest.
If it stiiill does not work, print the exact error message. And 502 (Bad Gateway) might just mean that you're not targetting the right url. (you're not targetting example.com, right?
csv="myfile.csv"
url='http://example.example.com/api/edc/upload/'+advertiserid+'/'+campaignid+'/'+'?encoding=utf-8&fieldsep=%3B&decimalsep=.&date=DD%2FMM%2FYYYY&info=1&process=1'
files = {'upload_file': open(csv,'rb')}
r = requests.post(url, files=files)
Imagine I have a rest API to import the CSV file (Multipart encoded file)
corresponding python request should be like below.
import requests
hierarchy_file_name = '/Users/herle/ws/LookoutLab/data/monitor/Import_Hierarchy_Testcase_v2.csv'
headers = {
'x-api-key': **REST_API_KEY**,
'x-api-token': **REST_API_TOKEN**,
'accept': 'application/json'
}
files = {'file': (hierarchy_file_name, open(hierarchy_file_name, 'rb'), 'text/csv')}
url = "https://abcd.com"
response = requests.post(url +'/api/v2/core/workspaces/import/validate',
files=files, verify=False, headers=headers)
print("Created")
print(response)
print(response.text)
Note:
Make sure that you don't add 'Content-Type': 'multipart/form-data' in the header
So as it stands I am able to get the content of the webpage of the PDF link EXAMPLE OF THE LINK HERE BUT, I don't want the content of the webpage I want the content of the PDF so I can put the content into a PDF on my computer in a folder.
I have been successful in doing this on sites that I don't need to log into and without a proxy server.
Relevant CODE:
import os
import urllib2
import time
import requests
import urllib3
from random import *
s = requests.Session()
data = {"Username":"username", "Password":"password"}
url = "https://login.url.com"
print "doing things"
r2 = s.post(url, data=data, proxies = {'https' : 'https://PROXYip:PORT'}, verify=False)
#I get a response 200 from printing r2
print r2
downlaod_url = "http://msds.walmartstores.com/client/document?productid=1000527&productguid=54e8aa24-0db4-4973-a81f-87368312069a&DocumentKey=undefined&HazdocumentKey=undefined&MSDS=0&subformat=NAM"
file = open("F:\my_filepath\document" + str(maxCounter) + ".pdf", 'wb')
temp = s.get(download_url, proxies = {'https' : 'https://PROXYip:PORT'}, verify=False)
#This prints out the response from the proxy server (i.e. 200)
print temp
something = uniform(5,6)
print something
time.sleep(something)
#This gets me the content of the web page, not the content of the PDF
print temp.content
file.write(temp.content)
file.close()
I need help figuring out how to "download" the content of the PDF
try this:
import requests
url = 'http://msds.walmartstores.com/client/document?productid=1000527&productguid=54e8aa24-0db4-4973-a81f-87368312069a&DocumentKey=undefined&HazdocumentKey=undefined&MSDS=0&subformat=NAM'
pdf = requests.get(url)
with open('walmart.pdf', 'wb') as file:
file.write(pdf.content)
Edit
Try again with a requests session to manage cookies (assuming they send you those after login) and also maybe a different proxy
proxy_dict = {'https': 'ip:port'}
with requests.Session() as session:
# Authentication request, use GET/POST whatever is needed
# data variable should hold user/password information
auth = session.get(login_url, data=data, proxies=proxy_dict, verify=False)
if auth.status_code == 200:
print(auth.cookies) # Tell me if you got anything
pdf = auth.get('download_url') # Were continuing the same session
with open('walmart.pdf', 'wb') as file:
file.write(pdf.content)
else:
print('No go, got {0} response'.format(auth.status_code))