Django(2)

Hyerang Kim·2020년 5월 8일
0

Structure of file directories

mysite
├── views.py
└── migrations
|   └── __init__.py
├── models.py
├── settings.py
├── urls.py
db.sqlite3.py

views.py deals with logics
migrations is to save the file that contains table structure defined in models.py created through the makemigrations option from manage.py.
models.py is a related to ORM, which is one of the main functionalities. Basically it defines a database table.
settings.py is literally a file that contains setting information of the project
urls.py is also literally a file regarding url path

views.py

import json
from django.views import View
from django.http  import JsonResponse


class MainView(View):
    def get(self, request):
	return JsonResponse({"Hello":"World"}, status=200)

urls.py

from django.urls import path
from .views  import MainView

urlpatterns = [
    path('', MainView.as_view())
]
  • as_view() determines a HTTP method(GET, POST, PUT DELETE, etc.) and is the function(class method) which will connect my MyView class with its url

    POST: requests supply additional data from the client (browser) to the server in the message body
    GET: requests include all required data in the URL
    PUT: putting or updating a resource on the server
    DELETE: requests that the origin server delete the resource identified by the Request-URI

❓What's going to happen when we click RUN??
✔️There's nothing but single JSON(JavaScript Object Notation) type data comes up!

{"hello":"world"}

There are many built-in modules in Django framework. Below are generally the main factors to manage endpoint view.

import json
from django.views import View
from django.http import JsonResponse

Json is to manage the json data
View class is no need to be implemented manually but need to be inherited from class built in Django framework
JsonResponse is to respond to the server request with json

Below is the view code written with the class format. There are tons of methods built in Django, and def get is one of them. Therefore, we are just overriding by redefining it.

class MainView(View):
    def get(self, request):
	return JsonResponse({"Hello":"World"}, status=200)

As shown on the function name above, this function only respond to the call from GET method in HTTP methods.

Httpie

Before writing a view, install httpie to send Http method.

$ brew install httpie
$ http -v 'browser address'

So that we can run our code locally.

Models

We need a database to save the data in the server. SQLite3(DB) is given!

ORM
It is a Object Relational Mapping, which means it maps the object and relational database. Object Oriented Programming uses class and relational database uses table. Inconsistency exists between object model and relational model. We can resolve the inconsistency through ORM by creating SQL automatically. We can manage database indirectly with objects.

❓So what is models.py for?
✔️We can write and edit models with ORM

First, create the model that contains user's info.

models.py

from django.db import models


class Users(models.Model):
    name       = models.CharField(max_length = 50)
    email      = models.CharField(max_length = 50)
    password   = models.CharField(max_length = 300)
    created_at = models.DateTimeField(auto_now_add = True)
    updated_at = models.DateTimeField(auto_now = True)

views.py

import json
from django.views import View
from django.http  import JsonResponse
from .models      import Users


class MainView(View):
    def post(self, request):
        data = json.loads(request.body)
        Users(
              name     = data['name'],
              email    = data['email'],
	      password = data['password']
        ).save()
        
        return JsonResponse({'message':'SUCCESS'}, status=200)

    def get(self, request):
	return JsonResponse({"Hello":"World"}, status=200)

We overrode post function and get function. It's a logic that enters data into Users model.

http -v 'page address' name='test_name' email='test_email' password='test_password'

If not working, please check mysite/settings.py and make sure to edit them like below.

Settings.py

INSTALLED_APPS = [
   #'django.contrib.admin',
   #'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'account',
    'comment',
]

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',
]

❓How to check the entered data values?
✔️Edit the get function in views.py.

def get(self, request):
    user_data = Users.objects.values()
    return JsonResponse({'users':list(user_data)}, status=200)

The expected result is shown below.

{
  - users: [
     - {
          id: 1,
          name: "pjh"
          email: "aaa@gmail.com"
          password: "1234"
          created_at: "2020-05-08T12:54:22.401Z",
          updated_at: "2020-05-08T12:54:22.401Z"
       }
    ]
}

If this server is operated for real, password would be encrypted.

profile
Backend Developer

0개의 댓글