简单上传文件(https://www.qcloud.com/document/product/436/6066)

        :param real_file_path: 文件的物理地址
        :param file_name: 文件名称
        :param dir_name: 文件夹名称（可选）
        :return:json数据串
359218
def upload_file(self, real_file_path, file_name, dir_name=None):
        

        if dir_name is not None and dir_name[0] == '/':
            dir_name = dir_name[1:len(dir_name)]
        if dir_name is None:
            dir_name = ""
        self.url = 'http://' + self.config.region + '.file.myqcloud.com/files/v2/' + str(self.config.app_id) + '/' + self.config.bucket
        if dir_name is not None:
            self.url = self.url + '/' + dir_name
        self.url = self.url + '/' + file_name
        headers = {}
        headers['Authorization'] = CosAuth(self.config).sign_more(self.config.bucket, '', 30)
        files = {'file': ('', open(real_file_path, 'rb'))}
        r = requests.post(url=self.url, data={'op': 'upload', 'biz_attr': '', 'insertOnly': '0'}, files={
            'filecontent': (real_file_path, open(real_file_path, 'rb'), 'application/octet-stream')}, headers=headers)
        return str(eval(r.content.decode('utf8')).get('data'))
440674
def dl_full_file(url, save_file_name):
    
    response = requests.get(url)
    with open(save_file_name, 'wb') as writefile:
        writefile.write(response.content)

    return
847264
def rel_path(*file_path):
        '''
        
        '''
        if hasattr(sys, 'frozen'):
            if file_path[0] == '__file__':
                return sys.executable
            return os.path.join(os.path.dirname(sys.executable), *file_path)
        else:
            try:
                main_file = AppBuilder.main_file
            except AttributeError:
                # The first call setting up the instance
                main_file = inspect.stack()[1][1]
            if file_path[0] == '__file__':
                return os.path.realpath(main_file)
            return os.path.join(os.path.dirname(main_file), *file_path)
794347
def verify_file_exists(file_name, file_location):
    
    return __os.path.isfile(__os.path.join(file_location, file_name))
385684
def write(file_name)
      # Encode json string:
      str = JSON.pretty_generate(@dictionary)
      # Create directory if needed:
      unless File.directory?(File.dirname(file_name))
        require 'fileutils'
        FileUtils.mkdir_p(File.dirname(file_name))
      end
      # Write to file:
      File.open(file_name, 'w') {|f| f.write(str) }
    end
300080
def choose_path():
    
    dirs = webview.create_file_dialog(webview.FOLDER_DIALOG)
    if dirs and len(dirs) > 0:
        directory = dirs[0]
        if isinstance(directory, bytes):
            directory = directory.decode("utf-8")

        response = {"status": "ok", "directory": directory}
    else:
        response = {"status": "cancel"}

    return jsonify(response)
756828
def __parse_json_file(self, file_path):
        
        if file_path == '' or os.path.splitext(file_path)[1] != '.json':
            raise IOError('Invalid Json file')

        with open(file_path) as json_file:
            self._raw_data = json.load(json_file)

        self._json_data = copy.deepcopy(self._raw_data)
1040190
def GetRealPath(filename):
  
  if os.path.isabs(filename):                # already absolute
    return filename

  if filename.startswith('./') or  filename.startswith('../'): # relative
    return os.path.abspath(filename)

  path = os.getenv('PATH', '')
  for directory in path.split(':'):
    tryname = os.path.join(directory, filename)
    if os.path.exists(tryname):
      if not os.path.isabs(directory):  # relative directory
        return os.path.abspath(tryname)
      return tryname
  if os.path.exists(filename):
    return os.path.abspath(filename)
  return None
522590
def resolve_upload_path(self, filename=None):
        
        if filename is None:
            return settings.FLOW_EXECUTOR['UPLOAD_DIR']

        return os.path.join(settings.FLOW_EXECUTOR['UPLOAD_DIR'], filename)
120551
def __send_main_file(self, file_name):
        

        file_name = join(self.app.static_folder, file_name)

        with codecs.open(file_name, 'r', 'utf-8') as file:
            data = file.read()

        data = data.replace(
            'fields.article.url = apiProject.url + fields.article.url;',
            '''if (fields.article.url.substr(0, 4).toLowerCase() !== \'http\')
                        fields.article.url = apiProject.url + fields.article.url;''')

        headers = Headers()
        headers['Content-Length'] = getsize(file_name)

        response = self.app.response_class(data,
                                           mimetype=mimetypes.guess_type(file_name)[0],
                                           headers=headers,
                                           direct_passthrough=True)

        response.last_modified = int(getmtime(file_name))

        return response
1211150
def get_real_layer_path(self, path):
        
        filename = path.split('/')[-1]
        local_path = path
        filetype = os.path.splitext(filename)[1]

        # Url
        if re.match(r'^[a-zA-Z]+://', path):
            local_path = os.path.join(DATA_DIRECTORY, filename)

            if not os.path.exists(local_path):
                sys.stdout.write('* Downloading %s...\n' % filename)
                self.download_file(path, local_path)
            elif self.args.redownload:
                os.remove(local_path)

                sys.stdout.write('* Redownloading %s...\n' % filename)
                self.download_file(path, local_path)
        # Non-existant file
        elif not os.path.exists(local_path):
            raise Exception('%s does not exist' % local_path)

        real_path = path

        # Zip files
        if filetype == '.zip':
            slug = os.path.splitext(filename)[0]
            real_path = os.path.join(DATA_DIRECTORY, slug)

            if not os.path.exists(real_path):
                sys.stdout.write('* Unzipping...\n')
                self.unzip_file(local_path, real_path)

        return real_path
41705
def loadFilename( self, filename = '' ):
        
        if ( not (filename and isinstance(filename, basestring)) ):
            filename = QFileDialog.getOpenFileName( self,
                                                    'Open XDK File',
                                                    QDir.currentPath(),
                                                    'XDK Files (*.xdk)' )
            
            if type(filename) == tuple:
                filename = nativestring(filename[0])
            
            if not filename:
                return False
        
        if not (filename and os.path.exists(filename)):
            return False
        
        elif filename in self.loadedFilenames():
            return False
        
        self.loadFileRequested.emit(filename)
        self.setCursor(Qt.WaitCursor)
        
        return True
365377
def _get_file_name(file_path):
    

    file_name = basename(file_path)

    utf8_file_name = bytearray(file_name, "utf8")
    utf8_file_name.append(0)

    return utf8_file_name
158923
def jsonobjlen(self, name, path=Path.rootPath()):
        
        return self.execute_command('JSON.OBJLEN', name, str_path(path))
1111707
def upload_to(instance, filename, prefix=None):
    
    ext = path.splitext(filename)[1]
    name = str(instance.pk or time()) + filename

    # We think that we use utf8 based OS file system
    filename = md5(name.encode('utf8')).hexdigest() + ext
    basedir = path.join(instance._meta.app_label, instance._meta.module_name)
    if prefix:
        basedir = path.join(basedir, prefix)
    return path.join(basedir, filename[:2], filename[2:4], filename)
748270
def random_name_filepath(path_full, length_random=5):
    '''
    '''
    path_full_pre_extension, extension = os.path.splitext(path_full)
    random_str = random_str_uuid(length_random)
    return "{}{}{}".format(path_full_pre_extension, random_str, extension)
821495
def get_file_fullpath(name, dirname=None):
        # type: (AnyStr, Optional[AnyStr]) -> Optional[AnyStr]
        """"""
        if name is None:
            return None
        if is_string(name):
            name = str(name)
        else:
            raise RuntimeError('The input function name or path must be string!')
        for sep in ['\\', '/', os.sep]:  # Loop all possible separators
            if sep in name:  # name is full path already
                name = os.path.abspath(name)
                return name
        if dirname is not None:
            dirname = os.path.abspath(dirname)
            name = dirname + os.sep + name
        return name