Til

Til 24.04.04 조별과제 넷플모봄게시판 만들기 (파비콘 추가, 알림팝업추가, 가상환경설정)

dini_dini 2024. 4. 4. 13:25

~~!!!!!항상 확인할것 ~~~~!!!!!

 

파일 폭파시키고 다시할땐

가상환경설정

 

-가상환경생성
python -m venv myenv
-가상환경 활성화
source myenv/Scripts/activate
-플라스크 패키지 설치
pip install Flask

-리퀘스트 설치

pip install requests <- s붙여야함

설치된것들 확인 

pip list

 

**폴더와 파일 형식

가위바위보/

├── app.py

├── templates/

│ └── index.html

── static/

  └── style.css

 

 

****

static/js/script.js

static/css/style.css

static/그림.png이런식으로 폴더를 나눠줘야함

 

html파일은 랜더 템플릿을 해야하므로

꼭 템플리츠 파일 안에 넣어주기~~~!!!!!

 

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

현재진행상황

-게시글 잘나옴

-게시글 등록, 수정, 삭제 됨

- 다른 조원이 진행중인 댓글 창 작업기다리는중

-또다른 조원이 진행중인 조아용 작업 기다리는중

 

오늘 진행상황

1,게시글 등록 알림팝업을 추가하였음
2.게시글 수정 저장 알림팝업 실패하였음 ㅠ
3.write.html 헤더부분에 "넷플모봄"누르면 홈으로 랜딩하는 하이퍼링크 추가하였음
4.업로드 이미지추가 하다가 실패하였음 ㅠㅠㅠㅠㅠㅠ

5. 파비콘을 추가하였음 -매우간단스

 

게시글 등록알람

 #기존코드[ ]
.then((response) => response.json())
    .then((data) => {
      console.log("Success:", data);
      window.location.href = "/"; // 성공 후 메인 페이지로 리다이렉트
    })
    .catch((error) => {
      console.error("Error:", error);
    });
}
==================


#수정본
.then((response) => {
    if (!response.ok) {
      throw new Error('Network response was not ok');
    }
    return response.json();
  })
  .then((data) => {
    console.log("Success:", data);
    alert("글이 성공적으로 제출되었습니다!"); // 성공 알림
    window.location.href = "/"; // 성공 후 메인 페이지로 리다이렉트
  })
  .catch((error) => {
    console.error("Error:", error);
    alert("오류가 발생했습니다. 다시 시도해주세요."); // 실패 알림
  });
}//게시글 등록 알림을 추가하였음

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

