Pyt yandexdisk file?
To upload files to Yandex.Disk programmatically using Python, you can utilize the Yandex.Disk API. Below is a step-by-step guide on how to do this, including installation of required libraries and an example code snippet.
Step 1: Set Up Yandex.Disk
- Create a Yandex.Disk account if you don’t already have one.
- Create an OAuth token:
- Go to the Yandex account management page.
- Click on "Create a new application".
- Select
Web applicationorScriptdepending on your use case. - After creating the application, note the
OAuth token. This will be needed for authentication.
Step 2: Install Required Libraries
You can use the requests library to interact with the Yandex.Disk API.
pip install requests
Step 3: Example Code to Upload a File
Here’s a simple example of how to upload a file to Yandex.Disk using Python:
import requests
def upload_to_yandex_disk(token, file_path, disk_path):
# Get the upload URL
upload_url = 'https://cloud-api.yandex.net/v1/disk/resources/upload'
headers = {'Authorization': f'OAuth {token}'}
params = {
'path': disk_path,
'overwrite': 'true'
}
response = requests.get(upload_url, headers=headers, params=params)
if response.status_code != 200:
print("Error getting upload URL:", response.json())
return
upload_url = response.json().get('href')
# Upload the file
with open(file_path, 'rb') as file:
upload_response = requests.put(upload_url, files={'file': file})
if upload_response.status_code == 201:
print("File uploaded successfully!")
else:
print("Error uploading file:", upload_response.json())
# Usage example
if __name__ == '__main__':
OAUTH_TOKEN = 'YOUR_OAUTH_TOKEN' # Replace with your actual OAuth token
FILE_TO_UPLOAD = 'local_file.txt' # Local file to upload
DISK_PATH = 'disk_file.txt' # Path in Yandex.Disk
upload_to_yandex_disk(OAUTH_TOKEN, FILE_TO_UPLOAD, DISK_PATH)
Explanation of the Code
- Get Upload URL: Send a GET request to the Yandex.Disk API to get the upload URL for your file.
- Upload File: Open the file in binary mode and use a PUT request to upload the file to the URL obtained in the previous step.
- Check Response: The response status code is checked to determine if the upload was successful.
Notes
- Ensure the paths (
file_pathanddisk_path) you provide are correct. - The uploaded file will overwrite any existing file with the same name in the specified disk path if you set
overwrite: true. - Handle exceptions and errors as needed for robustness.
This should get you started with uploading files to Yandex.Disk using Python!