# 智慧客服 3/19 上課內容 ###### tags: `智慧客服` [virtualenv](https://pypi.org/project/virtualenv/) ![](https://i.imgur.com/lGX24NM.png) [python](https://www.python.org/downloads/windows/) ![](https://i.imgur.com/vfdT5Um.png) * 直接下一頁 ![](https://i.imgur.com/GzuMTNv.png) ![](https://i.imgur.com/r55oHO5.png) * 執行位址 #### 資料夾使用者權限設定 ![](https://i.imgur.com/irtfHDE.png) ![](https://i.imgur.com/EcATKaQ.png) ![](https://i.imgur.com/ISp7jPQ.png) ![](https://i.imgur.com/ou0R7U7.png) "c:\program files\python39\python.exe" -m pip install --upgrade pip ![](https://i.imgur.com/Irzy5Tp.png) ctrl+c 2次 離開cmd #### 環境變數的部分 ![](https://i.imgur.com/GiAmM6f.png) #### 桌面建一個資料夾 再拖入cmd ![](https://i.imgur.com/plVJWHr.png) + cd ![](https://i.imgur.com/aFBd2LP.png) ![](https://i.imgur.com/7XE4Fg7.png) virtualenv . 建立環境 cd Scripts * activate 啟動 ![](https://i.imgur.com/G2neyRC.png) 在(ve)環境下 安裝 Flask ![](https://i.imgur.com/9naPd4e.png) 建ve2 ![](https://i.imgur.com/W8oRLKK.png) kk建立資料夾 ![](https://i.imgur.com/RfHmKob.png) 進入kk的資料環境 ![](https://i.imgur.com/hBqQrNC.png) 都跟上面動作重複 ![](https://i.imgur.com/BinAWYX.png) ```clike= C:\> pip install virtualenv # 安裝虛擬環境的套件virtualenv C:\> mkdir flask_learning C:\> cd flask_learning C:\flask_learning> virtualenv . # .表示在目前的目錄新建虛擬環境 C:\flask_learning> cd Scripts C:\flask_learning\Scripts> activate # 進入虛擬環境 (flask_learning) C:\flask_learning\Scripts> deactivate # 離開虛擬環境 C:\flask_learning\Scripts> ``` #### 確認套件有安裝 ![](https://i.imgur.com/Pv6GBp6.png) [github](https://github.com/benctw/flask) ![](https://i.imgur.com/1k0XSli.png) ![](https://i.imgur.com/IZObXF4.png) ![](https://i.imgur.com/p4IVAbq.png) ![](https://i.imgur.com/evyUDbd.png) * git clone https://github.com/benctw/flask.git * dir 查看專案內容 #### vs Code ![](https://i.imgur.com/uhhyCN5.png) ![](https://i.imgur.com/K9yCegA.png) * 我有改圖示 不一樣正常的 ![](https://i.imgur.com/Ee0HT7Z.png) * 快速尋找章節 * #### github ![](https://i.imgur.com/oaI8R5r.png) * 建立副本 在自己帳號下 #### vs Code ![](https://i.imgur.com/1W16EqA.png) ![](https://i.imgur.com/1EyOEJM.png) ![](https://i.imgur.com/Ra214S5.png) C:\Users\Student\Desktop\ve\Scripts\python.exe ![](https://i.imgur.com/hzRxlfs.png) * ctrl+j 執行終端機 ![](https://i.imgur.com/h4AzZFx.png) * 當成文字 ![](https://i.imgur.com/z39Pobv.png) ## 修正一下位子 vsCode開啟位子 ![](https://i.imgur.com/nrdjD4F.png) 可以把裡面刪掉 ![](https://i.imgur.com/RDpCOB7.png) #### 安裝 [Azure](https://docs.microsoft.com/zh-tw/cli/azure/install-azure-cli) ![](https://i.imgur.com/DMixbqW.png) ![](https://i.imgur.com/e1qRpJS.png) 確認安裝成功 ![](https://i.imgur.com/VQCq5tn.png) az --version ![](https://i.imgur.com/gv8scmt.png) ![](https://i.imgur.com/1i5pRKw.png) az login ![](https://i.imgur.com/gpuMx1D.png) ![](https://i.imgur.com/mWf2rmn.png) #### 上傳 ![](https://i.imgur.com/777iUyG.png) name 後面是接專案名稱 ![](https://i.imgur.com/nyfzA0a.png) 不存在 會自動建立 ![](https://i.imgur.com/OfOSwxP.png) 更新 ![](https://i.imgur.com/FYtyy4V.png) #### 查看 ![](https://i.imgur.com/tasOSLI.png) #### vsCode ![](https://i.imgur.com/8YE8Bfw.png) ![](https://i.imgur.com/ogqhg67.png) ```clike= from flask import Flask app = Flask(__name__) @app.route('/') def homepage(): return '資策會' @app.route('/hello') def hello(): return 'h' @app.route('/user/<username>') def user(username): return f'hello {username}' if __name__ == "__main__": app.run(host='127.0.0.1', port=5000, debug=True) ``` * 範例3有 ![](https://i.imgur.com/Tg3w7WR.png) ```clike= @app.route('/') def homepage(): return 'Homepage' @app.route('/hello') def hello(): return 'Hello, World' @app.route('/user/<username>') def show_user_profile(username): # show the user profile for that user return 'User %s' % escape(username) @app.route('/post/<int:post_id>') def show_post(post_id): # show the post with the given id, the id is an integer return 'Post %d' % post_id @app.route('/path/<path:subpath>') def show_subpath(subpath): # show the subpath after /path/ return 'Subpath %s' % escape(subpath) ``` #### 範例4 ![](https://i.imgur.com/Fak5OPS.png) ```clike= from flask import Flask, url_for , redirect from markupsafe import escape app = Flask(__name__) @app.route('/') def index(): return 'index' @app.route('/login') def login(): return 'login' @app.route('/user') @app.route('/user/<username>') def profile(username=None): if username: return '{}\'s profile'.format(escape(username)) else: return redirect(url_for('index')) with app.test_request_context(): print(url_for('index')) print(url_for('login')) print(url_for('login', next='/')) print(url_for('profile', username='John Doe')) if __name__ == "__main__": app.run(host='127.0.0.1', port=5000, debug=True) ``` ![](https://i.imgur.com/RbqKbNj.png) ![](https://i.imgur.com/HXQD853.png) #### 範例5 * postman ![](https://i.imgur.com/5DCzaRa.png) ![](https://i.imgur.com/PJX9KBP.png) * 顯示圖片 ![](https://i.imgur.com/4jxD9Wf.png) ![](https://i.imgur.com/4zoMlS1.png) * 樣板 ![](https://i.imgur.com/6RLTYzL.png) ![](https://i.imgur.com/IMSzwvY.png) ```clike= from flask import Flask, url_for, request , render_template from markupsafe import escape def do_the_login(): return "do_the_login" def show_the_login_form(): return "show_the_login_form" app = Flask(__name__) @app.route('/') def index(): return render_template('index.html') @app.route('/login', methods=['GET', 'POST']) def login(): if request.method == 'POST': return do_the_login() else: return show_the_login_form() if __name__ == "__main__": app.run(host='127.0.0.1', port=5000, debug=True) ``` #### Bootstrap [Bootstrap](https://getbootstrap.com/docs/5.0/getting-started/download/) ![](https://i.imgur.com/IQ0jBab.png) ![](https://i.imgur.com/7Tl2HRp.png) ![](https://i.imgur.com/8qer201.png) ![](https://i.imgur.com/9857Jt3.png) ![](https://i.imgur.com/DQzTgba.png) ![](https://i.imgur.com/147szci.png) ![](https://i.imgur.com/MZAVOMv.png) #### index.html ```clike= <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Homepage</title> <link rel="stylesheet" href="/static/css/bootstrap.css"> </head> <body> {% include 'navbar.html' %} <script src="/static/js/bootstrap.js"></script> </body> </html> ``` #### login.html ```clike= <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Login</title> <link rel="stylesheet" href="/static/css/bootstrap.css"> </head> <body> {% include 'navbar.html' %} <div class="container"> <form action="/login" method="POST"> <div class="mb-3"> <label for="exampleInputEmail1" class="form-label">Email address</label> <input name="email" type="email" class="form-control" id="exampleInputEmail1" aria-describedby="emailHelp"> <div id="emailHelp" class="form-text">We'll never share your email with anyone else.</div> </div> <div class="mb-3"> <label for="exampleInputPassword1" class="form-label">Password</label> <input name="password" type="password" class="form-control" id="exampleInputPassword1"> </div> <button type="submit" class="btn btn-primary">Submit</button> </form> </div> <script src="/static/js/bootstrap.js"></script> </body> </html> ``` #### navbar.html ![](https://i.imgur.com/KPddebP.png) ```clike= <nav class="navbar navbar-expand-lg navbar-light bg-light"> <div class="container-fluid"> <a class="navbar-brand" href="#">Navbar</a> <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarSupportedContent"> <ul class="navbar-nav me-auto mb-2 mb-lg-0"> <li class="nav-item"> <a class="nav-link active" aria-current="page" href="/">Home</a> </li> <li class="nav-item"> <a class="nav-link" href="/login">Login</a> </li> <li class="nav-item"> <a class="nav-link" href="/logout">Logout</a> </li> <li class="nav-item dropdown"> <a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button" data-bs-toggle="dropdown" aria-expanded="false"> Dropdown </a> <ul class="dropdown-menu" aria-labelledby="navbarDropdown"> <li><a class="dropdown-item" href="#">Action</a></li> <li><a class="dropdown-item" href="#">Another action</a></li> <li><hr class="dropdown-divider"></li> <li><a class="dropdown-item" href="#">Something else here</a></li> </ul> </li> <li class="nav-item"> <a class="nav-link disabled" href="#" tabindex="-1" aria-disabled="true">Disabled</a> </li> </ul> <form class="d-flex"> <input class="form-control me-2" type="search" placeholder="Search" aria-label="Search"> <button class="btn btn-outline-success" type="submit">Search</button> </form> </div> </div> </nav> ``` #### 5 app.py ```clike= from flask import Flask, url_for, request, render_template, redirect, make_response from markupsafe import escape import time def do_the_login(email, password): if email=='benctw@gmail.com' and password=='kk123': resp = make_response(redirect(url_for('hello', useremail=email))) resp.set_cookie('useremail', email, expires = time.time()+60*60*24*7) return resp else: return redirect(url_for('error', errorcode=6000)) app = Flask(__name__) @app.route('/') def index(): return render_template('index.html') @app.route('/login', methods=['GET', 'POST']) def login(): if request.method == 'POST': email = request.form['email'] password = request.form['password'] return do_the_login(email, password) else: if request.cookies.get('useremail'): return redirect(url_for('hello', useremail=request.cookies.get('useremail'))) else: return render_template('login.html') @app.route('/logout') def logout(): resp = make_response(url_for('success',success=3001)) resp.set_cookie('useremail','',expires=0) return resp @app.route('/hello') def hello(): useremail = request.args.get('useremail', '') return render_template('hello.html',useremail=useremail) @app.route('/success/<int:successcode>') def success(successcode): return render_template('success.html', successcode=errorcode) @app.route('/error/<int:errorcode>') def error(errorcode): return render_template('error.html', errorcode=errorcode) if __name__ == "__main__": app.run(host='127.0.0.1', port=5000, debug=True) ``` ![](https://i.imgur.com/VLM2Mq0.png) ![](https://i.imgur.com/rbR98LX.png) div.xxxx 快捷 [參考老師](https://the.annswer.org/t/topic/312) [jinja語法](https://jinja.palletsprojects.com/en/2.11.x/templates/) [jinja老師的](https://the.annswer.org/t/topic/328) #### 網站 ![](https://i.imgur.com/bv0PXpS.png) ![](https://i.imgur.com/EjLwtME.png) #### error.html ![](https://i.imgur.com/uW3pSCh.png) ```clike= <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>error</title> <link rel="stylesheet" href="/static/css/bootstrap.css"> </head> <body> {% include 'navbar.html' %} <div class="container"> {% if errorcode==6000 %}帳號或密碼錯誤 {% elif errorcode==6001 %}資料庫連線錯誤 {% endif %} </div> <script src="/static/js/bootstrap.js"></script> </body> </html> ``` ![](https://i.imgur.com/J3aOVgB.png) #### success.html ```clike= <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>success</title> <link rel="stylesheet" href="/static/css/bootstrap.css"> </head> <body> {% include 'navbar.html' %} <div class="container"> {% if successcode==3000 %}登入成功 {% elif successcode==3001 %}登出成功 {% endif %} </div> <script src="/static/js/bootstrap.js"></script> </body> </html> ``` #### hello.html ```clike= <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Hello</title> <link rel="stylesheet" href="/static/css/bootstrap.css"> </head> <body> {% include 'navbar.html' %} <div class="container">hello</div> <script src="/static/js/bootstrap.js"></script> </body> </html> ``` #### page_nor_found.html ```clike= <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>404 Page not found</title> <link rel="stylesheet" href="/static/css/bootstrap.css"> </head> <body> {% include 'navbar.html'%} <div> 找不到頁面 </div> <script src="/static/js/bootstrap.js"></script> </body> </html> ``` #### sql [sqlitestudio](https://sqlitestudio.pl/) ![](https://i.imgur.com/6p1NGmo.png) ![](https://i.imgur.com/ad41ZND.png) ![](https://i.imgur.com/G53K2nF.png) ![](https://i.imgur.com/dtw3K66.png) ![](https://i.imgur.com/nuyQS2L.png) ![](https://i.imgur.com/aTUzQL7.png) ![](https://i.imgur.com/dTCcABV.png) ![](https://i.imgur.com/IjwayqM.png) ![](https://i.imgur.com/gq8mb2u.png) ![](https://i.imgur.com/68OFe0C.png) ![](https://i.imgur.com/u9c9tiO.png) #### vscode ![](https://i.imgur.com/2Yv0ddY.png) ![](https://i.imgur.com/bM1SUOP.png) ```clike= from flask import Flask, url_for, request, render_template, redirect, make_response, g from markupsafe import escape import time, sqlite3 def do_the_login(email, password): sql = f'select * from `user` where `email`="{email}" and `password`="{password}"' cursor = g.conn.cursor() cursor.execute(sql) data = cursor.fetchone() return data if data else False app = Flask(__name__) @app.before_request def before(): g.user_email='' # 連接資料庫 g.conn = sqlite3.connect('flaskdb.db') @app.teardown_request def teardown(exception): # 關閉連線資源 g.conn.close() @app.route('/') def index(): return render_template('index.html') @app.route('/login', methods=['GET', 'POST']) def login(): if request.method == 'POST': email = request.form['email'] password = request.form['password'] if do_the_login(email, password): resp = make_response(redirect(url_for('hello', useremail=email))) resp.set_cookie('useremail', email, expires = time.time()+60*60*24*7) return resp else: return redirect(url_for('error', errorcode=6000)) else: if request.cookies.get('useremail'): return redirect(url_for('hello', useremail=request.cookies.get('useremail'))) else: return render_template('login.html') @app.route('/logout') def logout(): resp = make_response(redirect(url_for('success', successcode=3001))) resp.set_cookie('useremail', '', expires=0) return resp @app.route('/hello') def hello(): useremail = request.args.get('useremail', '') return render_template('hello.html', useremail=useremail) @app.route('/success/<int:successcode>') def success(successcode): return render_template('success.html', successcode=successcode) @app.route('/error/<int:errorcode>') def error(errorcode): return render_template('error.html', errorcode=errorcode) @app.errorhandler(404) def page_not_found(error): return render_template('page_not_found.html') if __name__ == "__main__": app.run(host='127.0.0.1', port=5000, debug=True) ``` #### cmd ![](https://i.imgur.com/k34GAIK.png) ![](https://i.imgur.com/CbyejLo.png)