Created
March 6, 2021 04:42
-
-
Save CaptainZidgel/3eb5c75714c1380f15beaddada483c5f to your computer and use it in GitHub Desktop.
An uploading tool for a forthcoming application - hopefully a useful template for you
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import requests | |
import cmd | |
import os | |
import magic | |
import json | |
import sys | |
URL = "http://127.0.0.1:8080/" | |
def mimetype(path): | |
mime = magic.Magic(mime=True) | |
type = mime.from_file(path) | |
if type != "image/png" and type != "image/jpeg": | |
raise("Image must be a png or jpeg") | |
return type | |
def process(*paths): | |
l = [] | |
for p in paths: | |
if not os.path.isfile(p): | |
raise("Path must be a file") | |
t = mimetype(p) | |
f = open(p, "rb") | |
l.append(("files", (p, f, t))) | |
return l | |
def upload_files(sess, array, desc): | |
r = sess.post(URL+"upload", files=array, data={"desc": desc}) | |
return r | |
def bulk(index, sess): | |
with open(index, 'r') as idx: | |
idx = idx.read() | |
fs = json.loads(idx) | |
for gal in fs["galleries"]: | |
arr = process(*gal["photos"]) | |
desc = gal["desc"] | |
upload_files(sess, arr, desc) | |
class CLI(cmd.Cmd): | |
def __init__(self): | |
cmd.Cmd.__init__(self) | |
self.prompt = "> " | |
self.sess = None | |
def do_quit(self, arg): | |
sys.exit(1) | |
def do_auth(self, creds): | |
c = creds.split() | |
self.sess = requests.Session() | |
self.sess.post(URL+"login", data={"username": c[0], "password": c[1]}) | |
def do_upload(self, target): | |
if os.path.isdir(target) or os.path.splitext(target)[1] == ".json": | |
bulk(target, self.sess) | |
elif os.path.isfile(target): | |
a = process(target) | |
desc = open(target.split(".")[0]+".txt", "r").read() | |
r = upload_files(self.sess, a, desc) | |
print(r.text) | |
else: | |
raise("Target must be a file or folder") | |
''' | |
files = [ | |
("files", ("foo.png", open("foo.png", "rb"), "image/png")) #"files" is the name of the parameter | |
] | |
''' | |
cli = CLI() | |
cli.cmdloop() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
this code SUCKS what the heck!!
who wrote this crap!!!