當前位置: 首頁>>代碼示例>>Python>>正文


Python temp.NamedTemporaryFile方法代碼示例

本文整理匯總了Python中django.core.files.temp.NamedTemporaryFile方法的典型用法代碼示例。如果您正苦於以下問題:Python temp.NamedTemporaryFile方法的具體用法?Python temp.NamedTemporaryFile怎麽用?Python temp.NamedTemporaryFile使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在django.core.files.temp的用法示例。


在下文中一共展示了temp.NamedTemporaryFile方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: to_analyser_export

# 需要導入模塊: from django.core.files import temp [as 別名]
# 或者: from django.core.files.temp import NamedTemporaryFile [as 別名]
def to_analyser_export(self, path, data, username, xform_id_string, *args):
        # Get the XLSForm.
        xform = XForm.objects.get(user__username__iexact=username, id_string__exact=xform_id_string)
        xlsform_io= xform.to_xlsform()

        if xlsform_io is None:
            raise RuntimeError('XLSForm `{}` for user `{}` could not be retrieved from storage.'.
                               format(xform_id_string, username))

        prefix = slugify('analyser_data__{}__{}'.format(username, xform_id_string))
        with tempfile.NamedTemporaryFile('w+b', prefix=prefix, suffix='.xlsx',) as xls_data:
            # Generate a new XLS export to work from.
            self.to_xls_export(xls_data.name, data)
            xls_data.file.seek(0)

            # Generate the analyser file.
            analyser_io= generate_analyser(xlsform_io, xls_data)

        # Write the generated analyser file to the specified path
        #   ...which itself points to a temp file.
        with open(path, 'wb') as analyser_file:
            analyser_file.write(analyser_io.read()) 
開發者ID:awemulya,項目名稱:kobo-predict,代碼行數:24,代碼來源:export_tools.py

示例2: create_media

# 需要導入模塊: from django.core.files import temp [as 別名]
# 或者: from django.core.files.temp import NamedTemporaryFile [as 別名]
def create_media(media):
    """Download media link"""
    if is_valid_url(media.data_value):
        filename = media.data_value.split('/')[-1]
        data_file = NamedTemporaryFile()
        content_type = mimetypes.guess_type(filename)
        with closing(requests.get(media.data_value, stream=True)) as r:
            for chunk in r.iter_content(chunk_size=CHUNK_SIZE):
                if chunk:
                    data_file.write(chunk)
        data_file.seek(os.SEEK_SET, os.SEEK_END)
        size = os.path.getsize(data_file.name)
        data_file.seek(os.SEEK_SET)
        media.data_value = filename
        media.data_file = InMemoryUploadedFile(
            data_file, 'data_file', filename, content_type,
            size, charset=None)

        return media

    return None 
開發者ID:awemulya,項目名稱:kobo-predict,代碼行數:23,代碼來源:meta_data.py

示例3: test_to_xls_export_respects_custom_field_delimiter

# 需要導入模塊: from django.core.files import temp [as 別名]
# 或者: from django.core.files.temp import NamedTemporaryFile [as 別名]
def test_to_xls_export_respects_custom_field_delimiter(self):
        survey = self._create_childrens_survey()
        export_builder = ExportBuilder()
        export_builder.GROUP_DELIMITER = ExportBuilder.GROUP_DELIMITER_DOT
        export_builder.set_survey(survey)
        xls_file = NamedTemporaryFile(suffix='.xls')
        filename = xls_file.name
        export_builder.to_xls_export(filename, self.data)
        xls_file.seek(0)
        wb = load_workbook(filename)

        # check header columns
        main_sheet = wb.get_sheet_by_name('childrens_survey')
        expected_column_headers = [
            u'name', u'age', u'geo.geolocation', u'geo._geolocation_latitude',
            u'geo._geolocation_longitude', u'geo._geolocation_altitude',
            u'geo._geolocation_precision', u'tel.tel.office',
            u'tel.tel.mobile', u'_id', u'meta.instanceID', u'_uuid',
            u'_submission_time', u'_index', u'_parent_index',
            u'_parent_table_name', u'_tags', '_notes']
        column_headers = [c[0].value for c in main_sheet.columns]
        self.assertEqual(sorted(column_headers),
                         sorted(expected_column_headers))
        xls_file.close() 
