How do I serve this video file for download using pyramid FileResponse - pyramid

Please what am i missing. I keep on getting internal server error in browser when I want to serve this video file that has been downloaded on disk.
here is my code: The view function
#view_config(name='download_video')
def dl(request):
url = request.params.get('url')
camefrom = request.params.get('came_from')
path_dir = request.registry.settings['app.download_path']
result= save_to_disk(url, path_dir)
if result:
filename = result['filename']
filepath = os.path.abspath(os.path.join(path_dir,filename))
file_exists = os.path.exists(filepath)
if file_exists:
res = FileResponse(filepath,content_type='video/mp4')
res.headers['Content-Length'] = os.path.getsize(filepath)
res.headers['Content-Disposition'] = 'attachment;filename=%s'%filename
return res
request.session.flash(_("Error downloading video, please check your network","danger"))
return HTTPFound(location=camefrom)
The template
<a tal:attributes="href api.url(api.root, '##download_video', query={'came_from': request.url,'url':context.video_url})" class="btn">Download</a>
The video downloads and I can see it in the folder but I keep on getting internal server error without tracebacks on browser
My app depends on Kotti cms

I'm m not sure what's going on with your Pyramid logging but here is my view for downloading a file. I'm currently on an iPhone so I just cut and pasted but you should get the idea.
#view_config(route_name="download_view", renderer="")
def server_view1010(request):
filepath = os.path.join(CFG.home_dir, "static/graphics/imgs/img_sample.jpg")
if request.storage.exists(filepath): #there is no overwrite
response = FileResponse(filepath)
response.headers['Content-Disposition'] = ("attachment; filename=img_sample.jpg")
return response
else:
return Response("Unable to find: {}".format(request.path_info))

Related

Uploading file to Sharepoint is failing with "HTTPError: 400 Client Error: Bad Request for url: " in python

I am trying to upload a file into Sharepoint but the code fails with the below error code.
office365.runtime.client_request_exception.ClientRequestException: ('-2147024809, System.ArgumentException', 'Server relative urls must start with SPWeb.ServerRelativeUrl', "400 Client Error: Bad Request for url: https://<company_name>.sharepoint.com/sites/<site_folder>/_api/Web/getFolderByServerRelativeUrl('Shared%20Documents%2FGeneral%2F3.%20PAYMENTS%20Operations%2FTIES%2FCRS%20Report%20files')/Files/add(overwrite=true,url='%2Ftmp%2Ftmp1lsc2asr%2FXML_REPORT_df185e51-2df0-48be-ad7f-cf8a3ae31914.xml')")
I am trying to upload a file in sharepoint with the below folder structure.
Shared Documents > General > 3. PYAMENTS Operations > TIES > CRS Report files
I have written the below code snippet to upload a file into sharepoint. Please let me know where I am going wrong.
full_url = f'https://<company_name>.sharepoint.com/sites/<site_folder>/'
relative_url = f'Shared Documents/General/3.PAYMENTS Operations/TIES/CRS Report files'
ctx = get_sharepoint_context_using_user()
print(ctx)
target_folder = ctx.web.get_folder_by_server_relative_url(relative_url)
print(target_folder)
# Open file in binary mode
with open(temp_file, 'rb') as content_file:
file_content = content_file.read()
#print(file_content)
target_folder.upload_file(temp_file, file_content).execute_query()

upload image from url to wordpress using rest api and python

I'm trying to upload image from url to wordpress without saving it in my device using python and rest api , i'm really close to achive that i just can't find where i'm lost
i keep getting 500 and this error :
{"code":"rest_upload_unknown_error","message":"Sorry, you are not allowed to upload this file type.","data":{"status":500}}
my code :
import base64, requests
def header(user, password):
credentials = user + ':' + password
token = base64.b64encode(credentials.encode())
header_json = {'Authorization': 'Basic ' + token.decode('utf-8'),
'Content-Disposition' : 'attachment; filename=%s'% "test1.jpg"}
return header_json
def upload_image_to_wordpress(file_path, header_json):
media = {'file': file_path,'caption': 'My great demo picture'}
responce = requests.post("https://website.com/wp-json/wp/v2/media", headers = header_json, files = media)
print(responce.text)
heder = header("user","password") #username, application password
url = "https://cdn.pixabay.com/photo/2021/11/30/08/24/strawberries-6834750_1280.jpg"
raw = requests.get(url).content
upload_image_to_wordpress(raw,heder)
after trying many solutions i found out working one
from tempfile import NamedTemporaryFile
url = "https://cdn.pixabay.com/photo/2021/11/30/08/24/strawberries-6834750_1280.jpg"
raw = requests.get(url).content
with NamedTemporaryFile(delete=False,mode="wb",suffix=".jpg") as img :
img.write(raw)
# print(f.file())
c = open(img.name,"rb")
upload_image_to_wordpress(c,heder)

