[TIL] Intro to Backend, using Flask
03/02/23
![[TIL] Intro to Backend, using Flask](/_next/image?url=https%3A%2F%2Fcdn.hashnode.com%2Fres%2Fhashnode%2Fimage%2Fupload%2Fv1677622899799%2Ff71e6cfd-b50b-488e-a778-2f9cc02dfaa3.png&w=3840&q=75)
Today, I learned how to use Flask to build a local web server and connect the front-end to the back-end. I implemented two small projects using HTML, CSS, JS, and jQuery for the front-end and Python and Flask for the back-end. Through this, I gained an understanding of how to pass data between them using the GET and POST methods.
Activate Python Virtual Environment
python -m venv venvsource venv/Scripts/activate
Building Server with Flask
Import Flask framework:
pip install flaskBase format:
from flask import Flask app = Flask(__name__) @app.route('/') def home(): return 'This is Home!' @app.route('/mypage') def mypage(): return '<button>Button<button>' if __name__ == '__main__': app.run('0.0.0.0',port=5000,debug=True)How to connect to Front-end
Create
templatesfolder. This folder is to store all HTML files
import
render_templatefrom flask import Flask, render_template app = Flask(__name__) @app.route('/') def home(): return 'This is Home!' @app.route('/mypage') def mypage(): return render_template('index.html') # here is html file we want to connect to if __name__ == '__main__': app.run('0.0.0.0',port=5000,debug=True)
GETandPOSTmethodsGET: usually to READ data- E.g.) reading movie lists & sending data through
url?key=value
- E.g.) reading movie lists & sending data through
POST: to CREATE, UPDATE, and DELETE data- E.g.) Signing up, changing my password, or deleting the account & sending data through invisible HTML
How to make API in Flask
import
requestandjsonify# Back-end from flask import Flask, render_template, request, jsonify app = Flask(__name__) @app.route('/') def home(): return render_template('index.html') @app.route('/test', methods=['GET']) def test_get(): title_receive = request.args.get('title_give') print(title_receive) return jsonify({'result':'success', 'msg': 'This request is GET!'}) @app.route('/test', methods=['POST']) def test_post(): title_receive = request.form['title_give'] print(title_receive) return jsonify({'result':'success', 'msg': 'This request is POST!'}) # send this dict to Front-end if __name__ == '__main__': app.run('0.0.0.0',port=5000,debug=True)<!-- Front-end: index.html --> <script> function hey() { fetch("/test") .then((res) => res.json()) .then((data) => { console.log(data); }); let formData = new FormData(); formData.append("title_give", "Avengers"); fetch("/test", { method: "POST", body: formData }) .then((res) => res.json()) .then((data) => { console.log(data); }); } </script>
Practice 1: Buying Mars

GET
<script> $(document).ready(function () { show_order(); }); function show_order() { fetch("/mars") .then((res) => res.json()) .then((data) => { $("#order-box").empty(); let results = data["result"]; results.forEach((a) => { let name = a["name"]; let address = a["address"]; let size = a["size"]; let temp_html = `<tr> <td>${name}</td> <td>${address}</td> <td>${size}</td> </tr>`; $("#order-box").append(temp_html); }); }); } </script># GET API @app.route("/mars", methods=["GET"]) def mars_get(): mars_orders = list(db.mars.find({}, {'_id': False})) return jsonify({'result': mars_orders})POST API
<script> function save_order() { let name = $("#name").val(); let address = $("#address").val(); let size = $("#size").val(); let formData = new FormData(); formData.append("name_give", name); formData.append("address_give", address); formData.append("size_give", size); fetch("/mars", { method: "POST", body: formData }) .then((res) => res.json()) .then((data) => { alert(data["msg"]); window.location.reload(); }); } </script># POST API @app.route("/mars", methods=["POST"]) def mars_post(): name_receive = request.form['name_give'] address_receive = request.form['address_give'] size_receive = request.form['size_give'] order_info = { 'name': name_receive, 'address': address_receive, "size": size_receive } db.mars.insert_one(order_info) return jsonify({'msg':'Order successfully saved'})Reload the page after POST is completed
:
window.location.reload();Begin function right after the page is refreshed
:
$(document).ready(function () { contents });
Practice 2: Movie List