開發者ID:awemulya,項目名稱:kobo-predict,代碼行數:26,代碼來源:test_export_builder.py

示例4: test_to_xls_export_generates_valid_sheet_names

# 需要導入模塊: from django.core.files import temp [as 別名]
# 或者: from django.core.files.temp import NamedTemporaryFile [as 別名]
def test_to_xls_export_generates_valid_sheet_names(self):
        survey = create_survey_from_xls(_logger_fixture_path(
            'childrens_survey_with_a_very_long_name.xls'))
        export_builder = ExportBuilder()
        export_builder.set_survey(survey)
        xls_file = NamedTemporaryFile(suffix='.xls')
        filename = xls_file.name
        export_builder.to_xls_export(filename, self.data)
        xls_file.seek(0)
        wb = load_workbook(filename)
        # check that we have childrens_survey, children, children_cartoons
        # and children_cartoons_characters sheets
        expected_sheet_names = ['childrens_survey_with_a_very_lo',
                                'childrens_survey_with_a_very_l1',
                                'childrens_survey_with_a_very_l2',
                                'childrens_survey_with_a_very_l3']
        self.assertEqual(wb.get_sheet_names(), expected_sheet_names)
        xls_file.close() 
開發者ID:awemulya,項目名稱:kobo-predict,代碼行數:20,代碼來源:test_export_builder.py

示例5: test_child_record_parent_table_is_updated_when_sheet_is_renamed

# 需要導入模塊: from django.core.files import temp [as 別名]
# 或者: from django.core.files.temp import NamedTemporaryFile [as 別名]
def test_child_record_parent_table_is_updated_when_sheet_is_renamed(self):
        survey = create_survey_from_xls(_logger_fixture_path(
            'childrens_survey_with_a_very_long_name.xls'))
        export_builder = ExportBuilder()
        export_builder.set_survey(survey)
        xls_file = NamedTemporaryFile(suffix='.xlsx')
        filename = xls_file.name
        export_builder.to_xls_export(filename, self.long_survey_data)
        xls_file.seek(0)
        wb = load_workbook(filename)

        # get the children's sheet
        ws1 = wb.get_sheet_by_name('childrens_survey_with_a_very_l1')

        # parent_table is in cell K2
        parent_table_name = ws1.cell('K2').value
        expected_parent_table_name = 'childrens_survey_with_a_very_lo'
        self.assertEqual(parent_table_name, expected_parent_table_name)

        # get cartoons sheet
        ws2 = wb.get_sheet_by_name('childrens_survey_with_a_very_l2')
        parent_table_name = ws2.cell('G2').value
        expected_parent_table_name = 'childrens_survey_with_a_very_l1'
        self.assertEqual(parent_table_name, expected_parent_table_name)
        xls_file.close() 
開發者ID:awemulya,項目名稱:kobo-predict,代碼行數:27,代碼來源:test_export_builder.py

示例6: test_xls_convert_dates_before_1900

# 需要導入模塊: from django.core.files import temp [as 別名]
# 或者: from django.core.files.temp import NamedTemporaryFile [as 別名]
def test_xls_convert_dates_before_1900(self):
        survey = create_survey_from_xls(viewer_fixture_path(
            'test_data_types/test_data_types.xls'))
        export_builder = ExportBuilder()
        export_builder.set_survey(survey)
        data = [
            {
                'name': 'Abe',
                'when': '1899-07-03',
            }
        ]
        # create export file
        temp_xls_file = NamedTemporaryFile(suffix='.xlsx')
        export_builder.to_xls_export(temp_xls_file.name, data)
        temp_xls_file.close()
        # this should error if there is a problem, not sure what to assert 
開發者ID:awemulya,項目名稱:kobo-predict,代碼行數:18,代碼來源:test_export_builder.py

示例7: test_large_upload

# 需要導入模塊: from django.core.files import temp [as 別名]
# 或者: from django.core.files.temp import NamedTemporaryFile [as 別名]
def test_large_upload(self):
        file = tempfile.NamedTemporaryFile
        with file(suffix=".file1") as file1, file(suffix=".file2") as file2:
            file1.write(b'a' * (2 ** 21))
            file1.seek(0)

            file2.write(b'a' * (10 * 2 ** 20))
            file2.seek(0)

            post_data = {
                'name': 'Ringo',
                'file_field1': file1,
                'file_field2': file2,
            }

            for key in list(post_data):
                try:
                    post_data[key + '_hash'] = hashlib.sha1(post_data[key].read()).hexdigest()
                    post_data[key].seek(0)
                except AttributeError:
                    post_data[key + '_hash'] = hashlib.sha1(post_data[key].encode()).hexdigest()

            response = self.client.post('/verify/', post_data)

            self.assertEqual(response.status_code, 200) 