Flask file upload returns error 405 method not allowed

The code below is endpoint used to upload images for a transaction in site am working but for some reason it keeps returning 405 error when a file attached to the request but works like it should when it isnt. So the code works locally and another server(used a similar code for site) but not on control server.
#bp.route("/transaction/<int:transaction_id>/image", methods=['PUT'])
def upload_image_ex(transaction_id):
transaction = Transaction.query.get(transaction_id)
if not transaction:
return jsonify(status='failed', message='Transaction Not Found!')
if transaction.status != 0:
return jsonify(status='failed', message='Transaction No Longer Pending!')
if 'images[]' not in request.files:
return jsonify(status='failed', message='No image uploaded!')
files = request.files.getlist('images[]')
for file in files:
print("dayer")
unique_filename = str(uuid.uuid4()) + '.' + \
file.filename.rsplit('.', 1)[1].lower()
print("dayer")
file.save(os.path.join(Config.POST_UPLOAD_FOLDER, unique_filename))
print("dayer")
save_image(
unique_filename,
file,
Config.POST_UPLOAD_FOLDER,
Config.BANNER_SIZE,
isByte=False
)
img = TransactionImage()
img.img = unique_filename
img.transaction_id = transaction_id
db.session.add(img)
db.session.commit()
return jsonify(
status='success',
message='Transaction Image Uploaded',
data=TransactionSchema().dump(transaction)
)
Check your frontend call, if the method is PUT.
Check the reverse proxy like nginx on your server if it changed the location or methods of the call.
Try add POST, PATCH ... methods into your route to address the problem. #bp.route("/transaction/<int:transaction_id>/image", methods=['PUT', 'POST', 'PATCH'])

Upload file to AWS Device Farm

I am trying to use python + boto3 to create upload in device farm (uploading a test or an application). The method "create_upload" works fine as it returns an upload arn and url to upload to it.
When I try to use requests to upload file to this URL I get an error:
<Error><Code>SignatureDoesNotMatch</Code><Message>The request signature we calculated does not match the signature you provided. Check your key and signing method.</Message><AWSAccessKeyId>AKIAJV4C3CWPBUMBC3GA</AWSAccessKeyId><StringToSign>AWS4-HMAC-SHA256
My code:
response = client.create_upload(
projectArn=df_project,
name="test.zip",
type="APPIUM_JAVA_TESTNG_TEST_PACKAGE",
contentType='application/octet-stream'
)
test_url = response["upload"]["url"]
files = {'upload_file': open('/tmp/test.zip','rb')}
r = requests.post(test_url, files=files, data={})
Also i tried using curl, and requests.post passing the file to the data
attribut:
r = requests.put(test_url, data=open("/tmp/test.zip", "rb").read())
print(r.text)
and
cmd = "curl --request PUT --upload-file /tmp/test.zip \""+test_url+"\""
result = subprocess.call(cmd, shell=True)
print(result)
I did this before in a past project. Here is a code snippet of how I did it:
create a new upload
#http://boto3.readthedocs.io/en/latest/reference/services/devicefarm.html#DeviceFarm.Client.create_upload
print('Creating the upload presigned url')
response = client.create_upload(projectArn=args.projectARN,name=str(args.testPackageZip),type='APPIUM_WEB_JAVA_TESTNG_TEST_PACKAGE')
#create the s3 bucket to store the upload test suite
uploadArn = response['upload']['arn']
preSignedUrl = response['upload']['url']
print('uploadArn: ' + uploadArn + '\n')
print('pre-signed url: ' + preSignedUrl + '\n')
#print the status of the upload
#http://boto3.readthedocs.io/en/latest/reference/services/devicefarm.html#DeviceFarm.Client.get_upload
status = client.get_upload(arn=uploadArn)
print("S3 Upload Bucket Status: " + status['upload']['status'] + '\n')
print("Uploading file...")
#open the file and make payload
payload = {'file':open(args.testPackageZip,'rb')}
#try and perform the upload
r = requests.put(url = preSignedUrl,files = payload)
#print the response code back
print(r)
Hope that helps
I work for AWS Device Farm. This problem occurs when some of the request parameters don't match what was used to sign the URL. The times that I have seen this issue, it has to do with the content type. I would suggest not passing it in the CreateUpload request. If you do pass it, then you'll also need to include that as a request header when making the PUT call.

