Python/Flask/README.md
2024-06-24 12:54:27 +08:00

233 lines
6.6 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# Flask
## 介紹
### Flask 是一個使用 Python 語言開發的輕量級 Web 應用框架。近年來因為Python簡單易學的語法以及強大的生態系統所以在Web開發領域也逐漸受到青睞。其中Flask的哲學是保持核心簡單但擴充性強它只提供了路由、模板、靜態檔案等最基本的功能其他大多數功能則是通過擴展提供這樣可以讓我們按需求選擇。
### Flask強調概念明確、低耦合度和可擴充性。和Django等全能框架不同
### Flask 用template 與 static 2個資料夾做區分
#### template 用於存放HTML等網頁
#### static 用於存放靜態文件包刮JS、CSS、img等
#### 若需要更進階的需求建議去前端找Bootstrap那邊以Flask去介紹如何套版可以快速製作漂亮的網站頁面
##
## 程式碼說明
### 首先先以Python切入
### Python
```python
# 匯入會用到的庫
from flask import Flask
from flask import render_template
from flask import Flask, request, jsonify
import threading
import requests, socket
import pymysql
# from flask_cors import CORS # 若有跨域需求再開,練習通常用不到
```
### 接著我這邊與網路上的寫法有些不同,我直接寫成物件導向的方式,實測下來沒太大問體
#### 先設定多線呈方式,及設定好資料庫連線位置
```python
class Website(threading.Thread):
def __init__(self):
threading.Thread.__init__(self)
self.db = pymysql.connect(host='140.125.21.65', port=3307, user='VIP125', passwd='@VIPvip125', db='VIP125', charset='utf8')
self.app = Flask(__name__)
# CORS(self.app)
```
### 路由設定
#### 這邊統一教學我設定成前後端分離的方式將頁面與API做個區分之後若是要單獨架設頁面或是API都可以直接修改
```python
#前端顯示
self.app.add_url_rule('/', 'Index', self.Index)
self.app.add_url_rule('/next/<id>', 'Next', self.Next)
# API
self.app.add_url_rule('/api/get_data', 'get_data', self.get_data,methods=['get'])
self.app.add_url_rule('/api/get_one_data/<id>', 'get_one_data', self.get_one_data, methods=['get'])
```
### 前端頁面導向
#### 這邊提供純頁面及需要攜帶部分參數的簡單方式
```python
# 前端
def Index(self):
return render_template('Index.html')
def Next(self,id): # 攜帶參數
return render_template('Next.html',id = id)
```
### 後端資料
#### 建議先看過一部份的資料庫語法後再來接觸
```python
# 後端API
def get_data(self):
cursor = self.db.cursor()
sql = "select * from teaching_sql_1"
cursor.execute(sql)
data = cursor.fetchall()
print(f'ALL_data = {data}')
return jsonify(data)
def get_one_data(self,id):
cursor = self.db.cursor()
sql = f"SELECT * FROM teaching_sql_1 WHERE student_id='{id}';"
print(sql)
cursor.execute(sql)
data = cursor.fetchall()
print(f'user_id = {data}')
return jsonify(data)
```
### 完整程式
```python
from flask import Flask
from flask import render_template
from flask import Flask, request, jsonify
import threading
import requests, socket
import pymysql
# from flask_cors import CORS
class Website(threading.Thread):
def __init__(self):
threading.Thread.__init__(self)
self.db = pymysql.connect(host='140.125.21.65', port=3307, user='VIP125', passwd='@VIPvip125', db='VIP125',
charset='utf8')
self.app = Flask(__name__)
# CORS(self.app)
#前端顯示
self.app.add_url_rule('/', 'Index', self.Index)
self.app.add_url_rule('/next/<id>', 'Next', self.Next)
# API
self.app.add_url_rule('/api/get_data', 'get_data', self.get_data,methods=['get'])
self.app.add_url_rule('/api/get_one_data/<id>', 'get_one_data', self.get_one_data, methods=['get'])
def run(self):
#self.app.run()
self.app.run(host="0.0.0.0", port="5500")
# 前端
def Index(self):
return render_template('Index.html')
def Next(self,id): # 攜帶參數
return render_template('Next.html',id = id)
# 後端API
def get_data(self):
cursor = self.db.cursor()
sql = "select * from teaching_sql_1"
cursor.execute(sql)
data = cursor.fetchall()
print(f'ALL_data = {data}')
# 返回 JSON 响应
return jsonify(data)
def get_one_data(self,id):
cursor = self.db.cursor()
sql = f"SELECT * FROM teaching_sql_1 WHERE student_id='{id}';"
print(sql)
cursor.execute(sql)
data = cursor.fetchall()
print(f'user_id = {data}')
return jsonify(data)
if __name__ == '__main__':
website = Website()
website.run()
```
### 前端(HTML)
#### 這邊就以基礎的HTML與JS進行
#### 有簡單的利用AJAX去撈資料、頁面跳轉
#### Index.html
``` HTML
<!DOCTYPE html>
<html lang="en">
<head>
<title>Flask HTML CSS Example</title>
<link rel="stylesheet" href="{{ url_for('static', filename='css/style.css') }}">
<link rel="stylesheet" href="{{ url_for('static', filename='lib/bootstrap/dist/css/bootstrap.min.css') }}"/>
<link rel="stylesheet" href="{{ url_for('static', filename='css/site.css') }}" asp-append-version="true"/>
<script src="{{ url_for('static', filename='js/script.js') }}"></script>
<script src="{{ url_for('static', filename='js/site.js') }}"></script>
<script src="{{ url_for('static', filename='lib/bootstrap/dist/js/bootstrap.bundle.min.js') }}"></script>
<script src="{{ url_for('static', filename='lib/jquery/dist/jquery.min.js') }}" asp-append-version="true"></script>
</head>
<body>
<h1>Flask</h1>
<div class="size2">
<div>
Hello World!
</div>
<input type="text" id="value_id" />
<button onclick="next_clicked()">下一頁</button>
<button onclick="get_data()">獲取資料</button>
</div>
</body>
</html>
<script>
function next_clicked(){
var id = document.getElementById("value_id").value
window.location = "/next/" + id;
}
function get_data(){
$.ajax({
type: "GET",
url: "/api/get_data",
data: {},
contentType: "application/json",
success: function (Model) {
console.log(Model)
//set_data(Model)
}
});
}
</script>
```
#### Next.html
``` HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<input id="value_id" value='{{ id }}' />
<br>
<button onclick="Index_clicked()">首頁</button>
</body>
</html>
<script>
function Index_clicked(){
window.location = "/";
}
</script>
```