#게시글 수정
function updatePost(postId) {
  const title = document.getElementById("titleInput").value;
  const author = document.getElementById("authorInput").value;
  const category = document.getElementById("categorySelect").value;
  const content = document.getElementById("contentTextarea").value;

  fetch(`/posts/${postId}/update`, {
    method: 'POST',
    body: JSON.stringify({ title, author, category, content }),
    headers: {
      'Content-Type': 'application/json'
    }
  })
  .then(response => {
    if (response.ok) {
      window.location.href = `/posts/${postId}`; // Redirect to the updated post
    }
  })
  .catch(error => console.error('Error:', error));

===================
아래게시글 수정 저장버튼은 실패하였음

//게시글 수정
function updatePost(postId) {
  const title = document.getElementById("titleInput").value;
  const author = document.getElementById("authorInput").value;
  const category = document.getElementById("categorySelect").value;
  const content = document.getElementById("contentTextarea").value;

  fetch(`/posts/${postId}/update`, {
    method: 'POST',
    body: JSON.stringify({ title, author, category, content }),
    headers: {
      'Content-Type': 'application/json'
    }
  })
  .then(response => {
    if (response.ok) {
      window.location.href = `/posts/${postId}`; // Redirect to the updated post
    }
  })
  .catch(error => console.error('Error:', error));
}


#수정본 - 수정 저장 버튼 눌렀을때
function updatePost(postId) {
  const title = document.getElementById("title").value;
  const author = document.getElementById("author").value;
  const category = document.getElementById("category").value;
  const content = document.getElementById("content").value;

  fetch(`/posts/${postId}/update`, {
    method: 'POST',
    body: JSON.stringify({ title, author, category, content }),
    headers: {
      'Content-Type': 'application/json'
    }
  })
  .then(response => {
    if (!response.ok) {
      throw new Error('Network response was not ok');
    }
    return response.json();
  })
  .then(() => {
    alert("글이 성공적으로 수정되었습니다!"); // 성공 알림
    window.location.href = `/posts/${postId}`; // 수정된 게시글로 리다이렉트
  })
  .catch(error => {
    console.error('Error:', error);
    alert("오류가 발생했습니다. 다시 시도해주세요."); // 실패 알림
  });
} //여기까지 실패임

==============================
write.html 

 <!-- 헤더 -->
    <header class="container">
      <nav class="navbar navbar-expand-lg navbar-light bg-light">
        <a class="navbar-brand" href="{{ url_for('index') }}">
하이퍼링크 추가하였음

=========================
파비콘 추가 시도~~
->생각보다 매우 간단스
<link rel="icon" type="image/png" href=""/>


 

 

@app.route('/posts', methods=['POST'])
def create_post():
    data = request.json  # 클라이언트로부터 받은 JSON 데이터를 파싱
    new_post = Post(title=data['title'], content=data['content'])  # 새 게시글 객체 생성
    db.session.add(new_post)  # 데이터베이스 세션에 추가
    db.session.commit()  # 변경사항 커밋
    return jsonify({'id': new_post.id, 'title': new_post.title, 'content': new_post.content}), 201  # JSON 형식으로 응답

 

==>>>> # JSON 요청을 통해 게시글 생성 API

JSON 요청을 통해 게시글 생성 API"는 사용자 또는 클라이언트가 JSON 형식의 데이터를 포함하는 HTTP 요청을 보내서, 서버에서 새로운 게시글을 데이터베이스에 생성하고 그 결과를 다시 JSON 형식으로 응답하는 웹 API

  1. 클라이언트로부터 JSON 형식의 게시글 데이터(예: 제목, 내용 등)를 포함하는 POST 요청을 받음
  2. 요청된 데이터를 파싱하여 새 게시글 객체를 생성하고 데이터베이스에 저장
  3. 성공적으로 게시글이 생성되면, 생성된 게시글의 정보(예: ID, 제목, 내용 등)를 JSON 형식으로 클라이언트에 응답

 

===================================
게시글 아이디 자동생성 - 디비에서 각행을 고유하게 식별하게함

 

##게시글 고유 아이디 자동생성(/add_post 엔드포인트는 웹 애플리케이션에서 JSON 형식의 데이터를 받아 게시글을 데이터베이스에 추가하는 API 역할을 수행해야함)
#json 형태로 데이터를 받아 게시글을 생성하ㄹ것임
@app.route('/add_post', methods=['POST'])
def add_post():
    data = request.json
    title = data.get('title')
    content = data.get('content')
    # 새 Post 인스턴스 생성
    new_post = Post(title=title, content=content)
    # 데이터베이스 세션에 추가
    db.session.add(new_post)
    # 변경사항 커밋
    db.session.commit()
    # 새로운 포스트의 ID와 함께 응답
    return jsonify({'id': new_post.id, 'title': new_post.title, 'content': new_post.content}), 201

 

자동으로 생성되는 부분은 Flask와 SQLAlchemy의 기본 동작 덕분

 

id = db.Column(db.Integer, primary_key=True)


db.Integer는 필드의 데이터 타입을 정수형으로 설정하고, primary_key=True는 이 필드가 기본 키(primary key) 역할

기본 키는 데이터베이스 테이블에서 각 행(row)을 고유하게 식별하는 역할

 

sql알케미와 함께 사용되는 데이터베이스 시스템 (예를들면 에스큐엘 라이트) - 어지간 하면 기본키(프라이머리키)로 설정된 필드(표?db창들어가면 보이는 줄중 기본행)에서 자동으로 증가하는 속성을 제공

->첫번째항목 의 아이디 =1 , 두번째항목 = 2 이런식으로 번호가 붙음

 

new_post = Post(title=title, content=content)

db.session.add(new_post)

db.session.commit()

일케 커밋까지 해주면 자동아이디 생기고 저장까지 됨 - 각 게시글 식별할때 사용