Skip to content

Instantly share code, notes, and snippets.

@onyx-and-iris
Last active March 21, 2023 17:16
Show Gist options
  • Save onyx-and-iris/de2255ab3a849cc6f8a8d1b5eb470f32 to your computer and use it in GitHub Desktop.
Save onyx-and-iris/de2255ab3a849cc6f8a8d1b5eb470f32 to your computer and use it in GitHub Desktop.
import logging
import time
from pathlib import Path
import requests
from watchdog.events import FileSystemEventHandler
from watchdog.observers import Observer
logging.basicConfig(level=logging.INFO)
class Handler(FileSystemEventHandler):
logger = logging.getLogger("handler")
APIKEYS = ("<file.io apikey>",)
def on_modified(self, event):
p = Path(event.src_path)
if p.is_file() and p.name == "name.log":
filepath = self.get_filepath(p)
self.logger.info(f"posting file {filepath}")
for apikey in self.APIKEYS:
self.post_file(filepath, apikey)
def get_filepath(self, logfile):
with open(logfile, "r") as f:
lines = f.read().splitlines()
last_line = lines[-1]
return last_line.split()[2]
def post_file(self, filepath, apikey):
url = "https://file.io/"
headers = {
"accept": "application/json",
"Authorization": f"Bearer {apikey}",
}
data = {
"expires": "1d",
"maxDownloads": 1,
"autoDelete": True,
}
with open(filepath, "rb") as f:
response = requests.post(
url,
headers=headers,
files={
"file": f,
},
data=data,
)
if response.ok:
self.logger.info("SUCCESS: name: {name}, URL: {link}".format(**response.json()))
else:
self.logger.error(response.status_code)
def main():
event_handler = Handler()
observer = Observer()
observer.schedule(event_handler, path="/path/to/working/directory/", recursive=False)
observer.start()
observer.join()
if __name__ == "__main__":
main()
@onyx-and-iris
Copy link
Author

A small script demonstrating how to upload a file to file.io via its API using python.

Specifically, this script monitors a log file named name.log, parses the filepath in get_filepath() and then posts the file. The file is configured to expire after 1 day, with 1 max download available and autodelete after download.

Multiple accounts can be uploaded to in a single run by adding more apikeys to APIKEYS.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment