本文整理汇总了Python中mimetypes.MimeTypes类的典型用法代码示例。如果您正苦于以下问题:Python MimeTypes类的具体用法?Python MimeTypes怎么用?Python MimeTypes使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了MimeTypes类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: upload_attachment
def upload_attachment(self, file_path):
__, file_name = os.path.split(file_path)
mime = MimeTypes()
url = urllib.pathname2url(file_path)
mime_type, __ = mime.guess_type(url)
data = {
'file_name': file_name,
'file_type': mime_type
}
url = urljoin(self.api_url, 'attachment/upload')
response = self.post(url, data=data)
with open(file_path) as fh:
file_data = fh.read()
upload_response = requests.put(
response['upload_url'],
data=file_data,
headers={'content-type': mime_type},
params={'file': file_path}
)
upload_response.raise_for_status()
return {
'file_url': response['file_url'],
'file_type': mime_type,
}
示例2: mime_type
def mime_type(self):
m = MimeTypes()
m.read(LIASIS_DIR+MIME_TYPES)
if m.guess_type(self.tfile):
return m.guess_type(self.tfile)[0]
else:
return "text/plain"
示例3: get_mime_type
def get_mime_type(path):
mime = MimeTypes()
mime_type = mime.guess_type(path)[0]
if not mime_type:
mime_type = "text/{0}".format(os.path.splitext(path)[1])
return mime_type
示例4: update_community
def update_community(self, properties):
pc = api.portal.get_tool('portal_catalog')
brain = pc.unrestrictedSearchResults(portal_type='ulearn.community',
community_hash=self.params['community'])
if not brain:
brain = pc.unrestrictedSearchResults(portal_type='ulearn.community',
gwuuid=self.params['community'])
if brain:
community = brain[0].getObject()
if properties['title'] is not None:
community.title = properties['title']
if properties['description'] is not None:
community.description = properties['description']
if properties['image'] is not None:
imageObj = ''
mime = MimeTypes()
mime_type = mime.guess_type(properties['image'])
imgName = (properties['image'].split('/')[-1]).decode('utf-8')
imgData = requests.get(properties['image']).content
imageObj = NamedBlobImage(data=imgData,
filename=imgName,
contentType=mime_type[0])
community.image = imageObj
if properties['activity_view'] is not None:
community.activity_view = properties['activity_view']
if properties['twitter_hashtag'] is not None:
community.twitter_hashtag = properties['twitter_hashtag']
if properties['notify_activity_via_push'] is not None:
community.notify_activity_via_push = True if properties['notify_activity_via_push'] == 'True' else None
if properties['notify_activity_via_push_comments_too'] is not None:
community.notify_activity_via_push_comments_too = True if properties['notify_activity_via_push_comments_too'] == 'True' else None
community.reindexObject()
return True
else:
return False
示例5: getMimeType
def getMimeType(self,buffre,url,mtype):
if '?' in url:
url = url.split('?')[0]
mime = MimeTypes()
ext = os.path.splitext(url)[1]
if mtype == 'text/html' and ext == '':
if url[-1] == '/':
l = len(url)-1
url = url[0:-1]
url = url+'/index.html'
ext = '.html'
#ext1 = mime.guess_extension(mtype,True)
#print ext1
mime_type = mime.guess_type(url)
#print url
if ext:
#print url
u = urlparse.urlparse(url)
#print u.netloc,u.path
print self.host
if self.host:
root_dir = self.root_dir+"/"+self.host
file_path = os.path.join(root_dir,u.netloc+u.path)
print file_path
#if not os.path.isfile(file_path):
makeDir(os.path.dirname(file_path))
f = open(file_path,"wb")
f.write(buffre)
示例6: download
def download(request, filename):
#down_file = File.objects.get(name = filename)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
DOWNLOAD_URL = BASE_DIR+"/download/"
file_path = DOWNLOAD_URL + filename
file_name = filename
fp = open(file_path, 'rb')
response = HttpResponse(fp.read())
fp.close()
mime = MimeTypes()
type, encoding = mime.guess_type(file_name)
if type is None:
type = 'application/octet-stream'
response['Content-Type'] = type
response['Content-Length'] = str(os.stat(file_path).st_size)
if encoding is not None:
response['Content-Encoding'] = encoding
if u'WebKit' in request.META['HTTP_USER_AGENT']:
filename_header = 'filename=%s' % file_name.encode('utf-8')
elif u'MSIE' in request.META['HTTP_USER_AGENT']:
filename_header = ''
else:
filename_header = 'filename*=UTF-8\'\'%s' % urllib.quote(file_name.encode('utf-8'))
response['Content-Disposition'] = 'attachment; ' + filename_header
# 記錄系統事件
if is_event_open(request) :
log = Log(user_id=request.user.id, event=u'下載檔案<'+filename+'>')
log.save()
return response
示例7: GetRFC
def GetRFC(rfc_id,file_name,peer_ip,peer_port):
global LRFCdata
global Server
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.settimeout(None)
peer_ipaddr=peer_ip
s.connect((peer_ipaddr,int(peer_port)))
message = ["GETRFC",str(rfc_id),"P2P-DI/1.0","Host: ",IP,"Port: ",PORT,"Title: ",file_name,"Client ID: ",str(self_id)]
s.send(pickle.dumps(message))
os.chdir(os.getcwd())
filename=file_name+".pdf"
file1=open(filename,'wb')
q=s.recv(4096)
q=pickle.loads(q)
if 'FILE NOT FOUND' in q:
code = '404'
phrase = 'FILE NOT FOUND'
reply = ["P2P-DI/1.0 ",str(code),str(phrase)]
PrintResponse(reply,'FILERESPN')
else:
if 'FILE FOUND' in q:
last_modified = q[2]
message = ["OK"]
s.send(pickle.dumps(message))
while True:
q=s.recv(4096)
if q:
file1.write(q)
else:
code = '200'
phrase = 'OK'
mime = MimeTypes()
filesize = os.stat(filename).st_size
mime_type = mime.guess_type(filename)
reply = ["P2P-DI/1.0 ",str(code),str(phrase),"Last-Modified: ",str(last_modified),"Content-Length: ",str(filesize),"Content-Type: ",str(mime_type[0])]
PrintResponse(reply,'FILESENT')
file1.close()
break
serverIP = Server[0]
serverPort = Server[1]
message=["PQUERY","P2P-DI/1.0 ",str(self_id),"Host: ",IP,"Port: ",str(PORT)]
reply = client(message,serverIP,serverPort)
PrintResponse(reply,'PQUERY')
LocalRFC = LocalRFCRecord(rfc_id,file_name)
LRFCdata.append(LocalRFC.getLocalRFC())
Local_linked_list.append(LocalRFC.getLocalRFC())
active_list = reply[4]
active_list=RFCStore(active_list,[[rfc_id,file_name]])
s.close()
示例8: export_warc
def export_warc(self):
# by using select_for_update and checking for existence of this file,
# we make sure that we won't accidentally try to create the file multiple
# times in parallel.
asset = self.assets.select_for_update().first()
if not asset:
return # this is not an old-style Link
if default_storage.exists(self.warc_storage_file()):
return
guid = self.guid
out = self.open_warc_for_writing()
def write_resource_record(file_path, url, content_type):
self.write_warc_resource_record(
default_storage.open(file_path),
url.encode('utf8'),
content_type,
default_storage.created_time(file_path),
out)
def write_metadata_record(metadata, target_headers):
concurrent_to = (v for k, v in target_headers if k == warctools.WarcRecord.ID).next()
warc_date = (v for k, v in target_headers if k == warctools.WarcRecord.DATE).next()
url = (v for k, v in target_headers if k == warctools.WarcRecord.URL).next()
self.write_warc_metadata_record(metadata, url, concurrent_to, warc_date, out)
# write PDF capture
if asset.pdf_capture and ('cap' in asset.pdf_capture or 'upload' in asset.pdf_capture):
file_path = os.path.join(asset.base_storage_path, asset.pdf_capture)
headers = write_resource_record(file_path, "file:///%s/%s" % (guid, asset.pdf_capture), 'application/pdf')
#write_metadata_record({'role':'primary', 'user_upload':asset.user_upload}, headers)
# write image capture (if it's not a PDF thumbnail)
elif (asset.image_capture and ('cap' in asset.image_capture or 'upload' in asset.image_capture)):
file_path = os.path.join(asset.base_storage_path, asset.image_capture)
mime_type = get_mime_type(asset.image_capture)
write_resource_record(file_path, "file:///%s/%s" % (guid, asset.image_capture), mime_type)
if asset.warc_capture:
# write WARC capture
if asset.warc_capture == 'archive.warc.gz':
file_path = os.path.join(asset.base_storage_path, asset.warc_capture)
self.write_warc_raw_data(default_storage.open(file_path), out)
# write wget capture
elif asset.warc_capture == 'source/index.html':
mime = MimeTypes()
for root, dirs, files in default_storage.walk(os.path.join(asset.base_storage_path, 'source')):
rel_path = root.split(asset.base_storage_path, 1)[-1]
for file_name in files:
mime_type = mime.guess_type(file_name)[0]
write_resource_record(os.path.join(root, file_name),
"file:///%s%s/%s" % (guid, rel_path, file_name), mime_type)
self.close_warc_after_writing(out)
# regenerate CDX index
self.cdx_lines.all().delete()
示例9: configure_mimetypes
def configure_mimetypes(extra_types):
"""
Add additional mimetypes to a local MimeTypes instance to avoid polluting
global registery
"""
mimetypes = MimeTypes()
for content_type, extension in extra_types:
mimetypes.add_type(content_type, extension)
return mimetypes
示例10: searchImages
def searchImages(rootDir):
imageList = []
mime = MimeTypes()
for root, subFolders, files in os.walk(rootDir):
for file in files:
mt = mime.guess_type(file)[0]
if mt and mt.startswith('image/'):
imageList = imageList + [os.path.join(root,file)]
return imageList
示例11: get_extension
def get_extension(url):
from mimetypes import MimeTypes
mime_types = MimeTypes()
(type, encoding) = mime_types.guess_type(url)
extensions = mime_types.guess_all_extensions(type)
extension = extensions[-1]
return extension
示例12: add_documents
def add_documents(request, category_id):
if request.is_ajax():
files = request.GET.getlist('files', False)
cat = Category.objects.get(id=category_id)
l_doc = []
l_pdf = []
cmds = []
paths = []
for f in list(files):
mime = MimeTypes()
path = os.path.join(settings.MEDIA_ROOT, settings.UPLOAD_DIR, f)
m = mime.guess_type(path)[0]
d = Document(name=f.encode('ascii', 'ignore'), owner=request.user, refer_category=cat)
d.save()
cat.add_doc(d)
if m == 'application/pdf':
l_pdf.append(([cat], path, f, [d]))
elif m in ['image/png', 'image/jpeg', 'image/bmp']:
im = Image.open(path)
w, h = im.size
new_filename = str(d.id) + '_' + f
new_path = os.path.join(cat.get_absolute_path(), new_filename)
shutil.copy2(path, new_path)
d.add_page(d.get_npages() + 1, new_filename, w, h)
for fu in FileUpload.objects.all():
if fu.file.path == path:
fu.delete()
d.complete = True
d.save()
remove_fileupload([path])
elif m in ['application/msword', 'application/vnd.openxmlformats-officedocument.wordprocessingml.document']:
p = re.compile(r'.[Dd][Oo][Cc][xX]?$')
new_f = p.sub('.pdf', f)
new_path = path.replace(f, new_f)
cmd = 'soffice --headless --convert-to pdf %s --outdir %s/upload' % (path, settings.MEDIA_ROOT)
cmds.append(cmd)
paths.append(path)
l_doc.append(([cat], new_path, new_f, [d]))
elif m in ['application/vnd.ms-excel', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet']:
p = re.compile(r'.[Xx][Ll][Ss][xX]?$')
new_f = p.sub('.pdf', f)
new_path = path.replace(f, new_f)
cmd = 'soffice --headless --convert-to pdf %s --outdir %s/upload' % (path, settings.MEDIA_ROOT)
cmds.append(cmd)
paths.append(path)
l_doc.append(([cat], new_path, new_f, [d]))
else:
print 'ERREUR FORMAT FICHIER'
if len(l_doc):
thread1 = Timer(0, manage_convert_doc_to_pdf, (cmds, paths, l_doc,))
thread1.start()
if len(l_pdf):
thread = Timer(0, manage_convert_pdf_to_jpg, (l_pdf,))
thread.start()
results = {'doc_list': [d.as_json() for d in cat.get_docs()], 'n': cat.count_docs()}
return HttpResponse(json.dumps(results))
示例13: mime
def mime(self):
if self.mMimeType is not None:
return self.mMimeType
mime = MimeTypes()
url = urllib.pathname2url(self.mFullPathName)
self.mMimeType = mime.guess_type(url)[0]
if self.mMimeType is None:
self.mMimeType = "Unkown/None"
return self.mMimeType
示例14: showfile
def showfile(file):
mime = MimeTypes()
mime_type = mime.guess_type(file)
if mime_type[0] is not None and mime_type[0].startswith("image"):
return render_template("image.html",
title="pyle :: preview",
filepath="/data/" + file,
filename=os.path.basename(file))
else:
return readfile(file)
示例15: show_media
def show_media(self, url, title = "", desc ="", loop = 0):
mime = MimeTypes()
mime_type = mime.guess_type(url)
payload = {
"target": url,
"title":title,
"description":desc,
"mimeType": mime_type[0],
"iconSrc":"",
"loop":loop}
command = '{"id":"images","type":"request","uri":"ssap://media.viewer/open","payload":'+ json.dumps(payload)+'}'
self.send_command(command)