youjeongsue

init file upload

./vscode
./backend/api/cloud/aws.py
\ No newline at end of file
"""
ASGI config for api project.
It exposes the ASGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/3.0/howto/deployment/asgi/
"""
import os
from django.core.asgi import get_asgi_application
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'api.settings')
application = get_asgi_application()
"""
Django settings for api project.
Generated by 'django-admin startproject' using Django 3.0.6.
For more information on this file, see
https://docs.djangoproject.com/en/3.0/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/3.0/ref/settings/
"""
import os
# 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/3.0/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '+ste$ef+eq%n&&f02quxcuk@w6ypz5)pp8gh*$^6*s-@3dvb9d'
# SECURITY WARNING: don't run with debug turned on in production!
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',
'cloud',
'rest_framework'
]
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',
]
ROOT_URLCONF = 'api.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 = 'api.wsgi.application'
# Database
# https://docs.djangoproject.com/en/3.0/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
# Password validation
# https://docs.djangoproject.com/en/3.0/ref/settings/#auth-password-validators
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',
},
]
# Internationalization
# https://docs.djangoproject.com/en/3.0/topics/i18n/
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/3.0/howto/static-files/
STATIC_URL = '/static/'
"""api URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/3.0/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.urls import include, path
2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('',include('cloud.urls'))
]
"""
WSGI config for api project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/3.0/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'api.settings')
application = get_wsgi_application()
from django.contrib import admin
# Register your models here.
from django.apps import AppConfig
class CloudConfig(AppConfig):
name = 'cloud'
def aws_key():
return {
'AWS_ACCESS_KEY_ID' : 'AKIAIBBP3XOYSXLBY2IQ',
'AWS_SECRET_ACCESS_KEY' : 'A+fK8ZytKlaweV42Z3Kt644+xtYVs2KFyOdGYlpU'
}
\ No newline at end of file
# Generated by Django 3.0.6 on 2020-05-09 15:45
from django.db import migrations, models
import django.utils.timezone
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='File',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('path', models.CharField(max_length=300)),
('created_date', models.DateTimeField(default=django.utils.timezone.now)),
('modified_date', models.DateTimeField(blank=True, null=True)),
],
),
]
from django.db import models
from django.utils import timezone
# Create your models here.
class File(models.Model):
path=models.CharField(max_length=300)
created_date = models.DateTimeField(default=timezone.now)
modified_date = models.DateTimeField(blank=True, null=True)
\ No newline at end of file
test
\ No newline at end of file
from django.test import TestCase
from rest_framework.test import APIClient
# Create your tests here.
class APITest(TestCase):
def test_upload_file(self):
client=APIClient()
response=client.post('/files/',{})
self.assertEqual(response.status_code,200)
\ No newline at end of file
from django.urls import path, include
from cloud import views
urlpatterns = [
path('files/', views.FileView.as_view())
]
\ No newline at end of file
from django.shortcuts import render
from cloud.models import File
from django.views.generic import View
from django.views.decorators.csrf import csrf_exempt
import boto3
from django.http import JsonResponse
from cloud.aws import aws_key
# class FileToURL(View):
# s3_client = boto3.client(
# 's3',
# aws_access_key_id={'AKIAIBBP3XOYSXLBY2IQ'},
# aws_secret_access_key={'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'}
# )
# @csrf_exempt
# def post(self, request):
# #FILES=MultiValueDict({'file':['/path1.txt','/folder/path2.txt',...]})
# for file in request.FILES.getlist('file'):
# self.s3_client.upload_fileobj(
# file,
# {'khuloud'},
# file.name
# )
# file_urls = [f"https://s3.us-ease-1.amazonaws.com/khuloud/{file.name}" for file in request.FILES.getlist('file')]
# return JsonResponse({'files':file_urls}, status=200)
class FileView(View):
keys=aws_key()
s3_client = boto3.client(
's3',
aws_access_key_id = keys['AWS_ACCESS_KEY_ID'],
aws_secret_access_key=keys['AWS_SECRET_ACCESS_KEY']
)
@csrf_exempt
def post(self, request):
# filename = request.data.get('filename')
bucket_name = "khuloud"
filepath = 'cloud/test/text1.txt'
self.s3_client.upload_file(filepath, bucket_name, filepath)
s3link='https://s3.console.aws.amazon.com/s3/buckets/'+bucket_name+'/'+filepath
return JsonResponse({'file':s3link})
\ No newline at end of file
No preview for this file type
#!/usr/bin/env python
"""Django's command-line utility for administrative tasks."""
import os
import sys
def main():
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'api.settings')
try:
from django.core.management import execute_from_command_line
except ImportError as exc:
raise ImportError(
"Couldn't import Django. Are you sure it's installed and "
"available on your PYTHONPATH environment variable? Did you "
"forget to activate a virtual environment?"
) from exc
execute_from_command_line(sys.argv)
if __name__ == '__main__':
main()