• 카테고리

    질문 & 답변
  • 세부 분야

    풀스택

  • 해결 여부

    미해결

게속 오류떠요

20.09.11 10:18 작성 조회수 197

1

고쳐도 수용없어요

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

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

# 메인
@app.route("/")  
def Main(): 
    Myyy =  """
        <meta http-equiv="refresh" content="0;url=/list">
    """
    # return """<meta http-equiv="refresh" content="0;url=/write">"""
    return Myyy


@app.template_filter("formatdatetime"# 시간
def format_datetime(value):
    if value is None:
        return " "

    now_timestamo = time.time()
    offset = datetime.fromtimestamp(now_timestamo) - datetime.utcfromtimestamp(now_timestamo)
    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"1type=int)
    # 한페이지당 몇개의 게시물을 출력할지 
    limit = request.args.get("limit"7type=int# 기본값은 10개이다 수정가능 

    search = request.args.get("search", - 1type=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}})


    # 검색 대상이 1개하도 존재할 경우 query 변수 $or 리스트 쿼리 한다
    if len(search_list) > 0:
        query = {"$or": search_list}

    # {"$and":[
    #     {"title": {"$regex": "파이썬"}},
    #     {"title": {"$regex": "파이썬"}},
    #     {"title": {"$regex": "안드로아드"}},
    # ]}   
    print(query)


    board = mongo.db.board  # DB가져오기
    datas = board.find(query).skip((page - 1) * limit).limit(limit)

    # 게시물의 총 갯수
    tot_count = board.find(query).count()
    # 마지막 페이지의 수를 구합니다
    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=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:
        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"),
            } 

            return render_template("view.html"result=result)
        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")


if __name__ == "__main__":
    app.run(host="0.0.0.0"debug=Trueport=8501)

html도 고쳐도 여전히 오류떠요

<script>
    function search() {
        var val_search = document.getElementById("search").value;
        var val_keyword = document.getElementById("keyword").value;

        if(val_search == "" || val_keyword == "") {
            return false;
        } else {
            self.location.href = "{{url_for('lists')}}?search=" + val_search + "&keyword=" + val_keyword;
        }
    }
</script>

{% if datas.count() > 0 %}
<title>목록</title>
<table>
    <thead>
        <tr>
            <td>번호</td>
            <td>제목</td>
            <td>이름</td>
            <td>날짜</td>
            <td>조회수</td>
        </tr>
    </thead>
    <tbody>
        <!--반복되는 구간-->
        {% for data in datas %}
        <tr>
            <td>{{loop.index + ((page - 1) * limit)}}</td>  <!--게시물 번호-->
            <td><a href="{{url_for('board_view', idx=data._id, page=page, search=search, keyword=keyword)}}">{{data.title}}</a></td>
            <td>{{data.name}}</td>
            <td>{{data.pubdate | formatdatetime}}</td>
            <td>{{data.view}}</td>
            <!-- <td>{{data.title}}</td>
            <td>{{data.title}}</td> -->
        </tr>
        {% endfor %}
        <!--반복되는 구간 끝-->
    </tbody>
</table>
{% if block_start - 1 > 0 %}
    <a href="{{url_for('lists', page=block_start - 1, search=search, keyword=keyword)}}">[이전]</a>
{% endif %}

{% for i in range(block_start, block_last + 1) %}
    {% if i > last_page %}
        <!-- {{ i }} -->
    {% else %}
        {% if i == page %}
            <b>{{i}}</b>
        {% else %}
            <a href="{{url_for('lists', page=i, search=search, keyword=keyword)}}">{{ i }}</a>
        {% endif %}
    {% endif %}
{% endfor %}

{% if block_last < last_page %}
    <a href="{{url_for('lists', page=block_last + 1, search=search, keyword=keyword)}}">[다음]</a>
{% endif %}

<select name="search" id="search">
    <option value="">검색대상</option>
    <option value="0">제목</option>
    <option value="1">내용</option>
    <option value="2">제목+내용</option>
    <option value="3">작성자</option>
</select>
<input type="text" name="keyword" id="keyword" >
<input type="button" value="검색" onclick="search()">
{% else %}
<h3>테이터가 없습니다</h3>
{% endif %}

답변 1

답변을 작성해보세요.

0

올려주신 코드랑 보여주신 오류 내용이 전혀 다른듯 합니다. 일단 올려주신 코드에서는 파이썬에서는 last_page_num 라고 변수를 사용하고 html 페이지에서는 last_page 라는 변수로 사용하셔서 문제가 생긴부분이 있습니다. 일단 올려주신 코드를 그대로 복사붙혀넣기 해서 이 부분만 수정했더니 정상적으로 실행되었습니다.