一時保存
11020 ワード
pip freeze
asgiref==3.3.1
bcrypt==3.2.0
certifi==2020.12.5
cffi==1.14.5
cryptography==3.4.7
Django==3.1.7
django-cors-headers==3.7.0
mysqlclient==2.0.3
pycparser==2.20
PyJWT==2.0.1
pytz==2021.1
six==1.15.0
sqlparse==0.4.1
プロジェクト名:プロジェクトwestagram
アプリケーション:users,postings
project_westagram/settings.py
asgiref==3.3.1
bcrypt==3.2.0
certifi==2020.12.5
cffi==1.14.5
cryptography==3.4.7
Django==3.1.7
django-cors-headers==3.7.0
mysqlclient==2.0.3
pycparser==2.20
PyJWT==2.0.1
pytz==2021.1
six==1.15.0
sqlparse==0.4.1
プロジェクト名:プロジェクトwestagram
アプリケーション:users,postings
project_westagram/settings.py
from pathlib import Path
import my_settings
# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/3.1/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = my_settings.SECRET_KEY
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = False
ALLOWED_HOSTS = ['*']
# Application definition
INSTALLED_APPS = [
# 'django.contrib.admin',
# 'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'users',
'postings',
'corsheaders',
]
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',
'corsheaders.middleware.CorsMiddleware',
]
ROOT_URLCONF = 'project_westagram.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 = 'project_westagram.wsgi.application'
# Database
# https://docs.djangoproject.com/en/3.1/ref/settings/#databases
DATABASES = my_settings.DATABASES
# Password validation
# https://docs.djangoproject.com/en/3.1/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.1/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.1/howto/static-files/
STATIC_URL = '/static/'
#REMOVE_APPEND_SLASH_WARNING
APPEND_SLASH = False
##CORS
CORS_ORIGIN_ALLOW_ALL=True
CORS_ALLOW_CREDENTIALS = True
CORS_ALLOW_METHODS = (
'DELETE',
'GET',
'OPTIONS',
'PATCH',
'POST',
'PUT',
)
CORS_ALLOW_HEADERS = (
'accept',
'accept-encoding',
'authorization',
'content-type',
'dnt',
'origin',
'user-agent',
'x-csrftoken',
'x-requested-with',
#만약 허용해야할 추가적인 헤더키가 있다면?(사용자정의 키) 여기에 추가하면 됩니다.
)
my_settings.pyDATABASES = {
'default' : {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'users_1', # db 명
'USER': 'root',
'PASSWORD': 'ubuntu', # mysql 접근 비밀번호
'HOST': 'localhost',
'PORT': '3306',
}
}
SECRET_KEY ='=6xvu3t)6+8k8vi@b-(g4=2ah$@vi*^f@h#fraf)mc-_3@xw8t'
users/models.pyfrom django.db import models
class User(models.Model):
email = models.CharField(max_length=50)
password = models.CharField(max_length=100)
name = models.CharField(max_length=50)
phone_number= models.CharField(max_length=50)
class Meta:
db_table='users'
project_westagram/users/views.pyimport json
import jwt
import bcrypt
from django.http import JsonResponse
from django.views import View
from django.db.models import Q
from django.core.validators import validate_email, ValidationError
from my_settings import SECRET_KEY
from .models import User
class SignUpView(View):
def post(self, request):
PASSWORD_LENGTH = 8
try:
data = json.loads(request.body)
if '@' not in data['email'] or '.' not in data['email']:
return JsonResponse({'MESSAGE':'INVALID EMAIL'}, status=400)
if User.objects.filter(email= data['email']).exists():
return JsonResponse({'MESSAGE':'DUPLICATED EMAIL'}, status=400)
if len(data['password']) <= PASSWORD_LENGTH :
return JsonResponse({'MESSAGE':'INVALID PASSWORD'}, status=400)
hashed_password = bcrypt.hashpw(data['password'].encode('utf-8'), bcrypt.gensalt()).decode('utf-8')
User.objects.create(
email = data['email'],
password = hashed_password,
name = data['name'],
phone_number= data['phone_number']
)
return JsonResponse({'MESSAGE':'SUCCESS'},status=201)
except KeyError:
return JsonResponse({'MESSAGE':'KEY ERROR'}, status=400)
class SignInView(View):
def post(self, request):
data = json.loads(request.body)
try:
email = data['email']
password = data['password']
name = data.get('name',None)
phone_number= data.get('phone_number',None)
if not User.objects.filter(email=email).exists():
return JsonResponse({'MESSAGE':'NOT_FOUND'}, status=404)
user = User.objects.get(email=email)
print('*'*30)
hashed_password = user.password.encode('utf-8')
if not bcrypt.checkpw(password.encode('utf-8'),hashed_password):
return JsonResponse({'MESSAGE':'INVALID_USER'}, status=401)
print('*'*30)
access_token =jwt.encode({'id':user.id},SECRET_KEY['secret'],algorithm='HS256')
print('*'*30)
return JsonResponse({'ACCESS_TOKEN':access_token}, status=200)
except KeyError:
return JsonResponse({'MESSAGE':'KEY_ERROR'}, status=400)
project_westagram/urls.pyfrom django.urls import path,include
urlpatterns = [
path('users', include('users.urls')),
path('users'), incluse('postings.urls')
]
users/urls.pyfrom django.urls import path
from .views import SignUpView,SignInView
urlpatterns =[
path('/signup', SignUpView.as_view()),
path('/signin', SignInView.as_view()),
]
なんてことだfrom django.db import models
# Create your models here.
class UserPosting(models.Model):
user_ID = models.ForeignKey('users.User',on_delete=models.SET_NULL, null=True)
create_at = models.DateTimeField(auto_now=True)
image_url = models.CharField(max_length=500)
def __str__(self):
return f'{self.user_ID.name.email}'
class Meta:
db_table = 'userpostings'
postings/models.pyfrom django.db import models
# Create your models here.
class UserPosting(models.Model):
user_ID = models.ForeignKey('users.User',on_delete=models.SET_NULL, null=True)
create_at = models.DateTimeField(auto_now=True)
image_url = models.CharField(max_length=500)
def __str__(self):
return f'{self.user_ID.name.email}'
class Meta:
db_table = 'userpostings'
postings/views.py import json
import bcrypt
import jwt
from django.http import HttpResponse, JsonResponse
from django.views import View
from django.db.models import Q
from django.core.validators import validate_email, ValidationError
from .models import User
class ContentSignupView(View):
def post(self, request):
try:
data = json.loads(request.body)
if User.objects.filter(email =data['email']).exists():
user = User.objects.get(email =data['email'])
image_url = data['image_url']
User.objects.create(
user_ID = user,
image_url = image_url
)
return JsonResponse({'MESSAGE':'SUCCESS'}), status=200)
return JsonResponse({'MESSAGE':'INVALID_NAME'},status=400)
except KeyError:
return JsonResponse({"MESSAGE":"INVALID_KEY"},status=400)
class ContentGetView(View):
def get(self, request):
content_data = UserPosting.objects.values()
return JsonResponse({"content_data":list(content_data)},status=200)
from django.urls import path
from .views import ContentGetView, ContentSignupView
urlpatterns =[
path('/post', ContentSignupView.as_view()),
path('/get',ContentGetView.as_view())
]
Reference
この問題について(一時保存), 我々は、より多くの情報をここで見つけました https://velog.io/@hong_tae/임시-저장テキストは自由に共有またはコピーできます。ただし、このドキュメントのURLは参考URLとして残しておいてください。
Collection and Share based on the CC Protocol