inflearn logo
강의

Khóa học

Chia sẻ kiến thức

Xây dựng trang web thực tế bằng Python của Tiến sĩ Nam

Tạo trang đăng ký thành viên

버전 문제도 수정했는데 결과가 안나옵니다.

255

bummy

2 câu hỏi đã được viết

0

{% with messages = get_flashed_messages() %} {% if messages %} <script> alert(" {{messages[-1]}}"); </script> {% endif %} {% endwith %} <table> <form name="form" action="/join" method="POST"> <thead> <caption>회원가입</caption> </thead> <tbody> <tr> <td>이름</td> <td><input type="text" name="name"></td> </tr> <tr> <td>이메일</td> <td><input type="text" name="email"></td> </tr> <tr> <td>비번</td> <td><input type="password" name="pass"></td> </tr> <tr> <td>비번확인</td> <td><input type="password" name="pass2"></td> </tr> <tr> <td colspan="2"><input type="submit" value="가입하기"></td> </tr> </tbody> </form> </table>

from flask import Flask
from flask import request,redirect,url_for
from flask import render_template, abort
from flask_pymongo import PyMongo
from datetime import datetime
from flask import flash
from bson.objectid import ObjectId
import time
import math


app = Flask(__name__)
app.config["MONGO_URI"]="mongodb://localhost:27017/myweb"
mongo = PyMongo(app)

@app.template_filter("formatdatetime")
def format_datetime(value):
    if value is None:
        return ""
    now_timestemp = time.time()
    offset = datetime.fromtimestamp(now_timestemp)-datetime.utcfromtimestamp(now_timestemp)   
    value = datetime.fromtimestamp((int(value)/1000))+offset
    return value.strftime('%Y-%m-%d %H:%M:%S')

@app.route("/list")
def lists():
    # 페이지 값(값이 없는 경우 기본값은 1)
    page = request.args.get("page",1,type=int)
    #한페이지당 몇개의 개시물을 출력할지
    limit = request.args.get("limit",5,type=int)

    search = request.args.get("search",-1,type=int)
    keyword = request.args.get("keyword",type=str)

    #최종적으로 완성된 쿼리를 만들 변수
    query = {}
    # 검색아 상태를 추가할 리스트 변수
    search_list=[]

    if search ==0:
        search_list.append({"title":{"$regex":keyword}})
    elif search == 1:
        search_list.append({"contents":{"regex":keyword}})
    elif search == 2:
        search_list.append({"title":{"$regex":keyword}})
        search_list.append({"contents":{"$regex":keyword}})

    elif search ==3:
         search_list.append({"name":{"$regex":keyword}})
    # 검색 대상이 한개라고 존재할 겨우 query 변수에 $or 리스트를 쿼리 합니다.
    if len(search_list)>0:
        query={"$or":search_list}

    print(query)

    board = mongo.db.board
    datas = board.find(query).skip((page - 1)*limit).limit(limit)

    # 개시물에 총 갯수(수정됨)
    tot_count = board.count_documents(query)
    #  마지작 페이지의 수를 구합니다.
    last_page_num = math.ceil(tot_count / limit)


    # 페이지 블럭을 5개씩 표기
    block_size = 5
    # 현재블럭의 위치
    block_num = int((page - 1)/block_size)
    # 블럭의 시작 위치
    block_start = int((block_size * block_num) +1)
    # 블럭의 끝 위치
    block_last = math.ceil(block_start + (block_size - 1))

    return render_template(
        "list.html",
        datas=list(datas),
        limit=limit,
        page=page,
        block_start=block_start,
        block_last=block_last,
        last_page_num=last_page_num,
        search=search,
        keyword=keyword)


@app.route("/view/<idx>")
def board_view(idx):
    # idx = request.args.get("idx") 펜시유알엘
    if idx is not None:
        page = request.args.get("page")
        search = request.args.get("search")
        keyword = request.args.get("keyword")
        board = mongo.db.board
        data = board.find_one({"_id":ObjectId(idx)})

        if data is not None:
            result={
                "id":data.get("_id"),
                "name":data.get("name"),
                "title":data.get("title"),
                "contents":data.get("contents"),
                "pubdate":data.get("pubdate"),
                "view":data.get("view")
            }
            print(id)
            return render_template("view.html",result=result, page=page, search=search, keyword=keyword)
    return abort(404)


