Skip to main content

Command Palette

Search for a command to run...

[TIL] Intro to Backend, using Flask

03/02/23

Updated
[TIL] Intro to Backend, using Flask

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 venv

  • source venv/Scripts/activate

Building Server with Flask

  • Import Flask framework: pip install flask

  • Base 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 templates folder. This folder is to store all HTML files

    • import render_template

        from 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)
      
  • GET and POST methods

    • GET: usually to READ data

      • E.g.) reading movie lists & sending data through url?key=value
    • 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 request and jsonify

        # 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!'})
    

Today I Learned

Part 1 of 50

Today I Learned!