[開発ログ8日目]フラスコアプリケーションへのデータベースのバインド

13898 ワード

1.学習内容


1) reivew


1-1)フラスコの運転方法
app = Flask(__name__)
~~
app.run()
1-2)家庭訪問の方法
 @app.route('/')
ジェジュン("/")は家族を訪問する方法です.
1-3)template()機能
template()は重複を解消する機能です.

2)PythonとSqliteの接続-読み取り可能


2-1)表に次のコードを記述します.
sqlite3
.open db.sqlite3
CREATE TABLE topics (
id INTEGER PRIMARY KEY,
title TEXT NOT NULL,
body TEXT
)
;
INSERT INTO topics (title,body) VALUES('SQLite', 'SQLite is ...');

2-2)小故障読取.pyを作成します.
ファイルに読み込みます.pyファイルの作成

read.pyに次のコードを記述します.
import sqlite3
conn = sqlite3.connect('db.sqlite3')
curor = conn.cursor()
curor.execute('SELECT * FROM topics')
topics = curor.fetchall()
print(topics)
その後、
.exit
2-3)python 3をテーブルから読み込みます.py入力
結果:1 SQLite
(1はidを表す)

3)PythonとSqliteの連携書込み機能
3-1)小さな障害を作成します.pyを作成します.
ファイルに作成します.pyファイルを作成したら、次のコードを入力します.
import sqlite3
conn = sqlite3.connect('db.sqlite3')
curor = conn.cursor()
title = input('title? ')
body = input('body? ')
curor.execute('INSERT INTO topics (title, body) VALUES(?, ?)', (title, body))
conn.commit()
conn.close()

3-2)下表
python3 create.py
入力した場合
title? mysqlの後、
body? これでMySQLは….
黙っていればいいのに.
<コメント>
もう一度確認するために、テーブルの上に
python3 create.py
入力後、下図のように表示される画面が良いです.

4)createから読み込む
importはモジュールをロードするコードで、最後にimport readと書くべきです.
create.pyに次のコードを入力します.

import sqlite3
conn = sqlite3.connect('db.sqlite3')
curor = conn.cursor()
title = input('title? ')
body = input('body? ')
curor.execute('INSERT INTO topics (title, body) VALUES(?, ?)', (title, body))
conn.commit()
conn.close()

import read
その後terminalに行ってpython 3 readを読みます.py
title? 甲骨文
body?これで甲骨文...そう言えば.
1 SQLite
2 mysql
3 oracle
表示されると、createでreadウィンドウが読み込まれます.

5) server.pyでトピックをDBに変換する方法
既存のトピックをDBに変更すると、ファイルとして保存されるため、情報を永続的に保存できます.
topics = [
  {"id":1, "title":"html", "body":"html is ...."},
  {"id":2, "title":"css", "body":"css is ...."},
  {"id":3, "title":"js", "body":"js is ...."}
]
5-1)sqliteを先に使用する必要があるのでimport sqlite 3
from flask import Flask, request, redirect
import sqlite3
5-2)sqlite 3への接続方法
app = Flask(__name__)
import sqlite3

topics = [
  {"id":1, "title":"html", "body":"html is ...."},
  {"id":2, "title":"css", "body":"css is ...."},
  {"id":3, "title":"js", "body":"js is ...."}
]
nextId = 4

def template(content, id=None):
  liTags = ''
  for topic in topics:
    liTags = liTags + f'<li><a href="/read/{topic["id"]}/">{topic["title"]}</a></li>'
  return f'''
トピックのトピック:
LiTags=liTags+f'
  • {トピック["title"]}
  • "是,作为报道名单的sqlite 3作为网络制作报道名单.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 ...."} ] nextId = 4 def template(content, id=None): 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''roconn表示connect,db.接续到sqlite 3.之后,制作了汽车(cursor).cs=conn.cursor()生成了cs这个汽车.cs.汽车指示的结果由execute("SELECT*FROM托皮克")生成.topics = cs.fetchall()によるdb中の情報をPython化し、fetchを「インポ」、allを「全部」と表す.以此为主题的.5-3)适用db的完全代码的SQLite/myql/oracle.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 ...."} ] nextId = 4 def template(content, id=None): 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> <body> <h1><a href="/">WEB</a></h1> <ol> {liTags} </ol> {content} <ul> <li><a href="/create/">create</a></li> <li> <form action="/delete/{id}/" method="POST"> <input type="submit" value="delete"> </form> </li> </ul> </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,)) conn.close() title = '' body = '' for topic in topics : if topic['id'] == id: title = topic['title'] body = topic['body'] break; 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(): global nextId title = request.form['title'] body = request.form['body'] newTopic = {"id":nextId, "title": title, "body": body} topics.append(newTopic) nextId = nextId + 1 return redirect(f'/read/{nextId-1}/') @app.route('/delete/<int:id>/', methods=['POST']) def delete(id): for topic in topics: if topic['id'] == id: topics.remove(topic) break; return redirect('/') # # @app.route('/update/') # # def update(): # # return 'Update' app.run() <评论>fatchone:1只打印时,fatchall:list表示6)2022.04.01 bootstrap+css等のマスタ時最終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 pink; }} h1>a{{ text-decoration:none; }} </style> </head> <body class="container"> <input type="button" value="night" onclick=" document.querySelector('body').style.backgroundColor = 'black'; document.querySelector('body').style.color = 'white'; "> <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> </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()結果-1)メイン画面結果-2)sqlite押したときの画面delete windowを表示結果-3)nightをクリックした場合の学習内容の難点や未解決の問題第3節の授業内容の自己createを実現することは難しい.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(): global nextId title = request.form['title'] body = request.form['body'] newTopic = {"id":nextId, "title": title, "body": body} topics.append(newTopic) nextId = nextId + 1 return f'success!! go:/read/{nextId-1}/'Sorechon的制作雷斯维德奥利法伦斯@app.route('/create_process/', methods=['POST']) def create_process(): global nextId title = request.form['title'] body = request.form['body'] newTopic = {"id":nextId, "title": title, "body": body} topics.append(newTopic) nextId = nextId + 1 return f'success!! go:/read/{nextId-1}/'活動場所を示す@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}/')用コード完成了コード.学习心得以及月末评价中,Python从0开始排队的部分错误了,但在今天接受的最后的法国应用程序中,数据贝斯的连动部分也再次接受,可以理解本人能向其他人说明的程度.そう思うよ