ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • 장고 앞으로 공부할 것들
    백엔드 : 서버공부/Django 2023. 8. 7. 19:35
    728x90

    앞에서 공부한 내용은 기본적인 내용입니다. 현실의 복잡한 문제들을 해결하려면 더 많은 것을 공부해야합니다.

     

     

    DataBase.Model

    아래와 같은 코드를 작성해서 저희는 정보를 메모리에 보관했습니다.

    topics = [
    {'id':1, 'title':'routing','body':'Routing is ..'},
    {'id':2, 'title':'view','body':'View is ..'},
    {'id':3, 'title':'Model','body':'Model is ..'}
    ]

    정보를 위와같이 메모리에 보관하게 되면 앱이 재실행 될때마다 정보가 리셋됩니다. 

     

    하지만 실무에서는 영구적으로 정보를 저장할 필요가 있습니다. 이를 위해서 'DataBase'를 이용합니다.

    출처:https://www.techopedia.com/definition/24361/database-management-systems-dbms

    DataBase를 이용하면 영구적으로 데이터를 저장할 수 있을뿐만아니라, 빠른속도로 데이터에 접근할 수 있습니다.

     

    또한 장고에는 Model이라는 기능이 내장되어있습니다.

    이를 이용해 데이터베이스를 쉽게 이용할 수 있습니다.

     

    Security

    다음으로는 웹과 관련된 보안도 공부해 볼 수 있겠습니다.

     

    Template engine

    또한 Template engine을 공뷰해볼 수 있습니다.

    from django.shortcuts import render, HttpResponse,redirect
    from django.views.decorators.csrf import csrf_exempt
    
    nextId = 4
    topics = [
    {'id':1, 'title':'routing','body':'Routing is ..'},
    {'id':2, 'title':'view','body':'View is ..'},
    {'id':3, 'title':'Model','body':'Model is ..'}
    ]
    
    def HTMLTemplate(articleTag, id=None):
        global topics
        contextUI = ''
        if id != None:
            contextUI = f'''
                <li>
                    <form action="/myapp/delete/" method="post">
                        <input type="hidden" name="id" value={id}>
                        <input type="submit" value="delete">
                    </form>
                </li>
                <li>
                    <a href="/myapp/update/{id}">update</a>
                </li>
            '''
        ol = ''
        for topic in topics:
            ol += f'<li><a href="read/{topic["id"]}">{topic["title"]}</a></li>'
        return f'''
        <html>
        <body>
            <h1><a href="/myapp">Django</a></h1>
            <ul>
                {ol}
            </ul>
            {articleTag}
            <ul>
                <li><a href="/myapp/create/">create</a></li>
                {contextUI}
            </ul>
        </body>
        </html>
       '''
    
    def index(request) :
        article = '''
        <h2>Welcome</h2>
            Hello, Django
        '''
        return HttpResponse(HTMLTemplate(article))
    def read(request, id):
        global topics
        article = ''
        for topic in topics:
            if topic['id'] == int(id):
                article=f'<h2>{topic["title"]}</h2>{topic["body"]}'
        return HttpResponse(HTMLTemplate(article, id))
    
    @csrf_exempt
    def create(request):
        global nextId
        print('request.method',request.method)
        if request.method == 'GET':
            article = '''
        		<form action="/myapp/create/" method="post">
                    <p><input type="text" name="title" placeholder="title"></p> 
                    <p><textarea name="body" placeholder="body"></textarea></p>
                    <p><input type="submit"></p>
                </form>
            '''
            return HttpResponse(HTMLTemplate(article))
        elif request.method == 'POST':
            title = request.POST['title']
            body = request.POST['body']
            newTopic = {"id":nextId, "title":title, "body":body}
            topics.append(newTopic)
            url = '/myapp/read/'+str(nextId)
            nextId+=1
            return redirect(url)
        
    
    @csrf_exempt
    def delete(request):
        global topics
        if request.method == 'POST':
            id = request.POST['id']
            newTopics = []
            for topic in topics:
                if topic['id'] != int(id):
                    newTopics.append(topic)
            topics = newTopics
            return redirect('/myapp/')
       
    @csrf_exempt
    def update(request, id):
        global topics
        if request.method == 'GET':
           for topic in topics :
               if topic['id'] == int(id):
                   selectedTopic = {
                       "title":topic['title'],
                       "body":topic['body']
                   }
           article = f'''
        		<form action="/myapp/update/{id}" method="post">
                    <p><input type="text" name="title" placeholder="title" value={selectedTopic["title"]}></p> 
                    <p><textarea name="body" placeholder="body">{selectedTopic['body']}</textarea></p>
                    <p><input type="submit"></p>
                </form>
            '''
       
           return HttpResponse(HTMLTemplate(article, id))
        elif request.method == 'POST':
               title = request.POST['title']
               body = request.POST['body']
               for topic in topics :
                    if topic['id'] == int(id):
                        topic['title']=title
                        topic['body']=body
               return redirect(f'/myapp/read/{id}')

    기존의 코드는 html코드와 파이썬 코드가 섞여있어 가독성도 떨어지고, 실수하기 쉽게 작성되어 있습니다.

     

    하지만 Template engine를 이용한다면, 별도의 html파일을 만들고, 그안에 변경이 필요한 부분만 약속된 문법에 맞게 코드를 작성하면 됩니다.

    파이썬코드와 html코드를 분리해서 작성할수있는 편리함을 갖고있습니다.

     

    '백엔드 : 서버공부 > Django' 카테고리의 다른 글

    AWS 계정 생성과 리전 선택  (9) 2023.08.09
    AWS기반의 Django 웹 애플리케이션  (10) 2023.08.08
    장고 수정 기능 구현  (0) 2023.07.31
    장고 삭제 기능 구현  (0) 2023.07.29
    장고 생성 기능 구현 2  (0) 2023.07.29
Designed by Tistory.