開發者ID:nesdis,項目名稱:djongo,代碼行數:27,代碼來源:tests.py

示例8: test_file_content

# 需要導入模塊: from django.core.files import temp [as 別名]
# 或者: from django.core.files.temp import NamedTemporaryFile [as 別名]
def test_file_content(self):
        file = tempfile.NamedTemporaryFile
        with file(suffix=".ctype_extra") as no_content_type, file(suffix=".ctype_extra") as simple_file:
            no_content_type.write(b'no content')
            no_content_type.seek(0)

            simple_file.write(b'text content')
            simple_file.seek(0)
            simple_file.content_type = 'text/plain'

            string_io = StringIO('string content')
            bytes_io = BytesIO(b'binary content')

            response = self.client.post('/echo_content/', {
                'no_content_type': no_content_type,
                'simple_file': simple_file,
                'string': string_io,
                'binary': bytes_io,
            })
            received = response.json()
            self.assertEqual(received['no_content_type'], 'no content')
            self.assertEqual(received['simple_file'], 'text content')
            self.assertEqual(received['string'], 'string content')
            self.assertEqual(received['binary'], 'binary content') 
開發者ID:nesdis,項目名稱:djongo,代碼行數:26,代碼來源:tests.py

示例9: test_content_type_extra

# 需要導入模塊: from django.core.files import temp [as 別名]
# 或者: from django.core.files.temp import NamedTemporaryFile [as 別名]
def test_content_type_extra(self):
        """Uploaded files may have content type parameters available."""
        file = tempfile.NamedTemporaryFile
        with file(suffix=".ctype_extra") as no_content_type, file(suffix=".ctype_extra") as simple_file:
            no_content_type.write(b'something')
            no_content_type.seek(0)

            simple_file.write(b'something')
            simple_file.seek(0)
            simple_file.content_type = 'text/plain; test-key=test_value'

            response = self.client.post('/echo_content_type_extra/', {
                'no_content_type': no_content_type,
                'simple_file': simple_file,
            })
            received = response.json()
            self.assertEqual(received['no_content_type'], {})
            self.assertEqual(received['simple_file'], {'test-key': 'test_value'}) 
開發者ID:nesdis,項目名稱:djongo,代碼行數:20,代碼來源:tests.py

示例10: test_custom_upload_handler

# 需要導入模塊: from django.core.files import temp [as 別名]
# 或者: from django.core.files.temp import NamedTemporaryFile [as 別名]
def test_custom_upload_handler(self):
        file = tempfile.NamedTemporaryFile
        with file() as smallfile, file() as bigfile:
            # A small file (under the 5M quota)
            smallfile.write(b'a' * (2 ** 21))
            smallfile.seek(0)

            # A big file (over the quota)
            bigfile.write(b'a' * (10 * 2 ** 20))
            bigfile.seek(0)

            # Small file posting should work.
            self.assertIn('f', self.client.post('/quota/', {'f': smallfile}).json())

            # Large files don't go through.
            self.assertNotIn('f', self.client.post("/quota/", {'f': bigfile}).json()) 
開發者ID:nesdis,項目名稱:djongo,代碼行數:18,代碼來源:tests.py

示例11: test_fileuploads_closed_at_request_end

# 需要導入模塊: from django.core.files import temp [as 別名]
# 或者: from django.core.files.temp import NamedTemporaryFile [as 別名]
def test_fileuploads_closed_at_request_end(self):
        file = tempfile.NamedTemporaryFile
        with file() as f1, file() as f2a, file() as f2b:
            response = self.client.post('/fd_closing/t/', {
                'file': f1,
                'file2': (f2a, f2b),
            })

        request = response.wsgi_request
        # The files were parsed.
        self.assertTrue(hasattr(request, '_files'))

        file = request._files['file']
        self.assertTrue(file.closed)

        files = request._files.getlist('file2')
        self.assertTrue(files[0].closed)
        self.assertTrue(files[1].closed) 
