# L2 基本Flask APP ## h2初始化/app結構 ```python #起首式 from flask import Flask app = Flask(__name__) #app.config["DEBUG"] = True #以上可加可不加,為除錯模式,盡量不要用,會容易遭攻擊 #再加入修飾器 @app.route('/') #()中可加 methods=['GET'];也可不加 因為預設就是"GET" def index(): return '<h1>Hello Word!!</h1>' @app.route('/user/<name>') def user(name): return '<h1>Hello, {}!</h1>'.format(name) #最後需用 if __name__ == '__main__': app.run() #()中可放host = 0.0.0.0 或 127.0.0.1...等 #()host後可加path = "5000"(預設為5000) #結尾 ``` --- ##請求循環回應 ```python #起首式 from flask import request from flask import Flask #再加入修飾器 @app.route('/') def index(): user_agent = request.headers.get('User-Agent') return '<p>your browser is {}</p>'.format(user_agent) ``` ### Flask request物件 '''dictionary''' ``` form : 送出所有表單欄位 args : 傳入URL的查詢字串的所有引數 value : 結合form與args的值 cookies : 存著所有cookies headers : 所有 HTTP的標頭 files : 存有所有上傳的檔案 ``` '''回傳''' ``` get_data() : 回傳內文的暫存資料 get_jason() : 回傳dic.py,是request中已解析的JASON ``` '''處理''' ``` blueprint : 處理Flask blueprint endprint : 處理Flask endprint(端點名稱) ``` '''HTTP/URL/其他 ``` method : HTTP request方法,例:GET or POST scheme : URL協定 :http 或 https is_secure() : 如果 request 是用安全連結(https)傳來的,會回傳"Ture" host : http://(127.0.0.1):5000/ 可指定()中的數值 path : 基本上可指定5000路徑的地方 (改數字 ) query_string : URL的查詢字串部分,用原始二進位值表示 full_path : URL 的路徑與字串查詢部分 url : 完整的URL base_url : 與URL一樣,但沒有查詢字串部分 remote_addr : 用戶端的IP位址 environ : request 的原始WSGI 環境字典 ``` ## 回應 ```python from flask import Flask from flask import make_response app = Flask(__name__) app.config["SEND_FILE_MAX_AGE_DEFAULT"] = 1 ##設置瀏覽器不緩存 #不良的請求錯誤 @app.route('/') def index2(): return '<h1>Bad Request!!</h1>',400 #讓回應帶cookies @app.route('/') def index3(): response = make_response('<h1>This document carries a cookie!!</h1>') response.set_cookie('answer','42') return response ``` '''回應物件''' ``` status_code : HTTP 數字狀態碼 headers : 似dic 的物件,裡面有準備以回應傳送的所有標頭 set_cookie() : 將一個cookie 加入回應 delete_cookie() : 移除一個cookie content_length : 回應內文的長度 content_type : 回應內文的媒體類型 set_data() : 將回應內文設成字串或byte值 get_data() : 取得回應內文 ``` ###將回應導入另一個URL ```python from flask import Flask from flask import redirect app = Flask(__name__) @app.route('/') def index4(): return redirect('https://www.google.com.tw/') ``` ```python #接模板 from flask import Flask, render_template from flask_bootstrap import Bootstrap app = Flask(__name__) # 创建一个 Flask 應用 bootstrap = Bootstrap(app) # 為應用初始化 bootstrap @app.route('/') def test_index(): return render_template('try.html') ``` ```htmlmixed= <!DOCTYPE html> <html lang="en"> <head> <title>i營養</title> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <style> * { box-sizing: border-box; } /* Style the body */ body { font-family: Arial, Helvetica, sans-serif; margin: 0; } /* Header/logo Title */ .header { padding: 100px; text-align: center; background: #1abc9c; color: white; } /* Increase the font size of the heading */ .header h1 { font-size: 100px; } /* Style the top navigation bar */ .navbar { overflow: hidden; background-color: #333; } /* Style the navigation bar links */ .navbar a { float: left; display: block; color: white; text-align: center; padding: 14px 20px; text-decoration: none; } /* Right-aligned link */ .navbar a.right { float: right; } /* Change color on hover */ .navbar a:hover { background-color: #ddd; color: black; } /* Column container */ .row { display: -ms-flexbox; /* IE10 */ display: flex; -ms-flex-wrap: wrap; /* IE10 */ flex-wrap: wrap; } /* Create two unequal columns that sits next to each other */ /* Sidebar/left column */ .side { -ms-flex: 30%; /* IE10 */ flex: 30%; background-color: #f1f1f1; padding: 20px; } /* Main column */ .main { -ms-flex: 70%; /* IE10 */ flex: 70%; background-color: white; padding: 20px; } /* Fake image, just for this example */ .fakeimg { background-color: #aaa; width: 100%; padding: 20px; } /* Footer */ .footer { padding: 20px; text-align: center; background: #ddd; } /* Responsive layout - when the screen is less than 700px wide, make the two columns stack on top of each other instead of next to each other */ @media screen and (max-width: 700px) { .row { flex-direction: column; } } /* Responsive layout - when the screen is less than 400px wide, make the navigation links stack on top of each other instead of next to each other */ @media screen and (max-width: 400px) { .navbar a { float: none; width: 100%; } } </style> </head> <body> <div class="header"> <h1>I Love 營養</h1> <p>AI營養師</p> <p>吃出健康;吃出自信</p> </div> <div class="navbar"> <a href="#">首頁</a> <a href="#">個人營養師</a> <a href="#">營養知識</a> <a href="#">會員中心</a> <a href="#">會員登入</a> <a href="#" class="right">聯絡我們</a> </div> <div class="row"> <div class="side"> <h2>圖片辨識</h2> <h5>請丟入圖片:</h5> <div class="fakeimg" style="height:200px;">Image</div> <p>恩...這不是食物?</p> <h3>更多辨識</h3> <p>亙多的辨識</p> <div class="fakeimg" style="height:200px;">Image</div><br> <div class="fakeimg" style="height:200px;">Image</div><br> <div class="fakeimg" style="height:200px;;">Image</div> </div> <div class="main"> <h2>今日最推薦!!!</h2> <script language="JavaScript"> function ShowTime(){  document.getElementById('showbox').innerHTML = new Date();  setTimeout('ShowTime()',1000); } </script> <body onload="ShowTime()"> <div id="showbox"></div> <div class="fakeimg" style="height:200px;">Image</div> <p>Some text..</p> <p>Sunt in culpa qui officia deserunt mollit anim id est laborum consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco.</p> <br> <h2>TITLE HEADING</h2> <h5>Title description, Sep 2, 2017</h5> <div class="fakeimg" style="height:200px;">Image</div> <p>Some text..</p> <p>Sunt in culpa qui officia deserunt mollit anim id est laborum consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco.</p> </div> </div> <div class="footer"> <h2>Footer</h2> </div> </body> </html> ``` ###Flask Bookstrap 基礎模板區塊 ``` doc : all HTML文件 html_attribs : <html>標籤屬性 html : 標籤內容 head : 就頭啊~!<head>XXXXXXX會包<title><metas>等...</head> title : 就title <title>I 營養</title> metas : <metas>標籤清單 styles : CSS 定義 body_attribs : <body>標籤屬性 body : 就身體 包網頁整個內容 navbar : 使用者定義的導覽列 content : 使用者定義的網頁內容 scripts : 在文件底部的Javascrip宣告 ```
{"metaMigratedAt":"2023-06-15T08:17:02.936Z","metaMigratedFrom":"Content","title":"L2 基本Flask APP","breaks":true,"contributors":"[{\"id\":\"e763f6db-f068-4fad-b34f-ecca2118ec83\",\"add\":6763,\"del\":145}]"}
    148 views