More about Python Crawling
Using meta tag
og_image = soup.select_one('meta[property="og:image"]')['content'] og_title = soup.select_one('meta[property="og:title"]')['content'] og_description = soup.select_one('meta[property="og:description"]')['content'] print(og_image,og_title,og_description)
GET
<script> $(document).ready(function () { weather(); listing(); }); function weather() { fetch("http://spartacodingclub.shop/sparta_api/weather/seoul") .then((res) => res.json()) .then((data) => { let temp = data["temp"]; $("#temp").text(temp); }); } function listing() { fetch("/movie") .then((res) => res.json()) .then((data) => { let rows = data["msg"]; $("#cards").empty(); rows.forEach((a) => { let title = a["title"]; let description = a["description"]; let comment = a["comment"]; let image = a["image"]; let star = a["star"]; let star_repeat = "⭐".repeat(star); let temp_html = `<div class="col"> <div class="card h-100"> <img src="${image}" class="card-img-top" alt="..." /> <div class="card-body"> <h5 class="card-title">${title}</h5> <p class="card-text">${description}</p> <p>${star_repeat}</p> <p class="mycomment">${comment}</p> </div> </div> </div>`; $("#cards").append(temp_html); }); }); } </script># GET API @app.route("/movie", methods=["GET"]) def movie_get(): movies_info = list(db.movies.find({}, {'_id': False})) return jsonify({'msg':movies_info})POST
<script> function posting() { let url = $("#url").val(); let comment = $("#comment").val(); let star = $("#star").val(); let formData = new FormData(); formData.append("url_give", url); formData.append("comment_give", comment); formData.append("star_give", star); fetch("/movie", { method: "POST", body: formData }) .then((res) => res.json()) .then((data) => { alert(data["msg"]); window.location.reload(); }); } </script># POST API @app.route("/movie", methods=["POST"]) def movie_post(): url_receive = request.form['url_give'] comment_receive = request.form['comment_give'] star_receive = request.form['star_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') ogimage = soup.select_one('meta[property="og:image"]')['content'] ogtitle = soup.select_one('meta[property="og:title"]')['content'] ogdesc = soup.select_one('meta[property="og:description"]')['content'] doc = { 'image': ogimage, 'title': ogtitle, 'description': ogdesc, 'comment': comment_receive, 'star': star_receive } db.movies.insert_one(doc) return jsonify({'msg':'Movie saved!'})
![[코테] 그리디 문제 - 무지의 먹방 라이브](/_next/image?url=https%3A%2F%2Fcdn.hashnode.com%2Fres%2Fhashnode%2Fimage%2Fupload%2Fv1712215455263%2F1ac1f35a-8862-4e42-8d0c-e2bea01e04c0.png&w=3840&q=75)
![[코테] Bfs 토마토](/_next/image?url=https%3A%2F%2Fcdn.hashnode.com%2Fres%2Fhashnode%2Fimage%2Fupload%2Fv1709032619170%2F70056896-c857-444b-9c99-45bfcb466806.png&w=3840&q=75)
![[코테] Dfs 문제 유형 - 그래프 내에서 구분하여 카운트 하기](/_next/image?url=https%3A%2F%2Fcdn.hashnode.com%2Fres%2Fhashnode%2Fimage%2Fupload%2Fv1709019361383%2Fb0585d72-c808-4169-83a9-2724f312e927.png&w=3840&q=75)
![[코테] DFS vs BFS](/_next/image?url=https%3A%2F%2Fcdn.hashnode.com%2Fres%2Fhashnode%2Fimage%2Fupload%2Fv1708971211123%2F71f9386c-6a62-43b2-a602-4d084c24d6cf.png&w=3840&q=75)
![[코테] 여행경로](/_next/image?url=https%3A%2F%2Fcdn.hashnode.com%2Fres%2Fhashnode%2Fimage%2Fupload%2Fv1708971251412%2F27ce72ed-8ee7-4d13-a02f-ff4bbe50c4be.png&w=3840&q=75)