[パブリックトレーニング-Phythonベース]データベースをフラスコアプリケーションにバインド

19110 ワード

1.勉強の内容


① SQLite

  • で生成されたデータベースを開きます(CLIプログラムの実行時にデータベースを選択します).
  • 生成された
  • データベース(CLIプログラムを実行してデータベースを選択)
  • を開く.
  • データベースがない場合は、
  • 表モードの確認
  • ②Python内蔵SQLite API

  • https://docs.python.org/ko/3/library/sqlite3.html
  • Read
  • Create
  • ③Glitchコードを埋め込む方法

  • Settings
  • Copy Embed Code
  • Apply to Code
  • ④授業中に作成したコード

    from flask import Flask, request, redirect
    import sqlite3
    
    app = Flask(__name__)
    
    topics = [
      {"id":1, "title":"html", "body":"html is ...."},
      {"id":2, "title":"css", "body":"css is ...."},
      {"id":3, "title":"js", "body":"js is ...."}
    ]
    
    
    def template(content, id=None):
      contextUI = ''
      if id != None:
        contextUI = '<input type="submit" value="delete" class="btn btn-dark">'
      conn = sqlite3.connect('db.sqlite3')
      cs = conn.cursor()
      cs.execute('SELECT * FROM topics')
      topics = cs.fetchall()
      conn.close()
      liTags = ''
      for topic in topics:
        liTags = liTags + f'<li><a href="/read/{topic[0]}/">{topic[1]}</a></li>'
      return f'''
      <html>
        <head>
          <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">
          <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js" integrity="sha384-ka7Sk0Gln4gmtz2MlQnikT1wXgYsOg+OMhuP+IlRH9sENBO0LRn5q+8nbTov4+1p" crossorigin="anonymous"></script>
          <style>
            h1{{
              border-bottom:10px solid green;
            }}
            h1>a{{
              text-decoration: none;
            }}
          </style>
        </head>
        <body class="container">
          <h1><a href="/">WEB</a></h1>
          <ol>
            {liTags}
          </ol>
          {content}
          <form action="/delete/{id}/" method="POST">
            <div class="btn-group" role="group" aria-label="Basic example">
                <a href="/create/" class="btn btn-dark">create</a>
                {contextUI}
            </div>
          </form>
          <input type="button" value="night" onclick="
          if(this.value === 'night') {{
            document.querySelector('body').style.backgroundColor = 'black';
            document.querySelector('body').style.color = 'white';
            document.querySelectorAll('a').forEach(a => a.style.color = 'white');
            this.value = 'day'
          }}
          else {{
            document.querySelector('body').style.backgroundColor = 'white';
            document.querySelector('body').style.color = 'black';
            document.querySelectorAll('a').forEach(a => a.style.color = 'black');
            this.value = 'night'
          }}
          ">
          <!-- Copy and Paste Me -->
          <div class="glitch-embed-wrap" style="height: 420px; width: 100%;">
            <iframe
              src="https://glitch.com/embed/#!/embed/slash-nutritious-trowel?path=&previewSize=0"
              title="slash-nutritious-trowel on Glitch"
              allow="geolocation; microphone; camera; midi; encrypted-media; xr-spatial-tracking; fullscreen"
              allowFullScreen
              style="height: 100%; width: 100%; border: 0;">
            </iframe>
          </div>
        </body>
      </html>
      '''
    
    @app.route("/")
    def index():
      return template('<h2>Welcome</h2>Hello, WEB!')
    
    @app.route("/read/<int:id>/")
    def read(id):
      conn = sqlite3.connect('db.sqlite3')
      cs = conn.cursor()
      cs.execute('SELECT * FROM topics WHERE id=?', (id,))
      topic = cs.fetchone()
      conn.close()
      title = topic[1]
      body = topic[2]
      return template(f'<h2>{title}</h2>{body}', id)
    
    @app.route('/create/')
    def create():
      content = '''
        <form action="/create_process/" method="POST">
          <p><input type="text" name="title" placeholder="title"></p>
          <p><textarea name="body" placeholder="body"></textarea></p>
          <p><input type="submit" value="create"></p>
        </form>
      '''
      return template(content)
    
    @app.route('/create_process/', methods=['POST'])
    def create_process():
      title = request.form['title']
      body = request.form['body']
      conn = sqlite3.connect('db.sqlite3')
      cs = conn.cursor()
      cs.execute('INSERT INTO topics (title, body) VALUES(?,?)',(title,body))
      id = cs.lastrowid
      conn.commit()
      conn.close()
      return redirect(f'/read/{id}/')
    
    
    @app.route('/delete/<int:id>/', methods=['POST'])
    def delete(id):
      
      conn = sqlite3.connect('db.sqlite3')
      cs = conn.cursor()
      cs.execute('DELETE FROM topics WHERE id = ?',(id,))
      conn.commit()
      conn.close()
      
      return redirect('/')
     
    # @app.route('/update/')
    # def update():
    #   return 'Update'
    
    app.run()

    2.学習内容の難点

  • Nothing
  • 3.解決方法

  • Nothing
  • 4.勉強の心得


    この有名な生活コード師の講義内容を聞くことができて光栄です.