학습 노트:RESTFUL 자원 의 요청 방법

RESTFUL
RESTFUL 은 프로 그래 밍 스타일 입 니 다.
URL 통합 자원 표식
학생 관리 시스템 의 학생 은 자원 이다.
도서 관리 시스템 의 책 은 자원 이다.
추가 요청 방법
restful 을 사용 하지 않 고 자원 에 대한 요청 방법(자원 인터페이스)
http://127.0.0.1/delete/2/  POST  
http://127.0.0.1/book_list/ GET  
http://127.0.0.1/book/2/    GET  
http://127.0.0.1/update/2/  POST  
http://127.0.0.1/add/       POST  
 

restful 을 사용 하여 자원 에 대한 요청 방법(자원 의 인터페이스)
      http://127.0.0.1/book/ POST   (     )
					   		   GET           

       http://127.0.0.1/book/2/  DELETE      
						          GET         
						          PUT      

브 라 우 저 클 라 이언 트 가 PUT DELETE 를 지원 하지 않 으 면 어떻게 처리 합 니까?
                   _method="DELETE"

  {% csrf_token %}      

     django-admin startproject RESTfulDemo
  app  django-admin startapp app

settings.py

ALLOWED_HOSTS = ['10.8.152.31']


# Application definition

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'app',
    'book',
]






restfuldemo/urls.py

from django.conf.urls import url,include
from django.contrib import admin

urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^',include('app.urls'))
]




app/urls.py      
   

from django.conf.urls import url
from app.views import home

urlpatterns = [
    url(r'^$',home)  # ^$    
]


   
# from django.conf.urls import url
# from app import views
#
# urlpatterns = [
#     url(r'^$',views.home)  # ^$    
# ]




app/views.py
from django.shortcuts import render
from django.http import JsonResponse

# Create your views here.

#REST  API (JSON        )

def home(request):
    if request.method == 'GET':
        return JsonResponse({'method':'GET'})

    elif request.method == 'POST':
        return JsonResponse({'method':'POST'})

    elif request.method == 'PUT':
        #    
        return JsonResponse({'method':'PUT'})

    elif request.method == 'DELETE':
        #      
        return JsonResponse({'method':'DELETE'})

    return render(request,template_name='index.html')




templates/index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>

<h2>hello</h2>

</body>
</html>


   

2 급 분류
     django-admin startproject RESTfulDemo
  app  django-admin startapp app 
  app  django-admin startapp book


book/models.py

from django.db import models
from datetime import datetime
# Create your models here.
#                

#    
class BookCategory(models.Model):
    CATEGORY_TYPE = [
        (1,'    '),
        (2,'    '),
    ]
 #    
    name = models.CharField('   ',max_length=50)

    #   code   
    code = models.CharField('  code',max_length=50)

    #      
    description = models.TextField('    ',default='')

    #      
    category_type = models.IntegerField('    ',choices=CATEGORY_TYPE)

    #             
    is_nav = models.BooleanField('     ',default=False)

    #              
    # self       
    parent_category = models.ForeignKey('self',on_delete=models.CASCADE,
                                        null=True,blank=True,
                                        verbose_name='    ',
                                        related_name='sub_category')
		    
     #           ForeignKey   MangToMang                    #verbose_name      related_name       
      
        
        # Meta         
        class Meta:
        #       
        verbose_name = "    "
        #            
        verbose_name_plural=verbose_name

    def __str__(self):
        return self.name
    
 #          ,   Foreign        on_delete=models.CASCADE        ,    ,                          


#   
class Book(models.Model):
    #   
    name = models.CharField(max_length=100)
    
    #   FloatField       
    price = models.FloatField()
    
    #  
    category=models.ForeignKey(BookCategory,
                               on_delete=models.CASCADE,
                               verbose_name='    ')
    #  
    cover=models.ImageField(upload_to='/books/images/',
                            null=True,
                            blank=True,
                            verbose_name='    ')

    #  
    inventory = models.IntegerField('   ',default=0)
    
    #     
    is_new = models.BooleanField('     ',default=False)
    #       
    is_hot = models.BooleanField('       ',default=False)
    #      
    add_time = models.DateTimeField('      ',default=datetime.now)

    class Meta:
        verbose_name = '    '
        verbose_name_plural = '    '

    def __str__(self):
        return self.name

  :
python manage.py makemigrations
python manage.py migrate



 book         database_help               
 database_help      data    data           book_category.py

 data      import_category_to_database.py          



				    |———data ————book_category.py
book—— database_help  |
					|———import_category_to_database.py
    
 

