Flask web dev

Tidas·2022년 1월 8일
0
post-thumbnail

setup for python

pre-install and setup: python3 and venv

pip install flask
pip install beautifulsoup4
pip install dnspython
pip install pymongo
pip install requests

import package

from flask import Flask, render_template, request, jsonify
import requests
from bs4 import BeautifulSoup
from pymongo import MongoClient

mongo db setup

pre-setup cloud mongodb

client = MongoClient('mongodb+srv://<DB>:<password>@cluster0.qcejh.mongodb.net/<collection name>?retryWrites=true&w=majority')
db = client.<collection name>

main func

app = Flask(__name__)
if __name__ == '__main__':
    app.run(port=5000, debug=True)

route index page

@app.route('/')
def home():
    return render_template('index.html')

route movie

@app.route("/movie", methods=["GET"])
def movie_get():
    movie_list = list(db.movies.find({}, {'_id': False}))
    return jsonify({'movies': movie_list})

Add movie info

@app.route("/movie", methods=["POST"])
def movie_post():
    url_receive = request.form['url_give']
    star_receive = request.form['star_give']
    comment_receive = request.form['comment_give']

    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64)AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.86 Safari/537.36'}
    data = requests.get(url_receive, headers=headers)

    soup = BeautifulSoup(data.text, 'html.parser')

    title = soup.select_one('meta[property="og:title"]')['content']
    image = soup.select_one('meta[property="og:image"]')['content']
    desc = soup.select_one('meta[property="og:description"]')['content']

    doc = {
        'title': title,
        'image': image,
        'desc': desc,
        'star': star_receive,
        'comment': comment_receive
    }
    db.movies.insert_one(doc)

    return jsonify({'msg': 'done saved!'})

index page setup

<!doctype html>
<html lang="en">

<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet"
          integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.bundle.min.js"
            integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM"
            crossorigin="anonymous"></script>

    <title>MovieStar</title>

    <link href="https://fonts.googleapis.com/css2?family=Gowun+Dodum&display=swap" rel="stylesheet">

    <style>
        * {
            font-family: 'Gowun Dodum', sans-serif;
        }

        .mytitle {
            width: 100%;
            height: 250px;

            background-image: linear-gradient(0deg, rgba(0, 0, 0, 0.5), rgba(0, 0, 0, 0.5)), url('https://movie-phinf.pstatic.net/20210715_95/1626338192428gTnJl_JPEG/movie_image.jpg');
            background-position: center;
            background-size: cover;

            color: white;

            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
        }

        .mytitle > button {
            width: 200px;
            height: 50px;

            background-color: transparent;
            color: white;

            border-radius: 50px;
            border: 1px solid white;

            margin-top: 10px;
        }

        .mytitle > button:hover {
            border: 2px solid white;
        }

        .mycomment {
            color: gray;
        }

        .mycards {
            margin: 20px auto 0px auto;
            width: 95%;
            max-width: 1200px;
        }

        .mypost {
            width: 95%;
            max-width: 500px;
            margin: 20px auto 0px auto;
            padding: 20px;
            box-shadow: 0px 0px 3px 0px gray;

            display: none;
        }

        .mybtns {
            display: flex;
            flex-direction: row;
            align-items: center;
            justify-content: center;

            margin-top: 20px;
        }

        .mybtns > button {
            margin-right: 10px;
        }
    </style>
    </head>
    <body>
<div class="mytitle">
    <h1>My Favorite movie</h1>
    <button onclick="open_box()">recording movie</button>
</div>
<div class="mypost" id="post-box">
    <div class="form-floating mb-3">
        <input id="url" type="email" class="form-control" placeholder="name@example.com">
        <label>naver movie url</label>
    </div>
    <div class="input-group mb-3">
        <label class="input-group-text" for="inputGroupSelect01">star</label>
        <select class="form-select" id="star">
            <option selected>-- select --</option>
            <option value="1"></option>
            <option value="2">⭐⭐</option>
            <option value="3">⭐⭐⭐</option>
            <option value="4">⭐⭐⭐⭐</option>
            <option value="5">⭐⭐⭐⭐⭐</option>
        </select>
    </div>
    <div class="form-floating">
        <textarea id="comment" class="form-control" placeholder="Leave a comment here"></textarea>
        <label for="floatingTextarea2">comment</label>
    </div>
    <div class="mybtns">
        <button onclick="posting()" type="button" class="btn btn-dark">Add</button>
        <button onclick="close_box()" type="button" class="btn btn-outline-dark">Close</button>
    </div>
</div>
<div class="mycards">
    <div class="row row-cols-1 row-cols-md-4 g-4" id="cards-box">

    </div>
</div>
</body>

dev javascript func

<script>
        $(document).ready(function () {
            listing();
        });

        function listing() {
            $.ajax({
                type: 'GET',
                url: '/movie',
                data: {},
                success: function (response) {
                    let rows = response['movies']
                    for (let i = 0; i < rows.length; i++) {
                        let image = rows[i]['image']
                        let title = rows[i]['title']
                        let desc = rows[i]['desc']
                        let comment = rows[i]['comment']
                        let star = rows[i]['star']
                        let star_image = '⭐'.repeat(star)

                        let temp = `
                        <div class="col">
                            <div class="card h-100">
                                <img src="${image}"
                                     class="card-img-top">
                                <div class="card-body">
                                    <h5 class="card-title">${title}</h5>
                                    <p class="card-text">${desc}</p>
                                    <p>${star_image}</p>
                                    <p class="mycomment">${comment}</p>
                                </div>
                            </div>
                        </div>
                        `
                        $('#cards-box').append(temp)
                    }
                }
            })
        }

        function posting() {
            let url = $('#url').val()
            let star = $('#star').val()
            let comment = $('#comment').val()

            $.ajax({
                type: 'POST',
                url: '/movie',
                data: {
                    url_give: url, star_give: star, comment_give: comment
                },
                success: function (response) {
                    alert(response['msg'])
                    window.location.reload()
                }
            });
        }

        function open_box() {
            $('#post-box').show()
        }

        function close_box() {
            $('#post-box').hide()
        }
    </script>

1개의 댓글

comment-user-thumbnail
2024년 2월 13일

With the excitement of an intrepid explorer embarking on a daring expedition, I embarked on a cinematic voyage through a vast sea of films, eager to discover hidden treasures and untold stories. Tonight's movie promised an epic tale of courage and sacrifice, and I eagerly awaited the emotional journey that lay ahead. With each unfolding scene, I found https://kinogo-by.online/ myself immersed in the rich tapestry of the narrative, captivated by the depth of human emotion on display. From triumphant victories to heart-wrenching defeats, I marveled at the resilience and fortitude of the human spirit. In those poignant moments, I felt a profound connection to the characters, as if their journey mirrored my own.

답글 달기