• [파이썬 기초]URL 쿼리스트링(Query String) 가져오기

    2021. 3. 12.

    by. 웰시코더

    반응형

    -URL의 쿼리스트링(Query String) 값을 가져오는 방법을 알아본다.

    -생활코딩의 파이썬 강의를 바탕으로 학습하였다.

    -파이썬은 3.9.2 ver를 사용한다.


    쿼리스트링이란?

     

     URL의 뒤에 입력 데이터를 함께 제공하는 가장 단순한 데이터 전달 방법이다. 웹개발에서 데이터를 요청하는 방식 중 대표적인 것이 GET방식과 POST방식인데, 주로 GET방식으로 데이터를 요청할 때 쓰이는 방법이다.

     

    URL주소뒤에 물음표(?)를 붙이고 key1=value1&key2=value2...방식으로 데이터를 요청한다.

     

    예를 들어 다음과 같은 URL을 가정해보자.

     

    https://roadofdevelopment.tistory.com?category=python&category=1

     이 경우라면 category=python이라는 데이터와 category=1이라는 데이터를 전달한 것이다. 쿼리스트링에 대한 부분은 실무 경험이나 프로젝트 경험을 하면서 자연스레 터득이 되기 때문에 처음 개발공부를 한 사람들이라면 이해가 잘 안 될수도 있으니 '데이터를 넘길 때 주소창을 이용해 넘기는 방법' 정도로 이해하고 넘어가거나 아래 파이썬 학습을 통해 학습하길 바란다.

     

    쿼리스트링을 사용하여 데이터를 동적으로 표현하기

    127.0.0.1/index.py로 접속을 하면 다음과 같은 화면이 나온다.

     

    위의 화면에서 최상단의 WEB이라는 타이틀과 그 아래 서브타이틀인 1.HTML, 2.CSS, 3.JavaScript라는 서브타이틀을 클릭시 동적으로 그 아래 글제목(현재 WEB)을 변경하려고 한다.

     

    일단 index.py의 코드를 살펴보자. 코드는 다음과 같다.

     

    #!Python
    print("Content-Type: text/html")    # HTML is following
    print()
    
    print('''<!doctype html>
    <html>
    <head>
      <title>WEB1 - Welcome</title>
      <meta charset="utf-8">
    </head>
    <body>
      <h1><a href="index.html">WEB</a></h1>
      <ol>
        <li><a href="1.html">HTML</a></li>
        <li><a href="2.html">CSS</a></li>
        <li><a href="3.html">JavaScript</a></li>
      </ol>
      <h2>WEB</h2>
      <p>The World Wide Web (abbreviated WWW or the Web) is an information space where documents and other web resources are identified by Uniform Resource Locators (URLs), interlinked by hypertext links, and can be accessed via the Internet.[1] English scientist Tim Berners-Lee invented the World Wide Web in 1989. He wrote the first web browser computer program in 1990 while employed at CERN in Switzerland.[2][3] The Web browser was released outside of CERN in 1991, first to other research institutions starting in January 1991 and to the general public on the Internet in August 1991.
      </p>
    </body>
    </html>
    ''')
    

     

    우선 쿼리스트링을 각 메뉴에 적용해본다. 각각의 버튼을 누르면 href로 이동할 수 있기 때문에 href 속성을 쿼리스트링 방식으로 변경하여 각각 고유 값을 얻도록 변경한다.

     

     <h1><a href="index.py?id=WEB">WEB</a></h1>
      <ol>
        <li><a href="index.py?id=HTML">HTML</a></li>
        <li><a href="index.py?id=CSS">CSS</a></li>
        <li><a href="index.py?id=JavaScript">JavaScript</a></li>
      </ol>

     위와 같이 쿼리스트링 방식으로 바꾸었다. 예를들어 HTML이라는 버튼을 누르면 127.0.0.1/index.py?id=HTML이라는 URL로 이동한다.

     

     앞에 소개했듯이 httpd.conf 파일에 DocumentRoot "C:/Bitnami/wampstack-8.0.2-1/apache2/htdocs"라는 루트 설정이 있기 때문에, 루트를 htdocs부터 찾는다. index.py가 htdocs폴더 밑에 있기 때문에 href를 클릭하면 127.0.0.1/index.py?id=HTML이라고 URL이 나오는 것이다.

     

    이제 이 쿼리스트링 값을 화면이 뿌리도록 사용하기 위해서는 CGI 모듈을 가져와 사용해야한다. 구글에 'python common gateway interface'라고 검색한 후 최상단의 docs.python.org/3/library/cgi.html로 들어가본다.

     

    페이지를 조금 내리면 Begin by writing import cgi라는 문구가 보인다. import cgi라고 선언한 후 CGI 모듈 사용이 가능하다.

     

    좀 더 내리면 다음과 같은 코드가 있다.

     

    form = cgi.FieldStorage()
    if "name" not in form or "addr" not in form:
        print("<H1>Error</H1>")
        print("Please fill in the name and addr fields.")
        return
    print("<p>name:", form["name"].value)
    print("<p>addr:", form["addr"].value)
    ...further form processing here...

    위의 예제 코드를 참고하여 index.py를 수정한다. 

     

    #!Python
    print("Content-Type: text/html")    # HTML is following
    print()
    import cgi
    form = cgi.FieldStorage()
    pageId = form["id"].value
    
    print('''<!doctype html>
    <html>
    <head>
      <title>WEB1 - Welcome</title>
      <meta charset="utf-8">
    </head>
    <body>
      <h1><a href="index.py?id=WEB">WEB</a></h1>
      <ol>
        <li><a href="index.py?id=HTML">HTML</a></li>
        <li><a href="index.py?id=CSS">CSS</a></li>
        <li><a href="index.py?id=JavaScript">JavaScript</a></li>
      </ol>
      <h2>{title}</h2>
      <p>The World Wide Web (abbreviated WWW or the Web) is an information space where documents and other web resources are identified by Uniform Resource Locators (URLs), interlinked by hypertext links, and can be accessed via the Internet.[1] English scientist Tim Berners-Lee invented the World Wide Web in 1989. He wrote the first web browser computer program in 1990 while employed at CERN in Switzerland.[2][3] The Web browser was released outside of CERN in 1991, first to other research institutions starting in January 1991 and to the general public on the Internet in August 1991.
      </p>
    </body>
    </html>
    '''.format(title=pageId))
    

     

    form = cgi.FieldStorage()를 통해 쿼리스트링의 데이터를 form변수에 담은 후, form["id"].value를 통해 id값을 pageId에 담았다. url을 클릭할 때마다 pageId가 동적으로 바뀔 것이다.

     

    여기서 앞에서 배운 포맷팅을 사용한다. 

    <h2>{title}</h2>
      <p>The World Wide Web (abbreviated WWW or the Web) is an information space where documents and other web resources are identified by Uniform Resource Locators (URLs), interlinked by hypertext links, and can be accessed via the Internet.[1] English scientist Tim Berners-Lee invented the World Wide Web in 1989. He wrote the first web browser computer program in 1990 while employed at CERN in Switzerland.[2][3] The Web browser was released outside of CERN in 1991, first to other research institutions starting in January 1991 and to the general public on the Internet in August 1991.
      </p>
    </body>
    </html>
    '''.format(title=pageId))
    

     

     코드의 일부인데 {title}이라는 곳에 값이 동적으로 들어간다. 맨 아래 format(title=pageId)선언을 통해 동적으로 변하는 pageIdtitle이라는 변수에 담기고 {title}이 결과적으로 변하게 된다.

     

    최종 결과화면은 다음과 같다.

     

    영상이 아니라 동적으로 클릭시 변하는 것을 보여주긴 어렵지만, URL의 id=JavaScript가 중간 서브타이틀 아래 제목으로 JavaScript로 변동된 것을 확인할 수 있다.

     

    반응형

    댓글