chatgpt/pastedb/example_post_multi_handling.py

72 lines
2.4 KiB
Python
Raw Normal View History

import json
import hashlib
import requests
import time
import random
# Function to generate a unique name for the upload
def generate_upload_name():
timestamp = int(time.time())
rand_str = ''.join(random.choices('abcdefghijklmnopqrstuvwxyz', k=3))
return f"{timestamp}-{rand_str}"
# Function to upload JSON data to termbin
def upload_to_termbin(data):
try:
resp = requests.post('https://termbin.com', data=data.encode('utf-8'), timeout=5)
if resp.status_code == 200:
key = resp.text.strip()
md5sum = hashlib.md5(data.encode('utf-8')).hexdigest()
return {'service': 'termbin', 'key': key, 'md5sum': md5sum}
else:
print(f"Failed to upload to termbin.com. Response code: {resp.status_code}")
return None
except requests.exceptions.RequestException as e:
print(f"Failed to upload to termbin.com. Error: {str(e)}")
return None
# Function to upload JSON data to pastie
def upload_to_pastie(data):
try:
resp = requests.post('https://pastie.io/documents', data=data.encode('utf-8'), timeout=5)
if resp.status_code == 200:
key = resp.json()['key']
md5sum = hashlib.md5(data.encode('utf-8')).hexdigest()
return {'service': 'pastie', 'key': key, 'md5sum': md5sum}
else:
print(f"Failed to upload to pastie.io. Response code: {resp.status_code}")
return None
except requests.exceptions.RequestException as e:
print(f"Failed to upload to pastie.io. Error: {str(e)}")
return None
# Upload data to both termbin and pastie
def upload_data_to_services(data):
upload_name = generate_upload_name()
print(f"\nUploading data to services with name {upload_name}...\n")
paste_dict = {'name': upload_name}
services = {'termbin': upload_to_termbin, 'pastie': upload_to_pastie}
for service, upload_function in services.items():
result = upload_function(data)
if result is not None:
paste_dict[service] = result
print(f"JSON object uploaded to {service}: https://{service}.com/{result['key']}")
with open('paste_dict.json', 'a+') as f:
f.write(json.dumps(paste_dict) + '\n')
print(f"\nUploads completed successfully.")
# Test function
def test():
data = '{"name": "John Doe", "age": 30, "city": "New York"}'
upload_data_to_services(data)
if __name__ == '__main__':
test()