当前位置: 首页>>代码示例>>Python>>正文


Python mimetypes.init函数代码示例

本文整理汇总了Python中mimetypes.init函数的典型用法代码示例。如果您正苦于以下问题:Python init函数的具体用法?Python init怎么用?Python init使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。


在下文中一共展示了init函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: ziplib

def ziplib(config, handle):
  """
  Function to unpack a downloaded zip file by exploding it into multiple handles.
  zip_unpack: Unpack if true
  """
  import zipfile
  import calendar
  import mimetypes

  mimetypes.init()

  if not config.get("zip_unpack", False):
    yield handle
    return

  logger.info("Extracting since zip_unpack = true");

  z = zipfile.ZipFile(handle.fileobj)

  def convert(dt):
    """
    Convert a ZipInfo date_time into a unix timestamp (compatible with tar).
    """
    return calendar.timegm(dt)

  for i in z.infolist():
    mime = mimetypes.guess_type(i.filename)[0]
    yield ExtHandle(i.filename, i.file_size, convert(i.date_time), mime, z.open(i))

  return
开发者ID:pestro,项目名称:pusher,代码行数:30,代码来源:extlib.py

示例2: create_server

def create_server(ui, app):

    if ui.config('web', 'certificate'):
        if sys.version_info >= (2, 6):
            handler = _httprequesthandlerssl
        else:
            handler = _httprequesthandleropenssl
    else:
        handler = _httprequesthandler

    if ui.configbool('web', 'ipv6'):
        cls = IPv6HTTPServer
    else:
        cls = MercurialHTTPServer

    # ugly hack due to python issue5853 (for threaded use)
    import mimetypes; mimetypes.init()

    address = ui.config('web', 'address', '')
    port = util.getport(ui.config('web', 'port', 8000))
    try:
        return cls(ui, app, (address, port), handler)
    except socket.error, inst:
        raise util.Abort(_("cannot start server at '%s:%d': %s")
                         % (address, port, inst.args[1]))
开发者ID:jordigh,项目名称:mercurial-crew,代码行数:25,代码来源:server.py

示例3: __init__

    def __init__(self):

        remuco.PlayerAdapter.__init__(
            self,
            "Totem",
            mime_types=("audio", "video"),
            volume_known=True,
            playback_known=True,
            progress_known=True,
            file_actions=FILE_ACTIONS,
        )

        self.__to = None

        self.__signal_ids = ()

        self.__update_item = False
        self.__md_album = None
        self.__md_artist = None
        self.__md_title = None
        self.__last_mrl = None

        self.__seek_step_initial = 5000
        self.__seek_step = self.__seek_step_initial
        self.__css_sid = 0

        if not mimetypes.inited:
            mimetypes.init()
开发者ID:sayanriju,项目名称:remuco,代码行数:28,代码来源:remotem.py

示例4: get_file_types_list

	def get_file_types_list(self):
		file_list = self.get_file_list()
		if not file_list[0][1].has_key('mimetype'):
			mimetypes.init()
			for item in file_list:
				item[1]['mimetype'] = mimetypes.guess_type(item[0])[0]
		return file_list
开发者ID:ffagerho,项目名称:metrics-tools,代码行数:7,代码来源:metrics.py

示例5: GoogleSitesLogin

def GoogleSitesLogin(site_name=None, site_domain=None, debug=False):
    if site_domain is None:
        raise ValueError("site_domain is not valid")
    if site_name is None:
        raise ValueError("site_name is not valid")

    mimetypes.init()

    client = gdata.sites.client.SitesClient( source="wiki-push",
                                             site=site_name,
                                             domain=site_domain )
    client.http_client.debug = debug

    try:
        gdata.sample_util.authorize_client( client,
                        auth_type=gdata.sample_util.CLIENT_LOGIN,
                        service=client.auth_service,
                        source="wiki-push",
                        scopes=['http://sites.google.com/feeds/',
                                'https://sites.google.com/feeds/'] )
    except gdata.client.BadAuthentication:
        print "Invalid user credentials given."
        return None
    except gdata.client.Error:
        print "Login Error."
        return None

    return client
