본문 바로가기
Book+ACT/Skill up

Day2_OpenAI

by Qookoo 2025. 5. 28.
반응형

 

Html Part

 

Html  
Html
문법작성규칙
 
Html 태그모음  
Html 이미지삽입하기  
Html 표만들기  
Html 입력받기  
입력받기 분석  
Html 공간분할  
   

 

 

CSS 웹서식

CSS
기본작성문법
 
CSS 적용방법  
CSS 셀렉터 지정  
   
   
   
   
   

 

Flask Part1

 

from flask import Flask

app = Flask(__name__)

@app.route("/hello")
def hello():
    return "<h1> hello Flask ~~~~ !</h1>"

@app.route("/hello1")
def hello1():
    return "<h1> hello111 Flask ~~~~ !</h1>"

if __name__ == "__main__":
    app.run()
1. Flask 임포트 및 앱 생성
from flask import Flask : Flask 프레임워크를 불러옵니다.

app = Flask(__name__) : Flask 애플리케이션 객체를 만듭니다.

2. 라우트(route) 설정
@app.route("/hello") : /hello 주소로 접속하면 아래의 hello 함수가 실행됩니다.

def hello(): : 함수 정의

return "<h1> hello Flask ~~~~ !</h1>" : 브라우저에 HTML 형태로 메시지를 출력합니다.

@app.route("/hello1") : /hello1 주소로 접속하면 hello1 함수가 실행됩니다.

def hello1():

return "<h1> hello111 Flask ~~~~ !</h1>" : 다른 메시지를 출력합니다.

3. 앱 실행
if __name__ == "__main__": app.run() : 이 파일을 직접 실행할 때 Flask 개발 서버를 실행합니다.
from flask import Flask

app = Flask(__name__)

@app.route("/greet/<username>")
def greet(username):
    return f"<h1>Hello, {username}! Welcome to Flask :)</h1>"

if __name__ == "__main__":
    app.run(debug=True)
@app.route("/greet/<username>")

/greet/이름 형태로 접속하면, URL의 <username> 부분이 함수의 인자로 전달됩니다.

예를 들어, http://localhost:5000/greet/홍길동으로 접속하면,
greet("홍길동")이 호출되어
<h1>Hello, 홍길동! Welcome to Flask :)</h1>
라는 메시지가 브라우저에 표시됩니다.

f"<h1>Hello, {username}! Welcome to Flask :)</h1>"

f-string을 사용해 동적으로 사용자 이름을 HTML로 출력합니다.

app.run(debug=True)

디버그 모드를 켜서 개발 중 오류를 쉽게 확인할 수 있습니다.
 
 
   
   
   
   
   
from operator import length_hint

from flask import Flask, request, render_template

app = Flask(__name__)

@app.route('/')
def hello():
    return render_template('index4.html')

@app.route('/<username>')
def post_page(username):
    length = len(username)
    return render_template('index4.html',name=username, leng=length)

if __name__ == '__main__':
    app.run()

 

 

1. Flask 임포트 및 앱 생성

  • Flask, request, render_template를 가져옵니다.
  • Flask 애플리케이션 인스턴스를 생성합니다.

2. 라우트 정의

/ (루트)

  • @app.route('/')
  • hello() 함수가 실행되어 index4.html 템플릿을 렌더링합니다.
  • 템플릿에 별도의 변수 전달 없이 단순히 페이지를 보여줍니다.

/<username>

  • 예: /hong, /alice 등 사용자가 입력한 경로가 username으로 전달됩니다.
  • post_page(username) 함수가 실행되어,
    • length = len(username)로 username의 길이를 계산(하지만 현재 코드에서는 사용하지 않음)
    • render_template('index4.html', name=username)
       name이라는 변수에 username 값을 담아 템플릿에 전달합니다.

3. 앱 실행

  • if __name__ == '__main__': app.run()
    서버를 실행합니다.

 

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Input Test</title>
</head>
<body>
    <h2>구구단 외우는 테스트</h2>
    <form action="{{ url_for('calculate') }}" method="post">
        <input type="number" name="num" placeholder="숫자를 입력하세요" required>
        <input type="submit" value="전송">
    </form>
    <h2>{{ num }}단 외우는 테스트</h2>
    {% if num %}
        <p>입력된 숫자: {{ num }}</p>
        <ul>
        {% for i in range(1, 10) %}
            <li>{{ num }} × {{ i }} = {{ num|int * i }}</li>
        {% endfor %}
        </ul>
    {% endif %}
</body>
</html>
from flask import Flask, request, render_template, url_for, redirect

app = Flask(__name__)

@app.route('/')
@app.route('/<int:num>')
def inputTest(num=None):
    return render_template('index5.html', num=num)

@app.route('/calculate', methods=['POST'])
def calculate():
    if request.method == 'POST':
        temp = request.form['num']
    else:
        temp = None
    return redirect(url_for('inputTest', num=temp))

if __name__ == '__main__':
    app.run()
  • {% for i in range(1, 10) %}
    Jinja2 템플릿 문법으로 1부터 9까지 반복합니다.
  • {{ num|int * i }}
    num이 문자열로 전달될 수 있으므로, |int 필터로 정수 변환 후 곱셈을 수행합니다.
  • 결과는 <ul> 태그 안에 리스트로 출력됩니다.

주요 수정점

  • if request.method == 'POST':로 수정
  • redirect(url_for('inputTest', num=temp))에서 num에 temp값을 넘김
  • 불필요한 import 제거

3. 동작 방식

  1. GET 요청
    • / 또는 /숫자로 접속하면,
      index5.html이 렌더링되고 num 값이 템플릿에 전달됨
  2. POST 요청
    • /calculate로 POST 요청을 보내면
      • form에서 'num' 값을 받아옴
      • /num 경로로 리다이렉트됨

 

 

MongoDB

from pymongo import MongoClient

# MongoDB에 연결 (로컬 서버 기준)
connection = MongoClient('localhost', 27017)
print(connection)

# sample 데이터베이스 선택
db = connection.sample
print(db)

# user 컬렉션 선택
collection = db.user
print(collection)

# 저장할 document 생성
post = [
{
    'name': 'user01',
    'Timeline': 'i sometimes cry',
    'follow': 11
},
{
    'name': 'user02',
    'Timeline': 'i super happy',
    'follow': 22
},
{
    'name': 'user03',
    'Timeline': 'i grey',
    'follow': 33
},
{
    'name': 'user04',
    'Timeline': 'i super super happy',
    'follow': 44
}
]

# MongoDB에 데이터 삽입
result = collection.insert_many(post)
print(result)

동작 방식

  1. MongoDB 연결
    • MongoClient('localhost', 27017)로 로컬 MongoDB 서버에 연결합니다.
    • MongoDB가 실행 중이어야 합니다.
  2. 데이터베이스 및 컬렉션 선택
    • sample 데이터베이스와 user 컬렉션을 선택합니다.
    • 존재하지 않으면 자동으로 생성됩니다.
  3. 여러 개의 document 생성
    • 4명의 사용자 정보를 담은 리스트(post)를 만듭니다.
  4. 데이터 삽입
    • insert_many(post)로 리스트의 모든 document를 한 번에 삽입합니다.
    • 반환값(result)은 InsertManyResult 객체입니다.
  5. 결과 출력
    • print(result)를 하면, 삽입 결과 객체가 출력됩니다.
    • 실제로 삽입된 각 document의 _id 값을 확인하려면
      print(result.inserted_ids)
      를 사용하면 됩니다
반응형