In this article ** Create a web API with Django! The article is **.
I'm using MySQL on RDS.
This is a continuation of the previous article, so please refer to it if you don't understand. [AWS] I tried using EC2, RDS, Django. Environment construction from 1
$ <-Commands on my PC terminal
[ec2-user] $ <-Commands while logged in to EC2
MySQL > <-Commands logged in to MySQL
# <-My comment
>>> <-Execution result(Output value)
-EC2, RDS, Django connection completed
I wrote it in the previous article, but I will write it again.
Let's create a project
#Create a project called testDjango
[ec2-user] $ django-admin startproject testDjango
[ec2-user] $ cd
[ec2-user] $ cd testDjango
#Create an app named polls
[ec2-user] $ python manage.py startapp polls
Refer to the previous article [2.2], [2.5]
** Edit settings.py using FileZilla **
testDjango/settings.py
#When you search the IP address on Google etc., the error content is returned.
DEBUG = True
#Change
ALLOWED_HOSTS = ['(EC2 open IP address)','localhost']
#Change
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'rest_framework',
'polls.apps.PollsConfig',
]
#(app name).apps.(先頭大文字app name)Config
...
(Abbreviation)
...
#Remark default settings
# DATABASES = {
# 'default': {
# 'ENGINE': 'django.db.backends.sqlite3',
# 'NAME': BASE_DIR / 'db.sqlite3',
# }
# }
#Fill in new
#[NAME]Is the table name in RDS, which will be created later.
#[USER,PASSWORD,HOST]Enter each
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'dbtest',
'USER': '(DB master user)',
'PASSWORD': '(DB master user password)',
'HOST': '(DB endpoint)',
'PORT': '3306',
}
}
...
(Abbreviation)
...
#Change to Japanese
#LANGUAGE_CODE = 'en-us'
LANGUAGE_CODE = 'ja'
#Change to Japan time
# TIME_ZONE = 'UTC'
TIME_ZONE = 'Asia/Tokyo'
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/'
** Log in to RDS MySQL **
[ec2-user] $ mysql -h (DB endpoint) -u (DB master user name) -p
#You will be asked for a password, so enter it(Characters are not displayed but are typed)(Copy and paste is possible)
>>> Welcome to the MariaDB monitor.
#Is displayed, you can connect to MySQL on RDS.
#Display the list in the database(Lowercase letters are acceptable show database;)
MySQL > SHOW databases;
#Create a table named "dbtest"
MySQL > CREATE DATABASE dbtest;
#End
MySQL > exit
Creating a model
polls/models.py
from django.db import models
class User(models.Model):
#Record creation time
created = models.DateTimeField(auto_now_add=True)
#Record User's name
name = models.CharField(max_length=100, blank=True, default='')
#User email
mail = models.TextField()
class Meta:
ordering = ('created',)
** Migrate the database **
[ec2-user] $ python manage.py makemigrations polls
[ec2-user] $ python manage.py migrate
I will check it
MySQL > show databases;
MySQL > use dbtest;
MySQL > show tables;
>>>
+----------------------------+
| Tables_in_dbtest |
+----------------------------+
| auth_group |
| auth_group_permissions |
| auth_permission |
| auth_user |
| auth_user_groups |
| auth_user_user_permissions |
| django_admin_log |
| django_content_type |
| django_migrations |
| django_session |
| example_table |
| polls_user | <--Have been generated
+----------------------------+ (app name)_user
MySQL > exit
The following articles will be helpful [Learning memo] About Make migrations and Migrate
It is not generated by default, so create it with Notepad or something and transfer it with FileZilla
――Serialization is the conversion of data handled inside the software so that it can be saved, sent and received as it is.
polls/serializers.py
from rest_framework import serializers
from polls.models import User
class UserSerializer(serializers.ModelSerializer):
class Meta:
model = User
fields = ('id', 'name', 'mail')
polls/views.py
from django.http import HttpResponse, JsonResponse
from django.views.decorators.csrf import csrf_exempt
from rest_framework.parsers import JSONParser
from polls.models import User
from polls.serializers import UserSerializer
@csrf_exempt
def user_list(request):
if request.method == 'GET':
#Get all Users from MySQL
polls = User.objects.all()
serializer = UserSerializer(polls, many=True)
#Return with Json
return JsonResponse(serializer.data, safe=False)
elif request.method == 'POST':
data = JSONParser().parse(request)
serializer = UserSerializer(data=data)
if serializer.is_valid():
serializer.save()
#Json data will be returned if registration is successful##status 200 series was processed successfully
return JsonResponse(serializer.data, status=201)
return JsonResponse(serializer.errors, status=400)
Please create a new one as well
polls/urls.py
from django.urls import path
from polls import views
urlpatterns = [
path('user/', views.user_list),
]
** Connect to the original urls.py **
testDjango/urls.py
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('polls.urls')),
]
This completes the settings.
Set up a local server What is local? The following article was easy to understand for those who say Who runs django? (Overview for deployment)
[ec2-user] $ cd
[ec2-user] $ cd testDjango
[ec2-user] $ python manage.py runserver
After this, with Google Chrome etc.
http://(EC2 open IP address)/user/
When you search
[]
I think that empty parentheses are returned.
It's inconvenient to keep this Download the Google Chrome extension ARC
When I try to communicate with GET, empty parentheses are returned
I will try to communicate by POST. At that time
{"name":"tanaka","mail":"[email protected]"}
Add this information.
Press SEND and you'll get a response
You should also check if you have registered properly with GET.
Also the database
MySQL > use dbtest;
MySQL > SELECT * FROM polls_user;
>>>
+----+----------------------------+--------+-------------+
| id | created | name | mail |
+----+----------------------------+--------+-------------+
| 1 | 2020-10-21 05:10:23.730602 | tanaka | [email protected] |
+----+----------------------------+--------+-------------+
Registration is now successful.
I hope this article helps someone.
Next time, I will try to create a production environment (I am a beginner) using NginX, Gunicorn.
Well then
The following and the sites that I have referred to very much in the middle of this article are introduced. Thank you very much.
[1]. Django REST framework tutorial # 1 [2]. Who runs django? (Overview for deployment) [3]. [Learning memo] About Make migrations and Migrate [4]. Frequently Used MySQL Commands
Recommended Posts