开发者ID:ericggregory,项目名称:gollumwiki-to-googlesites,代码行数:28,代码来源:gollumwiki-to-googlesites.py

示例6: main

def main():

    mimetypes.init()

    for info in scan_dir(sys.argv[1]):
       #add_file(info)
        print info['name'], datetime.fromtimestamp(info['mtime']).strftime('%d-%m-%Y')
开发者ID:Kristina-B,项目名称:Different-files,代码行数:7,代码来源:sync.py

示例7: handle_noargs

    def handle_noargs(self, **options):
        mimetypes.init()

        locked_print("===> Syncing static directory")
        pool = ThreadPool(20)

        # Sync every file in the static media dir with S3
        def pooled_sync_file(base, filename):
            pool.apply_async(self.sync_file, args=[base, filename])

        self.walk_tree([conf.SIMPLESTATIC_DIR], pooled_sync_file)
        pool.close()
        pool.join()
        locked_print("===> Static directory syncing complete")

        locked_print("===> Compressing and uploading CSS and JS")
        pool = ThreadPool(20)

        # Iterate over every template, looking for SimpleStaticNode
        def pooled_handle_template(base, filename):
            pool.apply_async(self.handle_template, args=[base, filename])

        self.walk_tree(list(settings.TEMPLATE_DIRS), pooled_handle_template)
        pool.close()
        pool.join()
        locked_print("===> Finished compressing and uploading CSS and JS")
开发者ID:ericflo,项目名称:django-simplestatic,代码行数:26,代码来源:static_sync.py

示例8: run

    def run(self):
        mimetypes.init()
        log.debug("Initialized mime type database.")
        screenshot_tube = self.config.get('beanstalk', 'screenshot_tube')
        self.beanstalk = politwoops.utils.beanstalk(
            host=self.config.get('beanstalk', 'host'),
            port=int(self.config.get('beanstalk', 'port')),
            watch=screenshot_tube,
            use=None)
        log.debug("Connected to queue.")

        while True:
            time.sleep(0.2)
            self.heart.beat()
            reserve_timeout = max(self.heart.interval.total_seconds() * 0.1, 2)
            job = self.beanstalk.reserve(timeout=reserve_timeout)
            if job:
                try:
                    tweet = anyjson.deserialize(job.body)
                    self.process_entities(tweet)
                    job.delete()
                except Exception as e:
                    log.error("Exception caught, burying screenshot job for tweet {tweet}: {e}",
                              tweet=tweet.get('id'), e=e)
                    job.bury()
开发者ID:monkeycycle,项目名称:politwoops-tweet-collector,代码行数:25,代码来源:screenshot-worker.py

示例9: __call__

    def __call__(self, value, *args, **kwargs):
        """
        :param value:
        :type value: :class:`list` of :class:`dict`
        :return:
        :rtype: :class:`django.forms.Form`
        """
        if value is None:
            return self.form_cls(*args, **kwargs)

        post_data = QueryDict("", mutable=True)
        file_data = QueryDict("", mutable=True)
        for obj in value:
            name = obj["name"]
            value = obj["value"]
            if name in self.form_cls.base_fields and isinstance(
                self.form_cls.base_fields[name], FileField
            ):
                mimetypes.init()
                basename = os.path.basename(value)
                (type_, __) = mimetypes.guess_type(basename)
                # it's a file => we need to simulate an uploaded one
                content = InMemoryUploadedFile(
                    io.BytesIO(b"\0"),
                    name,
                    basename,
                    type_ or "application/binary",
                    1,
                    "utf-8",
                )
                file_data.update({name: content})
            else:
                post_data.update({name: value})
        return self.form_cls(post_data, file_data, *args, **kwargs)
开发者ID:d9pouces,项目名称:django-floor,代码行数:34,代码来源:decorators.py

示例10: mimetype

 def mimetype(self):
     try:
         mimetypes.init()
         type = mimetypes.guess_type(self.file.name)[0]
     except:
         type = None
     return type
开发者ID:kawazrepos,项目名称:Kawaz2nd,代码行数:7,代码来源:models.py