開發者ID:nesdis,項目名稱:djongo,代碼行數:20,代碼來源:tests.py

示例12: test_dumpdata_progressbar

# 需要導入模塊: from django.core.files import temp [as 別名]
# 或者: from django.core.files.temp import NamedTemporaryFile [as 別名]
def test_dumpdata_progressbar(self):
        """
        Dumpdata shows a progress bar on the command line when --output is set,
        stdout is a tty, and verbosity > 0.
        """
        management.call_command('loaddata', 'fixture1.json', verbosity=0)
        new_io = StringIO()
        new_io.isatty = lambda: True
        with NamedTemporaryFile() as file:
            options = {
                'format': 'json',
                'stdout': new_io,
                'stderr': new_io,
                'output': file.name,
            }
            management.call_command('dumpdata', 'fixtures', **options)
            self.assertTrue(new_io.getvalue().endswith('[' + '.' * ProgressBar.progress_width + ']\n'))

            # Test no progress bar when verbosity = 0
            options['verbosity'] = 0
            new_io = StringIO()
            new_io.isatty = lambda: True
            options.update({'stdout': new_io, 'stderr': new_io})
            management.call_command('dumpdata', 'fixtures', **options)
            self.assertEqual(new_io.getvalue(), '') 
開發者ID:nesdis,項目名稱:djongo,代碼行數:27,代碼來源:tests.py

示例13: setUp

# 需要導入模塊: from django.core.files import temp [as 別名]
# 或者: from django.core.files.temp import NamedTemporaryFile [as 別名]
def setUp(self):
        logging_conf = """
[loggers]
keys=root
[handlers]
keys=stream
[formatters]
keys=simple
[logger_root]
handlers=stream
[handler_stream]
class=StreamHandler
formatter=simple
args=(sys.stdout,)
[formatter_simple]
format=%(message)s
"""
        self.temp_file = NamedTemporaryFile()
        self.temp_file.write(logging_conf.encode())
        self.temp_file.flush()
        sdict = {'LOGGING_CONFIG': '"logging.config.fileConfig"',
                 'LOGGING': 'r"%s"' % self.temp_file.name}
        self.write_settings('settings.py', sdict=sdict) 
開發者ID:nesdis,項目名稱:djongo,代碼行數:25,代碼來源:tests.py

示例14: setUp

# 需要導入模塊: from django.core.files import temp [as 別名]
# 或者: from django.core.files.temp import NamedTemporaryFile [as 別名]
def setUp(self):
        logging_conf = """
[loggers]
keys=root
[handlers]
keys=stream
[formatters]
keys=simple
[logger_root]
handlers=stream
[handler_stream]
class=StreamHandler
formatter=simple
args=(sys.stdout,)
[formatter_simple]
format=%(message)s
"""
        self.temp_file = NamedTemporaryFile()
        self.temp_file.write(logging_conf.encode())
        self.temp_file.flush()
        self.write_settings('settings.py', sdict={
            'LOGGING_CONFIG': '"logging.config.fileConfig"',
            'LOGGING': 'r"%s"' % self.temp_file.name,
        }) 
開發者ID:nesdis,項目名稱:djongo,代碼行數:26,代碼來源:tests.py

示例15: get_local_file

# 需要導入模塊: from django.core.files import temp [as 別名]
# 或者: from django.core.files.temp import NamedTemporaryFile [as 別名]
def get_local_file(file):
    """
    Get a local version of the file, downloading it from the remote storage if
    required. The returned value should be used as a context manager to
    ensure any temporary files are cleaned up afterwards.
    """
    try:
        with open(file.path):
            yield file.path
    except NotImplementedError:
        _, ext = os.path.splitext(file.name)
        with NamedTemporaryFile(prefix='wagtailvideo-', suffix=ext) as tmp:
            try:
                file.open('rb')
                for chunk in file.chunks():
                    tmp.write(chunk)
            finally:
                file.close()
            tmp.flush()
            yield tmp.name


# Delete files when model is deleted 
開發者ID:neon-jungle,項目名稱:wagtailvideos,代碼行數:25,代碼來源:models.py


注:本文中的django.core.files.temp.NamedTemporaryFile方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。