FileUploadParser没有获取文件名 [英] FileUploadParser doesn't get the file name
问题描述
我只想创建一个REST API来接收文件,对其进行处理并返回一些信息。我的问题是我在遵循以下示例:
http: //www.django-rest-framework.org/api-guide/parsers/#fileuploadparser
I just want to create a REST API that receives a file, process it and return some information. My problem is that I am following this example: http://www.django-rest-framework.org/api-guide/parsers/#fileuploadparser
而且我无法使用Postman或卷曲,我想我缺少了一些东西。解析器总是给我这两个错误:
And I can't make it work using Postman or curl, I think I am missing something. The parser always gives me these two errors:
- FileUpload解析错误-没有上载处理程序可以处理流
- 缺少文件名。请求应包含带有文件名参数的Content-Disposition标头。
这是代码:
views.py:
class FileUploadView(APIView):
parser_classes = (FileUploadParser,)
def post(self, request, filename, format=None):
file_obj = request.data['file']
# ...
# do some stuff with uploaded file
# ...
return Response(status=204)
def put(self, request, filename, format=None):
file_obj = request.data['file']
# ...
# do some stuff with uploaded file
# ...
return Response(status=204)
urls.py
urlpatterns = [
url(r'predict/(?P<filename>[^/]+)$', app.views.FileUploadView.as_view())
]
settings.py
settings.py
"""
Django settings for GenderAPI project.
Generated by 'django-admin startproject' using Django 1.9.1.
For more information on this file, see
https://docs.djangoproject.com/en/1.9/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.9/ref/settings/
"""
import os
import posixpath
LOGGING = {
'version': 1,
'disable_existing_loggers': False,
'handlers': {
'file': {
'level': 'DEBUG',
'class': 'logging.FileHandler',
'filename': 'debug.log',
},
},
'loggers': {
'django': {
'handlers': ['file'],
'level': 'DEBUG',
'propagate': True,
},
},
}
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.9/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = removed
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = ['localhost','127.0.0.1']
REST_FRAMEWORK = {
'DEFAULT_PARSER_CLASSES': (
'rest_framework.parsers.FileUploadParser'
)
}
# Application definition
INSTALLED_APPS = [
# Add your apps here to enable them
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'rest_framework',
'app'
]
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.auth.middleware.SessionAuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware'
]
ROOT_URLCONF = 'GenderAPI.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'GenderAPI.wsgi.application'
# Database
# https://docs.djangoproject.com/en/1.9/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.9/howto/static-files/
STATIC_URL = '/static/'
STATIC_ROOT = posixpath.join(*(BASE_DIR.split(os.path.sep) + ['static']))
FILE_UPLOAD_TEMP_DIR = BASE_DIR
MEDIA_URL = '/media/'
在这里您可以看到邮递员的抓拍(我已经尝试了所有方法):
Here you can see a postman capture (I have tried everything):
PUT /predict/pabloGrande.jpg HTTP/1.1
Host: 127.0.0.1:52276
Content-Type: multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW
------WebKitFormBoundary7MA4YWxkTrZu0gW
Content-Disposition: form-data; name="file"; filename="04320cf.jpg"
Content-Type: image/jpeg
------WebKitFormBoundary7MA4YWxkTrZu0gW--
要求:
bleach==1.5.0
Django==1.11.6
djangorestframework==3.7.1
html5lib==0.9999999
Markdown==2.6.9
numpy==1.13.3
olefile==0.44
pandas==0.20.3
Pillow==4.3.0
pip==9.0.1
protobuf==3.4.0
python-dateutil==2.6.1
pytz==2017.2
scipy==1.0.0rc1
setuptools==28.8.0
six==1.11.0
tensorflow==1.3.0
tensorflow-tensorboard==0.1.8
Werkzeug==0.12.2
wheel==0.30.0
非常感谢您的帮助
推荐答案
在Django REST框架。我们有解析器,渲染器和序列化器之类的组件。
In django REST framework. we have components like Parsers, Renderers and Serializers.
-
解析器的职责是解析请求方法发送的数据GET,POST和PUT等。
The responsibility of Parsers is to parse the data that is sent by request methods GET, POST and PUT, etc.
在Django REST中使用的默认解析器为' JSONParser 。它仅解析数据JSON数据[数字,字符串,日期]。它会忽略诸如FILES之类的数据。
Default parser used in django REST is 'JSONParser'. It only parses the data JSON data[numbers, string, date]. It ignores the data like FILES.
为了解析FILES,我们需要使用诸如 MultiPartParser 或 FormParser 。
In order to parse the FILES we need to use parsers like "MultiPartParser" or "FormParser".
示例代码:
from rest_framework.parsers import MultiPartParser
from rest_framework.response import Response
from rest_framework.views import APIView
class ExampleView(APIView):
"""
A view that can accept POST requests with JSON content.
"""
parser_classes = (MultiPartParser,)
def post(self, request, format=None):
# to access files
print request.FILES
# to access data
print request.data
return Response({'received data': request.data})
当我们使用属性 request.data
时,解析器将解析数据。
When we use property request.data
then parser will parse the data.
参考文献: Django REST文档, Django REST Github
这篇关于FileUploadParser没有获取文件名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!