python) 조건에 반응하는 웹 애플리케이션 만들기

"조건에 반응하는 웹 애플리케이션 만들기"

#!/usr/local/bin/python3
print("Content-Type: text/html")
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">WEB</a></h1>
  <ol>
    <li><a href="index.py?id=HTML">HTML</a></li>
    <li><a href="index.py?id=CSS"></a>CSS</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))

위와 같은 코드를 갖는 웹 애플리케이션에서
href 값을 가진 WEB, HTML, CSS, JavaScript 를 각각 클릭하면

id값이 있는 HTML, CSS, JavaScript 는
?id=ㅇㅇ 의 주소를 갖는 웹페이지가 출력되지만
id값이 없는 WEB 은 빈페이지가 출력된다.


이를 아래와 같이 if 조건문을 통해
id 값이 있을때의 조건과 없을 때의 조건에 따라
각각의 페이지가 출력되도록 만들 수 있다.

if "id" in form:
  변수 = form["id"].value
else:
  변수 = "보여질 문구"
#!/usr/local/bin/python3
print("Content-Type: text/html")
print()

import cgi
form = cgi.FieldStorage()

if "id" in form:
  pageId = form["id"].value
else:
  pageId = "welcome"

print('''<!doctype html>
<html>
<head>
  <title>WEB1 - Welcome</title>
  <meta charset="utf-8">
</head>
<body>
  <h1><a href="index.py">WEB</a></h1>
  <ol>
    <li><a href="index.py?id=HTML">HTML</a></li>
    <li><a href="index.py?id=CSS"></a>CSS</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))

이제 id값이 없는 WEB 을 클릭하면,
글의 제목이 welcome 이라 적힌 웹페이가 출력되고

id값이 있는 HTML, CSS, JavaScript 를 클릭하면
전과 같이 id값을 글의 제목으로 하는 웹페이지가 출력된다.




[출처] 생활코딩 WEB2 - Python
https://opentutorials.org/module/3357

좋은 웹페이지 즐겨찾기