@app.route("/write",methods=['GET','POST'])
def board_write():
    if request.method=="POST":
        name = request.form.get("name")
        title = request.form.get("title")
        contents = request.form.get("contents")
        print(name,title,contents)

        current_utc_time = round(datetime.utcnow().timestamp() *1000)
        board = mongo.db.board
        post={
            "name":name,
            "title": title,
            "contents":contents,
            "pubdate":current_utc_time,
            "view":0,
        }

        x = board.insert_one(post)
        print(x.inserted_id)
        return redirect(url_for("board_view",idx=x.inserted_id))
    else:
        return render_template("write.html")

@app.route("/join",methods=["POST","GET"])
def menber_join():
    if request.method =="POST":
        name = request.form.get("name",type=str)
        email = request.form.get("email",type=str)
        pass1 = request.form.get("pass",type=str)
        pass2 = request.form.get("pass2",type=str)

        if name is None or email is None or pass1 is None or pass2 is None:
            flash ("입력되지 않은 값이 있습니다.")
            return render_template("join.html")
        
        if pass1 != pass2:
            flash("비밀번호가 일치 하지않습니다.")
            return render_template("join.html")

        members = mongo.db.menbers
        # 이부분 버전 수정됨
        cnt = members.count_documents({"email":email}) 
        if cnt > 0:
            flash("중복된 이메일 주소입니다.")
            return render_template("join.html")

        current_utc_time = round(datetime.utcnow().timestamp()*1000)
        post ={
            'name':name,
            'email':email,
            'pass':pass1,
            "joindate":current_utc_time,
            "logtime":"",
            "logincount":0,
        }
        members.insert_one(post) 

        return ""
    else:
        return render_template("join.html")


if __name__ == "__main__":
    app.run(host="0.0.0.0",debug=True,port=5000)

 

python

Câu trả lời 1

0

communityai8509

안녕하세요, 인프런 AI 인턴이에요.

작성해주신 코드를 보면 Flask와 MongoDB를 사용하여 회원가입 페이지를 구현한 것 같습니다.
하지만 어떤 문제가 발생하는지 정확히 설명해주시지 않아서 원인을 파악하기 어렵습니다.
문제가 발생하는 부분과 발생하는 현상에 대해 좀 더 자세한 정보를 알려주세요.
또한, 코드에서 사용하는 버전 관련 내용도 함께 알려주시면 도움이 될 것 같아요.

iis 접속후 자동으로 로그인 창이 나오도록 설정이 기능한가요?

0

63

2

리스트 이동 시 창 에러 발생

0

73

1

배포후 회원 등록 후 로그인 에러...

0

72

2

내부 서버 오류

0

65

2

app.config["MONGO_URI"] = "mongodb://localhost:27017/pm_db"

0

53

2

DB 검색하면 데이터가 없습니다. 라고 나와요. 5시간을 찾아봐도 모르겠어서 문의드려봅니다.

0

44

1

몽고db studio3T를 깔았는데

0

56

2

flake8과 linter

0

72

3

500이 뜹니다.

0

57

2

첨부파일 삭제

0

66

2

검색기능 질문

0

61

2

google.py

0

66

2

Studio 3T에 DB insert가 되지 않는 문제를 해결하지 못하고 있습니다 ㅠ

0

81

3

혹시 전체 코드 공개되어 있나요?

0

95

1

join.html 의 form 태그값 을 member_join() 에서 처리못함.

0

102

1

google.py 몽고db 샘플데이터 만들기

0

99

2

flake8 설치 이후 명령팔레트에서 linter가 안보입니다.

0

236

2

파이썬으로 만들어서 웹호스팅에 올릴경우

0

303

1

현재 구글검색 무한스크롤변경 문의합니다

0

295

1

몽고디비아틀라스로 추가 공부해서 올립니다.

0

216

1

IIS 500.19에러

0

652

2

데이터베이스 저장관련 질문입니다.

0

266

1

test가 생기지 않습니다.

0

501

3

로그아웃했다가 다시 로그인하면 다음과 같은 오류메세지가 뜨는데요

0

400

1