book_category.py
#           
book_category = [
    #    ,    

    {
        'code':'ETWX',  #  code   
        'name':'    ', #    

    #                         
        'sub_category':[
            {
                'code':'ZGETWX',
                'name':'      '
            },

            {
                'code':'WGETWX',
                'name':'      '
            },
            {
                'code':'SEYY',
                'name':'    '
            },

        ]
    },



    #    ,      
    {
        'code':'LZ',
        'name':'  ',
    #              
        'sub_category':[

            {
                'code':'LZCG',
                'name':'    '},
            {
                'code':'XLXY',
                'name':'    '},

        ]
    },

]

#      json  

import json
#json.dumps(book_category)

#  
print(json.dumps(book_category))
  
[{"name": "\u513f\u7ae5\u56fe\u4e66", "code": "ETWX", "sub_category": [{"name": "\u4e2d\u56fd\u513f\u7ae5\u6587\u5b66", "code": "ZGETWX"}, {"name": "\u5916\u56fd\u513f\u7ae5\u6587\u5b66", "code": "WGETWX"}, {"name": "\u5c11\u513f\u82f1\u8bed", "code": "SEYY"}]}, {"name": "\u52b1\u5fd7", "code": "LZ", "sub_category": [{"name": "\u52b1\u5fd7\u6210\u529f", "code": "LZCG"}, {"name": "\u5fc3\u7075\u4fee\u517b", "code": "XLXY"}]}]#os.path  sys.path
 #__file__    #             
 #os.path.dirname()        
 os.path      ,      、       。 
sys.path      ,            、    、        
   

sys.path ——      Python    
  python    package module      PATH ,      sys.path     package module   PATH     。
sys.path.append('       ')   
sys.path.insert(0, '       ')  




         
import_category_to_database.py


import os
import sys
BASE_DIR =os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
#print(BASE_DIR )      C:\Users\Administrator\Desktop\RESTfulDemo-9.1
 
#print(sys.path)        
['C:\\Users\\Administrator\\Desktop\\RESTfulDemo-9.1\\book\\database_help', 'C:\\Users\\Administrator\\Desktop\\RESTfulDemo-9.1', 'C:\\Users\\Administrator\\PycharmProjects\\02-xuni\\venv\\Scripts\\python35.zip', 'C:\\Users\\Administrator\\AppData\\Local\\Programs\\Python\\Python35\\DLLs', 'C:\\Users\\Administrator\\AppData\\Local\\Programs\\Python\\Python35\\lib', 'C:\\Users\\Administrator\\AppData\\Local\\Programs\\Python\\Python35', 'C:\\Users\\Administrator\\PycharmProjects\\02-xuni\\venv', 'C:\\Users\\Administrator\\PycharmProjects\\02-xuni\\venv\\lib\\site-packages', 'C:\\Users\\Administrator\\PycharmProjects\\02-xuni\\venv\\lib\\site-packages\\setuptools-39.1.0-py3.5.egg']


#print(sys.path)        
['C:\\Users\\Administrator\\Desktop\\RESTfulDemo-9.1\\book\\database_help', 'C:\\Users\\Administrator\\Desktop\\RESTfulDemo-9.1', 'C:\\Users\\Administrator\\PycharmProjects\\02-xuni\\venv\\Scripts\\python35.zip', 'C:\\Users\\Administrator\\AppData\\Local\\Programs\\Python\\Python35\\DLLs', 'C:\\Users\\Administrator\\AppData\\Local\\Programs\\Python\\Python35\\lib', 'C:\\Users\\Administrator\\AppData\\Local\\Programs\\Python\\Python35', 'C:\\Users\\Administrator\\PycharmProjects\\02-xuni\\venv', 'C:\\Users\\Administrator\\PycharmProjects\\02-xuni\\venv\\lib\\site-packages', 'C:\\Users\\Administrator\\PycharmProjects\\02-xuni\\venv\\lib\\site-packages\\setuptools-39.1.0-py3.5.egg', 'C:\\Users\\Administrator\\Desktop\\RESTfulDemo-9.1'] #       
         
import_category_to_database.py

import os
import sys
BASE_DIR =os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
#       
sys.path.append(BASE_DIR)
 
 

#   setting    setdefault     
if __name__ =='__main__':
    os.environ.setdefault("DJANGO_SETTINGS_MODULE","RESTfulDemo.settings")
#    django
import django
django.setup()

#       
from book.database_help.data.book_category import book_category
#     
from book.models import BookCategory
#   book_category     ,           

#       
for lev1 in book_category:
    print(">>>",lev1)
    #          
    lev1_instance =  BookCategory()
    lev1_instance.code = lev1['code']
    lev1_instance.name = lev1['name']
    lev1_instance.category_type=1
    lev1_instance.save()


    for lev2 in lev1['sub_category']:
        print('<<, lev2)

        #          
        lev2_instance = BookCategory()
        lev2_instance.code = lev2['code']
        lev2_instance.name = lev2['name']
        lev2_instance.category_type = 2
        #         
        lev2_instance.parent_category = lev1_instance
        lev2_instance.save()

    
 


  

좋은 웹페이지 즐겨찾기