python - 如何通过 Django 查看上传的文本文件?

标签 python django python-3.x

我现在正在制作网络应用程序。此应用程序获取具有未组织数据的文本文件并对其进行组织。我现在在 Python3 中使用 Django。

我已经在模板中制作了表单数据。

  • 模板

>    <form action="/practice/kakao_reader/" method="post"enctype="multipart/form-data">{% csrf_token %}
>        File:
>        <input type="file" name="file"/>
>        <input type="submit" value="UPLOAD" />
>     </form>

但是我很难通过VIEW获取上传的文件。 我试过的第一个代码是

  • 查看.py

def kakao_reader(request):

f = codecs.open(request.FILES['file'], encoding = 'utf-8')

data = f.read()

我收到无效文件:InMemoryUploadedFile:这个错误。

具体错误是

Environment:

Request Method: POST Request URL: http://localhost:8000/practice/kakao_reader/

Django Version: 1.10 Python Version: 3.5.2 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'elections', 'practice'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware']

Traceback:

File "C:\Python35\lib\site-packages\django\core\handlers\exception.py" in inner 39. response = get_response(request)

File "C:\Python35\lib\site-packages\django\core\handlers\base.py" in _get_response 187. response = self.process_exception_by_middleware(e, request)

File "C:\Python35\lib\site-packages\django\core\handlers\base.py" in _get_response 185. response = wrapped_callback(request, *callback_args, **callback_kwargs)

File "C:\Django\mysite\practice\views.py" in kakao_json 43. f = codecs.open(request.FILES['file'], encoding = 'utf-8')

File "C:\Python35\Lib\codecs.py" in open 895. file = builtins.open(filename, mode, buffering)

Exception Type: TypeError at /practice/kakao_reader/ Exception Value: invalid file:

我该如何解决?谢谢。

最佳答案

request.FILES['file'] 已经是文件处理程序,因此您不必打开它。只需使用 request.FILES['file'].read()

关于python - 如何通过 Django 查看上传的文本文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39436612/

相关文章:

Python:字典中 numpy 数组的高效串联

python - 在 Django 中访问查询集数据并对其执行操作

python - 将计时器添加到赠品命令 discord.py

python - TypeError : 'dict' object is not callable fix in python card game

python - OpenCV Python 去除小轮廓,保存子轮廓

python - celery 使用错误的经纪人

android - 获取 token 身份验证 View 时出现 Django REST HTTP 400 错误

python-3.x - 如何在不需要启动终端窗口的情况下等到在 python3 中按下热键?

python - 多个目录的错误处理

python - 在 SciPy 中求概率分布函数曲线下的面积