相关疑难解决方法(0)

如何在不知道编码的情况下将字节写入Python 3中的文件?

在Python 2.x中使用'file-like'对象:

sys.stdout.write(bytes_)
tempfile.TemporaryFile().write(bytes_)
open('filename', 'wb').write(bytes_)
StringIO().write(bytes_)
Run Code Online (Sandbox Code Playgroud)

如何在Python 3中做同样的事情?

如何编写这个Python 2.x代码的等价物:

def write(file_, bytes_):
    file_.write(bytes_)
Run Code Online (Sandbox Code Playgroud)

注意:sys.stdout在语义上并不总是文本流.有时将它视为字节流可能是有益的.例如,在远程机器上制作dir /的加密存档:

tar -c dir/ | gzip | gpg -c | ssh user@remote 'dd of=dir.tar.gz.gpg'
Run Code Online (Sandbox Code Playgroud)

在这种情况下,没有必要使用Unicode.

python io python-3.x

48
推荐指数
2
解决办法
6万
查看次数

如何使用django-rest-framework的测试客户端测试二进制文件上传?

我有一个Django应用程序,其视图接受要上载的文件.使用Django REST框架我将APIView子类化并实现post()方法,如下所示:

class FileUpload(APIView):
    permission_classes = (IsAuthenticated,)

    def post(self, request, *args, **kwargs):
        try:
            image = request.FILES['image']
            # Image processing here.
            return Response(status=status.HTTP_201_CREATED)
        except KeyError:
            return Response(status=status.HTTP_400_BAD_REQUEST, data={'detail' : 'Expected image.'})
Run Code Online (Sandbox Code Playgroud)

现在我正在尝试编写几个单元测试以确保需要身份验证并且实际处理了上载的文件.

class TestFileUpload(APITestCase):
    def test_that_authentication_is_required(self):
        self.assertEqual(self.client.post('my_url').status_code, status.HTTP_401_UNAUTHORIZED)

    def test_file_is_accepted(self):
        self.client.force_authenticate(self.user)
        image = Image.new('RGB', (100, 100))
        tmp_file = tempfile.NamedTemporaryFile(suffix='.jpg')
        image.save(tmp_file)
        with open(tmp_file.name, 'rb') as data:
            response = self.client.post('my_url', {'image': data}, format='multipart')
            self.assertEqual(status.HTTP_201_CREATED, response.status_code)
Run Code Online (Sandbox Code Playgroud)

但是当REST框架尝试对请求进行编码时,这会失败

Traceback (most recent call last):
  File "/home/vagrant/.virtualenvs/myapp/lib/python3.3/site-packages/django/utils/encoding.py", line 104, in force_text
    s = six.text_type(s, encoding, errors)
UnicodeDecodeError: …
Run Code Online (Sandbox Code Playgroud)

django django-unittest django-rest-framework

43
推荐指数
4
解决办法
1万
查看次数

如何使用Python持久化磁盘临时文件?

我试图使用'tempfile'模块来操作和创建文本文件.文件准备好后,我想将其保存到磁盘.我认为这就像使用'shutil.copy'一样简单.但是,我得到'权限被拒绝'IOError:

>>> import tempfile, shutil
>>> f = tempfile.TemporaryFile(mode ='w+t')
>>> f.write('foo')
>>> shutil.copy(f.name, 'bar.txt')

Traceback (most recent call last):
  File "<pyshell#5>", line 1, in <module>
    shutil.copy(f.name, 'bar.txt')
  File "C:\Python25\lib\shutil.py", line 80, in copy
    copyfile(src, dst)
  File "C:\Python25\lib\shutil.py", line 46, in copyfile
    fsrc = open(src, 'rb')
IOError: [Errno 13] Permission denied: 'c:\\docume~1\\me\\locals~1\\temp\\tmpvqq3go'
>>> 
Run Code Online (Sandbox Code Playgroud)

这是不是在使用'tempfile'库时?有一个更好的方法吗?(也许我忽略了一些非常微不足道的事情)

python temporary-files

25
推荐指数
4
解决办法
3万
查看次数

Return openpyxl workbook object as HttpResponse in django. Is it possible?

I need to provide an excel formatted data from django's database to visitors.

The only way I can think of is with these steps:

  1. Extract data from database.
  2. Wrap it with Workbook object from openpyxl.
  3. Save it somewhere temporarily.
  4. Read it again as 'rb'.
  5. 使用excel的mime类型返回视图.
  6. 删除磁盘上的excel文件.(现在没用了?)

应该这样做.但是,我认为还有另一种更好的方法.我的意思是也许有一种方法可以openpyxlHttpResponse没有中间文件介质的情况下直接返回对象.

所以,在这里我的问题是:是否有可能返回openpyxlWorbook 对象?(我是新手openpyxl)

python django excel

14
推荐指数
3
解决办法
5558
查看次数

如何简洁地创建一个临时文件,它是python中另一个文件的副本

我知道可以创建一个临时文件,并将要复制的文件的数据写入其中.我只是想知道是否有这样的功能:

create_temporary_copy(file_path)
Run Code Online (Sandbox Code Playgroud)

python

11
推荐指数
3
解决办法
1万
查看次数

Windows 10 上带有上下文管理器的 Python 临时文件会导致 PermissionError:[Errno 13]

操作系统: Windows 10

Python: 3.6(蟒蛇)

我正在尝试使用带有上下文管理器的简单临时文件来编写简单的 csv。

import csv
import tempfile

fp = tempfile.TemporaryFile()
with open(fp.name,'w',newline='') as f:
    csv_out = csv.writer(f)
    csv_out.writerow(['first_name','last_name'])
    csv_out.writerow(['foo','bar'])
Run Code Online (Sandbox Code Playgroud)

运行此命令会导致此权限错误:

with open(fp.name,'w',newline='') as f:
E       PermissionError: [Errno 13] Permission denied: 'C:\\TEMP\\tmp2bqke7f6'
Run Code Online (Sandbox Code Playgroud)

更改临时目录的 Windows 权限状态C:\TEMP\以允许所有用户完全访问并没有帮助。

根据这篇文章,我尝试以管理员身份运行 Windows cmd,但仍然不起作用。

temporary-files file-writing python-3.x windows-10

5
推荐指数
1
解决办法
3947
查看次数

无法访问使用tempfile创建的临时文件

tempfile.NamedTemporaryFile()用来存储一些文本,直到程序结束。在Unix上可以正常使用,但是在Windows上无法读取或写入返回的文件:python提供Errno13。唯一的方法是使用设置delete=False和手动删除文件os.remove()。为什么?

python windows

4
推荐指数
1
解决办法
4594
查看次数