How to download the PDF by using Selenium Module (FireFox) in Python 3

I want to download a PDF which is from an Online-Magazin. In order to open it, must log in first. Then open the PDF and download it.
The following is my code. It can login to the page and the PDF can also be open. But the PDF can not be downloaded since I am not sure how to simulate the click on Save. I use FireFox.
import os, time
from selenium import webdriver
from bs4 import BeautifulSoup
# Use firefox dowmloader to get file
fp = webdriver.FirefoxProfile()
fp.set_preference("browser.download.folderList",2)
fp.set_preference("browser.download.manager.showWhenStarting",False)
fp.set_preference("browser.download.dir", 'D:/eBooks/Stocks_andCommodities/2008/Jul/')
fp.set_preference("browser.helperApps.neverAsk.saveToDisk", "application/pdf")
fp.set_preference("pdfjs.disabled", "true")
# disable Adobe Acrobat PDF preview plugin
fp.set_preference("plugin.scan.plid.all", "false")
fp.set_preference("plugin.scan.Acrobat", "99.0")
browser = webdriver.Firefox(firefox_profile=fp)
# Get the login web page
web_url = 'http://technical.traders.com/sub/sublogin2.asp'
browser.get(web_url)
# SImulate the authentication
user_name = browser.find_element_by_css_selector('#SubID > input[type="text"]')
user_name.send_keys("thomas2003#test.net")
password = browser.find_element_by_css_selector('#SubName > input[type="text"]')
password.send_keys("LastName")
time.sleep(2)
submit = browser.find_element_by_css_selector('#SubButton > input[type="submit"]')
submit.click()
time.sleep(2)
# Open the PDF for downloading
url = 'http://technical.traders.com/archive/articlefinal.asp?file=\V26\C07\\131INTR.pdf'
browser.get(url)
time.sleep(10)
# How to simulate the Clicking to Save/Download the PDF here?
You should not open the file in browser. Once you have the file url. Get a request session with all the cookies
def get_request_session(driver):
import requests
session = requests.Session()
for cookie in driver.get_cookies():
session.cookies.set(cookie['name'], cookie['value'])
return session
Once you have the session you can download the file using the same
url = 'http://technical.traders.com/archive/articlefinal.asp?file=\V26\C07\\131INTR.pdf'
session = get_request_session(driver)
r = session.get(url, stream=True)
chunk_size = 2000
with open('/tmp/mypdf.pdf', 'wb') as file:
for chunk in r.iter_content(chunk_size):
file.write(chunk)
Apart from Tarun's solution, you can also download the file through js and store it as a blob. Then you can extract the data into python via selinium's execute script as shown in this answer.
In you case,
url = 'http://technical.traders.com/archive/articlefinal.asp?file=\V26\C07\\131INTR.pdf'
browser.execute_script("""
window.file_contents = null;
var xhr = new XMLHttpRequest();
xhr.responseType = 'blob';
xhr.onload = function() {
var reader = new FileReader();
reader.onloadend = function() {
window.file_contents = reader.result;
};
reader.readAsDataURL(xhr.response);
};
xhr.open('GET', %(download_url)s);
xhr.send();
""".replace('\r\n', ' ').replace('\r', ' ').replace('\n', ' ') % {
'download_url': json.dumps(url),
})
Now your data exists as a blob on the window object, so you can easily extract into python:
time.sleep(3)
downloaded_file = driver.execute_script("return (window.file_contents !== null ? window.file_contents.split(',')[1] : null);")
with open('/Users/Chetan/Desktop/dummy.pdf', 'wb') as f:
f.write(base64.b64decode(downloaded_file))
Try
import urllib
file_path = "<FILE PATH TO SAVE>"
urllib.urlretrieve(<pdf_link>,file_path)

Resources