我想使用django和django rest-framework在亚马逊s3上传图像文件。以下是我项目的代码片段。
models.py
class Image(models.Model):
image_meta = models.ForeignKey('Image_Meta',on_delete=models.CASCADE,)
image = models.ImageField(upload_to='images-data')
order = models.IntegerField()
version = models.CharField(max_length=10)
serializers.py
class ImageSerializer(serializers.ModelSerializer):
class Meta:
model = Image
field = ('id', 'image_path' , 'order' , 'version')
urls.py
from django.conf.urls import patterns , include , url
from rest_framework.urlpatterns import format_suffix_patterns
from imagedata import views
urlpatterns = patterns('',
url(r'^image/$',views.ImageList.as_view(),name='image_list'),
url(r'^image/(?P<pk>[0-9]+)/$',views.ImageDetail.as_view(),name='image_detail'),
)
urlpatterns = format_suffix_patterns(urlpatterns)
views.py
@api_view(('GET',))
def api_root(request, format=None):
return Response({
'Component': reverse('component_list', request=request),
'Image Type': reverse('imagetype_list', request=request),
'Image Component':reverse('imagecomponent_list' , request=request),
'Feature':reverse('feature_list',request=request)
})
class ImageList(generics.ListCreateAPIView):
queryset = Image.objects.all()
serializer_class = ImageSerializer
parser_classes = (MultiPartParser)
class ImageDetail(generics.RetrieveUpdateDestroyAPIView):
queryset = Image.objects.all()
serializer_class = ImageSerializer
settings.py
import os
import psycopg2
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
SECRET_KEY = '****secret_key****'
DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'imagedata',
'django.contrib.postgres',
'rest_framework',
'storages',
]
DEFAULT_FILE_STORAGE = 'storages.backends.s3boto.S3BotoStorage'
REST_FRAMEWORK = {
'EXCEPTION_HANDLER': [
'rest_framework.views.exception_handler'
],
'DEFAULT_PERMISSION_CLASSES' : [
'rest_framework.permissions.IsAuthenticated'
]
}
MIDDLEWARE_CLASSES = [
'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 = 'imageserver1.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 = 'imageserver1.wsgi.application'
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': 'image_database',
'USER': 'the_flash',
'PASSWORD': 'password',
'HOST': 'localhost',
'PORT': '5432',
}
}
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.9/howto/static-files/
STATIC_URL = '/static/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'images')
MEDIA_URL = '/images/'
try:
from local_settings import *
except ImportError:
pass
assert len(SECRET_KEY) > 20, 'Please set SECRET_KEY in local_settings.py'
local_settings.py
AWS_S3_ACCESS_KEY_ID = 'Get this from Amazon'
AWS_S3_SECRET_ACCESS_KEY = 'This as well'
AWS_STORAGE_BUCKET_NAME = 'your-s3-bucket-name'
SECRET_KEY = '****secret_key****'
完成所有这些后,我陷入了下一步。我想做的就是将图像从本地系统上传到s3到Django。我一直在使用this作为参考。