-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.py
151 lines (126 loc) · 4.95 KB
/
main.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
# used by OTALA written by ciscoquan--2025
import requests
import time
import json
import mimetypes
class Pinata:
"""
A client for interacting with the Pinata IPFS API.
This class provides methods to upload files to IPFS through Pinata and generate
signed URLs for accessing the uploaded content.
Attributes:
headers (dict): Authorization headers for API requests
"""
def __init__(self, bearer_token):
"""
Initialize the Pinata client with authentication.
Args:
bearer_token (str): The Pinata Bearer token for API authentication
"""
self.headers = {"Authorization": "Bearer {0}".format(bearer_token)}
def upload_files(
self, uploaded_file, filename: str, mime: str = None
) -> str:
"""
Upload a file to IPFS through Pinata's API.
Args:
uploaded_file: A file-like object opened in binary mode
filename (str): The name of the file to be uploaded
mime (str, optional): The MIME type of the file. If not provided,
it will be automatically detected
Returns:
str: The CID (Content Identifier) of the uploaded file if successful,
None if the upload fails
Examples:
>>> with open('image.jpg', 'rb') as f:
... cid = pinata.upload_files(f, 'image.jpg', 'image/jpeg')
>>> print(cid)
'QmX...'
"""
api_url = "https://uploads.pinata.cloud/v3/files"
# Guess MIME type if not provided
if mime is None:
mime, _ = mimetypes.guess_type(filename)
if mime is None:
mime = "application/octet-stream" # Fallback MIME type
try:
files = [
("file", (filename, uploaded_file, mime))
] # Directly use the file-like object
# Debugging: Print request details
print(f"Filename: {filename}")
print(f"MIME type: {mime}")
print(f"File object: {uploaded_file}")
response = requests.post(
api_url,
headers=self.headers,
data={}, # Explicitly set data to an empty dictionary
files=files,
)
response.raise_for_status() # Raise an exception for bad status codes (4xx or 5xx)
print("File uploaded successfully!")
data = response.json()
cid = data["data"]["cid"]
return cid
except requests.exceptions.RequestException as e:
print(f"Error uploading file: {e}")
if response is not None:
print(
f"Response content: {response.text}"
) # Print response for debugging
return None
except Exception as e:
print(f"A general error occurred: {e}")
return None
def retrieve_file_url(
self,
gateway_url: str,
cid: str,
method: str = "GET",
expires: int = 31536000,
) -> str:
"""
Generate a signed URL for accessing an uploaded file.
Args:
gateway_url (str): The base gateway URL for accessing the file
cid (str): The Content Identifier (CID) of the uploaded file
method (str, optional): HTTP method for the signed URL. Defaults to "GET"
expires (int, optional): URL expiration time in seconds. Defaults to 1 year
Returns:
str: A signed URL if successful, None if the operation fails
Examples:
>>> url = pinata.retrieve_file_url(
... "https://gateway.pinata.cloud/",
... "QmX...",
... expires=3600
... )
>>> print(url)
'https://gateway.pinata.cloud/QmX...?signature=...'
"""
self.headers.update({"Content-Type": "application/json"})
current_timestamp = int(time.time())
api_url = "https://api.pinata.cloud/v3/files/sign"
try:
data = json.dumps(
{
"url": gateway_url + cid,
"method": method,
"expires": expires,
"date": current_timestamp,
}
)
response = requests.post(api_url, data=data, headers=self.headers)
response.raise_for_status() # Raise an exception for bad status codes (4xx or 5xx)
print("File uploaded successfully!")
data = response.json()
return data["data"]
except requests.exceptions.RequestException as e:
print(f"Error uploading file: {e}")
if response is not None:
print(
f"Response content: {response.text}"
) # Print response for debugging
return None
except Exception as e:
print(f"A general error occurred: {e}")
return None