Created
February 2, 2022 10:36
-
-
Save jenca-adam/20f29f6180506fceb0b9f7dbbb4a0855 to your computer and use it in GitHub Desktop.
This file contains hidden or 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 random | |
import string | |
import io | |
import os | |
import sys | |
import mimetypes | |
import urllib.request | |
def force_string(anything): | |
if isinstance(anything,str): | |
return anything | |
elif isinstance(anything,bytes): | |
return anything.decode() | |
else: | |
return str(anything) | |
def items(dct): | |
its=[] | |
for k in dct: | |
v=dct[k] | |
if isinstance(v,list) or isinstance(v,tuple): | |
for i in v: | |
its.append([k,i]) | |
else: | |
its.append([k,v]) | |
return its | |
class File(io.IOBase): | |
def __init__(self,buffer,filename,content_type=None): | |
if content_type is None: | |
content_type=force_string(mimetypes.guess_type(os.path.split(filename)[1])[0]) | |
content_type=force_string(content_type) | |
self.size=len(buffer) | |
self.buffer=io.BytesIO(buffer) | |
self.name=force_string(os.path.split(filename)[1]) | |
self.mode='rb' | |
self.content_type=content_type | |
def read(self,size=-1): | |
return self.buffer.read(size) | |
def write(self,anything): | |
raise(io.UnsupportedOperation('not writable')) | |
@classmethod | |
def open(self,file): | |
reader=open(file,'rb') | |
return File(reader.read(),file) | |
def _boundary(): | |
return ''.join(random.choices(string.ascii_letters+string.digits,k=10)) | |
class Maker: | |
def __init__(self,fields,boundary=None): | |
if boundary is None: | |
boundary=_boundary() | |
self.boundary=boundary | |
self.fields=fields | |
self.headers={"Content-Type":"multipart/form-data; boundary="+self.boundary} | |
def make(self): | |
built='' | |
bdr='--'+self.boundary+'\n' | |
for field in items(self.fields): | |
built+=bdr | |
disp='Content-Disposition: form-data; name="'+field[0]+'"' | |
val=field[1] | |
if isinstance(val,File): | |
disp+='; filename="'+val.name+'"\nContent-Type: '+val.content_type | |
val=val.read().decode() | |
disp+='\n\n' | |
disp+=val+'\n' | |
built+=disp | |
built+=bdr.strip()+'--' | |
return built.encode() | |
def urllib_send_files(data): | |
maker=Maker(data) | |
headers,built=maker.headers,maker.make() | |
origh={"Content-Type":"multipart/form-data"} | |
origh.update(headers) | |
req=urllib.request.Request(url, | |
data, | |
headers=origh | |
) | |
urlopen=urllib.request.urlopen(req) | |
return urlopen.read() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment