[PYTHON] I made a webAPI! Build environment from Django Rest Framework 1 on EC2

Introduction

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)

Prerequisites

-EC2, RDS, Django connection completed

Django project creation

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

Django settings

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

Create serializers.py

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')

Implement views.py

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)

Create polls / urls.py

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.

Testing

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.

Enter data

It's inconvenient to keep this Download the Google Chrome extension ARC

Advanced REST client download

When I try to communicate with GET, empty parentheses are returned

スクリーンショット 2020-10-21 14.01.45.png

I will try to communicate by POST. At that time


{"name":"tanaka","mail":"[email protected]"}

Add this information.

スクリーンショット 2020-10-21 14.07.27.png

Press SEND and you'll get a response

スクリーンショット 2020-10-21 14.10.35.png

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.

in conclusion

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

Reference site

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

I made a webAPI! Build environment from Django Rest Framework 1 on EC2
# 3 Build a Python (Django) environment on AWS EC2 instance (ubuntu18.04) part2
Build a Django environment on Raspberry Pi (MySQL)
Build a Django development environment using pyenv-virtualenv on Mac
# 2 Build a Python environment on AWS EC2 instance (ubuntu18.04)
I made a Python3 environment on Ubuntu with direnv.
How to build a Django (python) environment on docker
[AWS] I tried using EC2, RDS, Django. Environment construction from 1
Build a python3 environment on CentOS7
I made a development environment for Django 3.0 with Docker, Docker-compose, Poetry
Build a python environment on MacOS (Catallina)
I want to build a Python environment
Build a Python + OpenCV environment on Cloud9
I made a WEB application with Django
Build a "Deep learning from scratch" learning environment on Cloud9 (jupyter miniconda python3)
Build a LAMP environment on your local Docker
Build a WardPress environment on AWS with pulumi
Build python environment with pyenv on EC2 (ubuntu)
What I found by deploying Django on EC2
Simply build a Python 3 execution environment on Windows
Build a python environment with ansible on centos6
Build a Python environment on Mac (Mountain Lion)
[Python] Build a Django development environment with Docker
Build a Django environment with Vagrant in 5 minutes
Build a Python development environment on your Mac
I made a LINE Bot with Serverless Framework!
Build a Django development environment with Doker Toolbox
Django REST framework A little useful to know.
Build a Kubernetes environment for development on Ubuntu
Quickly build a Python Django environment with IntelliJ
Create a Python execution environment on IBM i
Build a TensorFlow development environment on Amazon EC2 with command copy and paste
Build a Python development environment on Raspberry Pi
[Django] Hit a command you made from within the process that runs on manage.py.
Create a Todo app with Django REST Framework + Angular
Build a GVim-based Python development environment on Windows 10 (3) GVim8.0 & Python3.6
Build a machine learning Python environment on Mac OS
Create a Todo app with the Django REST framework
What I did when I stumbled on a Django tutorial
[Part 2] Let's build a web server on EC2 Linux
Build a GVim-based Python development environment on Windows 10 (1) Installation
I want to easily build a model-based development environment
Build a Python development environment on Mac OS X
Build a Python virtual environment using venv (Django + MySQL ①)
[Go + Gin] I tried to build a Docker environment
Build a Python development environment using pyenv on MacOS
Deploy a Django app made with PTVS on Azure
How to build a Python environment on amazon linux 2
Build a Django environment for Win10 (with virtual space)
Build a machine learning environment natively on Windows 10 (x64)
Django REST framework basics
Django Rest Framework Tips
When I tried to build a Rails environment on WSL2 (Ubuntu 20.04LTS), I stumbled and fell.
Build a python machine learning study environment on macOS sierra
Install LAMP on Amazon Linux 2 and build a WordPress environment.
Build a machine learning environment on mac (pyenv, deeplearning, opencv)
Build a Django development environment with Docker! (Docker-compose / Django / postgreSQL / nginx)
How to build a new python virtual environment on Ubuntu
[Memo] Build a development environment for Django + Nuxt.js with Docker
I made a box to rest before Pepper gets tired
I made a command to generate a table comment in Django