ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • [WebPage] 실전 웹 프로젝트 구축 !!(Client Part 1) - 웹 페이지 제작 강좌
    Web/WebPage 2015. 7. 9. 14:48

    이제 클라이언트(Client)를 개발할 차례입니다. 




    연결된 강좌이므로 아래 링크대로 따라주시면 이해가 더 쉬우실 것 입니다.

    ===========================================


    1. 개발환경설정

    2. CSS & Bootstrap 

    3. CSS 선택자(Selector)

    4. CSS 요소(Element)

    5. Bootstrap Part. 1

    6. Bootstrap Part. 2

    7. 실전 예제 - 개인용 포트폴리오 페이지 제작

    8. Python & Django

    9. Django

    10. 장고(Django) 프로젝트

    11. JavaScript & jQuery

    12. 실전 웹 프로젝트(예제)


    13. 실전 웹 프로젝트(Timeline) Server Part.1


    ===========================================







    시작하기전 CORS(Cross Origin Resource Sharing)을 처리하기 위하여 settings.py를 열어서 아래와 같이 해당 소스를 추가해줍니다. MIDDLEWARE_CLASSES를 아래로 대체하세요.


     * 가장 하단에 보시면 '프로젝트명.cors.XsSharingMiddleware', 형식으로 추가되었음을 확인 할 수 있습니다.


    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    MIDDLEWARE_CLASSES = (
        'django.middleware.common.CommonMiddleware',
        'django.contrib.sessions.middleware.SessionMiddleware',
        #'django.middleware.csrf.CsrfViewMiddleware',
        'django.contrib.auth.middleware.AuthenticationMiddleware',
        'django.contrib.messages.middleware.MessageMiddleware',
        # Uncomment the next line for simple clickjacking protection:
        # 'django.middleware.clickjacking.XFrameOptionsMiddleware',
        'timelineproject.cors.XsSharingMiddleware',
    )
    cs



    그리고 나서 아래 주소에 접속하여 cors.py를 받아서 settings.py가 들어있는 폴더에 저장해줍니다.

    https://gist.github.com/3733574



    우선 프로젝트 틀을 갖추기 위해서 새로운 프로젝트를 생성하여 Bootstrap 까지 복사하겠습니다.



    그리고 join.html, timeline.css, timeline.js 까지 생성해 놓겠습니다.



    완료된 프로젝트 구조는 아래와 같습니다.







    다음 해당되는 파일들을 아래 경로에다가 넣어주세요.


    timelineproject -> templates -> timeline


    templates폴더 생성한 뒤, timeline 생성해서 넣어주시면 됩니다.







    1. 먼저 HTML의 틀을 잡겠습니다. join.html을 열어 아래와 같이 작성해주세요.





    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
     
    <!DOCTYPE html>
    <html lang="ko">
        <head>
            <meta charset="utf-8"/>
            <title>Timeline Example</title>
            <link href="bootstrap/css/bootstrap.css" rel="stylesheet"/>
            <link href="timeline.css" rel="stylesheet"/>
            <link href="bootstrap/css/bootstrap-responsive.css" rel="stylesheet"/>
        </head>
        <body>
            <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
            <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/jquery-ui.min.js"></script>
            <script src="bootstrap/js/bootstrap.js"></script>
            <script src="timeline.js"></script>
            <script>
                $(document).ready(function() {
                    
                });
           </script>
        </body>
    </html>
    cs




     - Bootstrap, jQuery 라이브러리 추가를 위한 간단한 코드와 HTML 틀을 구성하기 위한 소스입니다.











    2. 다음으로 네비게이션으로 상단 메뉴를 구성하겠습니다.






     위에서 작성한 join.html의 body 태그에 작성해주세요.


    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
            <div class="navbar navbar-inverse navbar-fixed-top">
                <div class="navbar-inner">
                    <div class="container">
                        <a class="btn btn-navbar" data-toggle="collapse" data-target="#navMenu">
                            <span class="icon-bar"></span>
                            <span class="icon-bar"></span>
                            <span class="icon-bar"></span>
                        </a>
                        <a class="brand" href="login.html">TimeLine service</a>
                        <div class="nav-collapse" id="navMenu">
                            <div class="btn-group pull-right">
                                <a class="btn" id="adminBtn">
                                    <i class="icon-pencil"></i>
                                    ADMIN
                                </a>
                            </div>
                        </div>
                    </div>
                </div>
            </div><!-- End of NavBar -->
    cs



     - 화면의 Navigation Bar를 생성하기 위해 작성한 코드입니다.




    실행 결과 아래와 같이 나옵니다.












    3. 메뉴를 완성했으니, 페이지 레이아웃을 구성해보도록 하겠습니다.





    navbar 밑에 작성하세요.



    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    <div class="container">
                <!-- Start of Container -->
                <div class="row-fluid">
                    <!-- Start of Row -->
                    <div class="span12">
                        <div class="inside">
                            <br>
                            <div class="lighblue">
                                <h1>Create Account</h1>
                            </div>
                            <div>
                                <h3>Join our Service!</h3>
                            </div>
                            <br>
                        </div>
                    </div>
                </div><!-- End of Row -->
                <div class="row-fluid">
                    <!-- Start of Row2 -->
                    <div class="span6">
                        <div class="inside center">
                            <h2>ID</h2>
                            <input type="text" placeholder="Input Your ID" id="username"/>
                        </div>
                    </div>
                    <div class="span6">
                        <div class="inside center">
                            <h2>PASSWORD</h2>
                            <input type="text" placeholder="Input your Password" id="password"/>
                        </div>
                    </div>
                </div><!-- End of Row 2 -->
                <div class="row-fluid">
                    <!-- Start of Row3 -->
                    <div class="span12">
                        <div class="inside center">
                            <h2>NAME</h2>
                            <input type="text" placeholder="Input your Name" id="name"/>
                        </div>
                    </div>
                </div><!-- End of Row3 -->
                <div class="row-fluid">
                    <!-- Start of Row 4 -->
                    <div class="span12">
                        <div class="inside center">
                            <a class="btn btn-large btn-info" id="joinBtn">Join Now!</a>
                        </div>
                    </div>
                </div><!-- End of Row 4 -->
            </div><!-- End of Container -->
    cs




    실행결과 간단한 화면이 구성될 것 입니다. 그러나 상단의 메뉴바와 문구가 약간 겹치는 현상이 있습니다. 

    본격적으로 CSS를 추가하여 조절하도록 하겠습니다.







    4. CSS를 열어서 아래와 같이 작성합니다.





    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    /* join page */
    body {
        background-color: #C0DEED;
        padding-top: 60px;
        padding-bottom: 40px;
        font-family: calibri;
    }
    .row-fluid div[class*="span"] {
        background-color: white;
        -webkit-border-radius: 6px;
        -moz-border-radius: 6px;
        border-radius: 6px;
        margin-bottom: 10px !important;
    }
    .center {
        text-align: center;
        font-size: 16px;
    }
    .inside {
        margin: 10px;
    }
    .lighblue {
        color: #5b7dc1;
    }
     
    cs




     실행결과 좀 더 깔끔하게 구현되어 집니다.














    5. JS를 준비된 API와 연동하기 위해 timeline.js를 열어서 아래와 같이 작성합니다.







    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    var baseUrl = 'http://127.0.0.1:8000/';
    var username;
    var password;
     
    var doJoin = function() {
        var name = $("#name").val();
     
        username = $("#username").val();
        password = $("#password").val();
     
        $.ajax({
            type : 'POST',
            url : baseUrl + 'api/user/create/',
            data : {
                username : username,
                password : password,
                name : name
            },
            success : function() {
                alert("OK");
                location.href = "login.html";
            },
            error : function(msg) {
                alert("Error!");
            },
        });
     
    };
     
    var goAdmin = function() {
        location.href = baseUrl + "admin/";
    };
     
    cs






    다음은 작성된 js를 html에 연결하는 코드를 작성하겠습니다. join.html을 열어 아래 부분을 추가합니다.



    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
     
            <script>
                $(document).ready(function() {
                    $("#joinBtn").click(function() {
                        var name = $("#name").val();
                        var username = $("#username").val();
                        var password = $("#password").val();
                        
                        if (name != "" && username != "" && password != "")
                            doJoin();
                        else 
                            alert("Fill all forms");
                    });
                    $("#adminBtn").click(goAdmin);
                });
            </script>
    cs





    이렇게 하면 계정생성 페이지가 완성이 되었습니다.


    간단하게 테스트 결과 login.html의 부재로 인해 깔끔하지가 않습니다. 다음으로 로그인 페이지를 만들도록 하겠습니다.








    6. template.html을 작성한 뒤, 복사하여 login.html의 틀을 잡겠습니다.






    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    <!DOCTYPE html>
    <html lang="ko">
        <head>
            <meta charset="utf-8"/>
            <title>Timeline Example</title>
            <link href="bootstrap/css/bootstrap.css" rel="stylesheet"/>
            <link href="timeline.css" rel="stylesheet"/>
            <link href="bootstrap/css/bootstrap-responsive.css" rel="stylesheet"/>
        </head>
        <body>
            <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
            <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/jquery-ui.min.js"></script>
            <script src="bootstrap/js/bootstrap.js"></script>
            <script src="timeline.js"></script>
            <script>
                $(document).ready(function() {
     
                });
           </script>
        </body>
    </html>
    cs




    위와 같이 작성된 template.html을 토대로 복사하여서 login.html을 똑같이 만듭니다.







    7. login.html의 레이아웃을 구성 하겠습니다.





     먼저 상단 네비게이션 바를 구성하겠습니다. body 태그 위에서부터 작성하세요.



    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
        <body>
            <div class="navbar navbar-inverse navbar-fixed-top">
                <div class="navbar-inner">
                    <div class="container">
                        <a class="btn btn-navbar" data-toggle="collapse" data-target="#navMenu">
                            <span class="icon-bar"></span>
                            <span class="icon-bar"></span>
                            <span class="icon-bar"></span>
                        </a>
                        <a class="brand" href="login.html">TimeLine Service</a>
                        <div class="nav-collapse" id="navMenu">
                            <div class="btn-group pull-right">
                                <a class="btn" id="adminBtn">
                                    <i class="icon-pencil"></i>
                                    ADMIN
                                </a>
                            </div>
                        </div>
                    </div>
                </div>
            </div><!-- End of NavBar -->
    cs






    다음으로 레이아웃을 구성하겠습니다. 네비바 다음부터 작성해주세요.


    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
            </div><!-- End of NavBar -->
            <div class="container bg logincontainer"><!-- Start of Container -->
                <div class="row-fluid"><!-- Start of Row -->
                    <div class="span8">
                        <div class="inside center loginbox">
                            <h1 class="bigfont lightblue middlemsg">Time Line Service</h1>
                        </div>
                    </div>
                    <div class="span4">
                        <div class="inside center loginbox"><br>
                            <div class="alert alert-info">
                                <h4>Login Please</h4>
                            </div>
                            I D : <input type="text" id="username" class="width50"/> <br>
                            P W : <input type="password" id="password" class="width50" />
                            <div class="inside">
                                <a class="btn btn-primary" id="loginBtn"
                                    Login
                                </a>
                                <a class="btn btn-primary between" id="registerBtn">
                                    Register
                                </a>
                            </div>
                        </div>
                    </div>
                </div><!-- End of Row -->
            </div><!-- End of Container -->
    cs






    실행 결과 아래와 같습니다. 추가적으로 CSS를 적용시켜야 합니다.









    8. timeline.css를 작성 하겠습니다.





     가장 하단 부터 작성하시면 되겠습니다. (이전에 작성한 코드 맨 하단에)



    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    /* login page */
    .logincontainer {
        padding: 15px;
        margin-top: 120px;
    }
    .between {
        margin-left: 30px;
    }
    .bg {
        padding: 15px;
        background: url('http://bit.ly/MTt30q');
    }
    .loginbox {
        height: 200px;
    }
    .middlemsg {
        padding-top: 80px;
    }
    .bigfont {
        font-size: 60px;
        font-weight: bold;
    }
    .width50 {
        width: 50%;
    }
     
    cs




     더욱 깔끔한 구성으로 바뀌었습니다.













    9. 직접적으로 인증을 하기 위한 javascript를 작성 하겠습니다.





     장고(Django)에서도 사용한 Basic Auth를 통해 인증을 구현하도록 하겠습니다.

     - 간단히 설명한다면, Basic Auth는 암호화 방법으로 base64 encoding을 사용합니다. 

     - 그럼 아래 링크로 접속하여 소스를 복사해서 timeline.js와 같은 경로에 넣어줍니다.(base64.js 파일명으로)

      http://www.webtoolkit.info/javascript-base64.html



     다음으로 login.html에 아래 코드를 추가합니다.


    1
            <script src="base64.js"></script>
    cs




     timeline.js를 열어서 아래 코드를 추가합니다.


    1
    var loginstring;
    cs



    맨 상단에 var password 밑에 위 코드를 추가해 주시고, 로그인에 필요한 기능 함수를 맨 하단에 작성하도록 하겠습니다.




    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
     
    var doLogin = function() {
        username = $("#username").val();
        password = $("#password").val();
        loginstring = "Basic " + Base64.encode(username + ":" + password);
        
        $.ajax({
            type: 'GET',
            url: baseUrl + 'api/login/',
            beforeSend: function(req) {
                req.setRequestHeader('Authorization', loginstring);
            },
            success: function(data) {
                alert("Login Success");
                setLoginString();
                window.location = "timeline.html";
            },
            error: function() {
                alert("Fail to get data!");
            }
        });
    };
     
    cs





     다음으로는 쿠키를 통해서 로그인 상태에 대해 담는 그릇을 생성하겠습니다.



     위 코드 아래 부분에 다음과 같이 작성합니다.



    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
     
    function setCookie(name, value, day) {
        var expire = new Date();
        expire.setDate(expire.getDate() + day);
        cookies = name + '=' + escape(value) + '; path=/ ';
        
        if (typeof day != 'undefined')
            cookies += ';expires=' + expire.toGMTString() + ';';
        
        document.cookie = cookies;
    }
     
    function getCookie(name) {
        name = name + '=';
        var cookieData = document.cookie;
        var start = cookieData.indexOf(name);
        var value = '';
        
        if (start != -1) {
            start += name.length;
            var end = cookieData.indexOf(';', start);
            
            if (end == -1
                end = cookieData.length;
            
            value = cookieData.substring(start, end);
        }
        
        return unescape(value);
    }
     
    cs




     추가적으로 쿠키를 이용해서 로그인 데이터를 유지하기 위한 함수를 더 작성하도록 하겠습니다.


    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
     
    function getLoginString() {
        loginstring = getCookie("loginstring");
        username = getCookie("username");
    }
     
    function setLoginString() {
        setCookie("loginstring", loginstring, 1);
        setCookie("username", username, 1);
    }
     
    function resetLoginString() {
        setCookie("loginstring""""-1");
        setCookie("username""""-1");
    }
     
    function checkLoginString() {
        if (loginstring == "") {
            history.back();
        }
    }
     
    cs





     마지막으로 작성된 기능들에 대해 login.html에서 연결해보도록 하겠습니다.



    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
     
            <script>
                $(document).ready(function() {
                    $("#registerBtn").click(function() {
                        location.href = "join.html";
                    });
                    $("#loginBtn").click(doLogin);
                    $("#adminbtn").click(goAdmin);
                });
           </script>
     
    cs





     로그인 화면에서 계정에 대한 로그인을 시도해서 Login Success 가 뜨는 지 확인합니다.

     다음으로 넘어가는 timeline.html이 부재로 미완성이라는 것을 염두해 둡니다.
















    여기까지해서 간단한 로그인 및 계정 생성을 구현하였습니다.



    다음 장에서 타임라인에 대한 구현을 진행하도록 하겠습니다.



    질문 사항은 댓글이나 DISQUS를 통해 달아주세요.





    * 본 포스팅은 이재근 등 4명 저 "Fast Web Service Build up: 웹 서비스를 쉽고 빠르게 구축하는 기술" 저서를 참고하여 작성하였습니다



    댓글

Designed by Tistory.