示例11: encoding

 def encoding(self):
     try:
         mimetypes.init()
         encoding = mimetypes.guess_type(self.file.name)[1]
     except:
         encoding = None
     return encoding
开发者ID:kawazrepos,项目名称:Kawaz2nd,代码行数:7,代码来源:models.py

示例12: get_file_mimetype

 def get_file_mimetype(path):
     """
     Returns file mimetype
     """
     filename, file_extension = os.path.splitext(path)
     mimetypes.init()
     return mimetypes.types_map[file_extension]
开发者ID:DimaSavkov,项目名称:simple_http,代码行数:7,代码来源:storage.py

示例13: get_resource_content

def get_resource_content(request, source_name):
    """
        Returns the actual resource.
        Tries to guess the mimetype. If it fails, returns 
        application/octet-stream as fallback.
    """
    import mimetypes
    mimetypes.init()
    resource_id = request.GET.get('resource_id', None)
    if not resource_id:
        raise Http404

    try:
        source = Source.objects.get(name=source_name)
    except Source.DoesNotExist:
        response_data = {'error': 'Source not found'}
    else:
        response_data = Backend(source.backend_id).get_resource_content(source, resource_id)
        
    if 'content' in response_data.keys():
        content = response_data['content']
        mimetype, encoding = mimetypes.guess_type(response_data['name'])
        if not mimetype:
            mimetype = 'application/octet-stream'
    else:
        content = response_data
        mimetype = "application/json"
    return HttpResponse(content, mimetype=mimetype)
开发者ID:adieyal,项目名称:docrepo-backend,代码行数:28,代码来源:views.py

示例14: _ContentType

def _ContentType(requestedfile):
	"""
	Guess the file type based on the extension. This will be used 
	to decide whether to open the file in text or binary mode.
	"""

	base, ext = posixpath.splitext(requestedfile)

	# This uses the standard MIME types mapping library. If it isn't 
	# found, we check to see if it is xhtml (which might not be in the
	# local mime types library). If the type still is not found, it 
	# defaults to plain text.
	mimetypes.init()
	try:
		ctype = mimetypes.types_map[ext]
	except:
		if (ext.lower() == '.xhtml'):
			ctype = 'application/xhtml+xml'
		else:
			ctype = 'text/plain'

	# We need to augment this information with a set of image
	# types to use for the file mode.
	if (ext in ['.png', '.PNG', '.gif', '.GIF', '.jpeg', '.JPEG', 
		'.jpg', '.JPG']):
		fmode = 'rb'
	else:
		fmode = 'r'

	return fmode, ctype
开发者ID:ssrselvamraju,项目名称:mblogic-S2-client,代码行数:30,代码来源:MBWebPage.py

示例15: GET

    def GET(self, courseid, taskid, path):
        """ GET request """
        if User.is_logged_in():
            try:
                course = FrontendCourse(courseid)
                if not course.is_open_to_user(User.get_username()):
                    return renderer.course_unavailable()

                task = course.get_task(taskid)
                if not task.is_visible_by_user(User.get_username()):
                    return renderer.task_unavailable()

                path_norm = posixpath.normpath(urllib.unquote(path))
                public_folder_path = os.path.normpath(os.path.realpath(os.path.join(INGIniousConfiguration["tasks_directory"], courseid, taskid, "public")))
                file_path = os.path.normpath(os.path.realpath(os.path.join(public_folder_path, path_norm)))

                # Verify that we are still inside the public directory
                if os.path.normpath(os.path.commonprefix([public_folder_path, file_path])) != public_folder_path:
                    raise web.notfound()

                if os.path.isfile(file_path):
                    mimetypes.init()
                    mime_type = mimetypes.guess_type(file_path)
                    web.header('Content-Type', mime_type[0])
                    with open(file_path) as static_file:
                        return static_file.read()
                else:
                    raise web.notfound()
            except:
                if web.config.debug:
                    raise
                else:
                    raise web.notfound()
        else:
            return renderer.index(False)
开发者ID:GuillaumeDerval,项目名称:INGInious,代码行数:35,代码来源:tasks.py


注:本文中的mimetypes.init函数示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。