# 業師演講筆記整理
---
## 1.發出Request
```python=
import requests
web = requests.get('https://httpbin.org/anything/get?user=andy')
```
:::success
<Response [200]>
:::
上面我對網站發出request並的到一個狀態碼200,代表請求成功
:::info
下面是HTTP協定中可能出現的狀態碼
1xx (Informational): 信息性狀態碼,指示請求已被接收,繼續處理。
2xx (Success): 成功狀態碼,表示請求已成功被伺服器接收、理解、並接受。
200 OK: 請求成功。常見的成功回應碼,表示伺服器成功處理了請求。
201 Created: 請求已經被實現,並且創建了一個新的資源。
204 No Content: 伺服器成功處理了請求,但沒有返回任何內容。
3xx (Redirection): 重新導向狀態碼,指示需要進行進一步的動作以完成請求。
301 Moved Permanently: 被請求的資源已永久移動到新位置。
302 Found (or Moved Temporarily): 被請求的資源暫時移動到新的位置。
304 Not Modified: 如果客戶端的請求的資源未修改,可以使用緩存的版本。
4xx (Client Error): 用戶端錯誤狀態碼,指示客戶端可能出現錯誤。
400 Bad Request: 伺服器無法理解請求的語法。
401 Unauthorized: 未授權,要求需要用戶驗證。
403 Forbidden: 伺服器理解請求,但拒絕執行它。
404 Not Found: 未找到請求的資源。
5xx (Server Error): 伺服器錯誤狀態碼,指示伺服器可能出現錯誤。
500 Internal Server Error: 伺服器遇到了一個未知的錯誤。
502 Bad Gateway: 伺服器作為閘道或代理,從上游伺服器接收到了一個無效的回應。
503 Service Unavailable: 伺服器目前無法處理請求(例如,由於超載或維護)。
:::
## 2.Request & response的結構
### 1.Request的結構
```python=
web.request.__dict__
```
:::success
{'method': 'GET',
'url': 'https://httpbin.org/anything/get?user=andy',
'headers': {'User-Agent': 'python-requests/2.28.1', 'Accept-Encoding': 'gzip, deflate', 'Accept': '*/*', 'Connection': 'keep-alive'},
'_cookies': <RequestsCookieJar[]>,
'body': None,
'hooks': {'response': []},
'_body_position': None}
:::

### 1.Response的結構
```python=
web.__dict__
```
:::success
{'_content': b'{\n "args": {\n "user": "andy"\n }, \n "data": "", \n "files": {}, \n "form": {}, \n "headers": {\n "Accept": "*/*", \n "Accept-Encoding": "gzip, deflate", \n "Host": "httpbin.org", \n "User-Agent": "python-requests/2.28.1", \n "X-Amzn-Trace-Id": "Root=1-655c0d8a-2b56ecd454cbbe600afe03b4"\n }, \n "json": null, \n "method": "GET", \n "origin": "140.116.247.244", \n "url": "https://httpbin.org/anything/get?user=andy"\n}\n',
'_content_consumed': True,
'_next': None,
'status_code': 200,
'headers': {'Date': 'Tue, 21 Nov 2023 01:53:14 GMT', 'Content-Type': 'application/json', 'Content-Length': '433', 'Connection': 'keep-alive', 'Server': 'gunicorn/19.9.0', 'Access-Control-Allow-Origin': '*', 'Access-Control-Allow-Credentials': 'true'},
'raw': <urllib3.response.HTTPResponse at 0x16ade263340>,
'url': 'https://httpbin.org/anything/get?user=andy',
'encoding': 'utf-8',
'history': [],
'reason': 'OK',
'cookies': <RequestsCookieJar[]>,
'elapsed': datetime.timedelta(seconds=2, microseconds=384520),
'request': <PreparedRequest [GET]>,
'connection': <requests.adapters.HTTPAdapter at 0x16ade23bc10>}
:::

```python=
from urllib.parse import urlparse, parse_qs
url = input()
o = urlparse(url)
# Parse the query parameters into a dictionary
query_params = parse_qs(o.query)
# Print the dictionary of query parameters
print(query_params)
```
:::success
'hl=zh-Hant'
:::
o.query是 URL 中的查詢參數部分
## 3.實作server的行為
```python=
from urllib.parse import urlparse
# 輸入一個URL
url = input() # 假設輸入是 http://127.0.0.1/hello/?user=andy
# 使用urlparse函數解析URL
o = urlparse(url)
# 取得URL的查詢參數部分
query_string = o.query
# 輸出查詢參數部分
print(query_string)
```
:::success
http://127.0.0.1/hello/?user=andy
'user=andy'
:::
```python=
from urllib.parse import urlparse
# 輸入一個URL
url = input()
# 使用 urlparse 函數解析URL
o = urlparse(url)
# 根據 URL 的路徑部分進行條件判斷
if o.path == '/hello':
# 如果路徑是 '/hello',印出查詢參數部分
print(o.query)
elif o.path == '/world':
# 如果路徑是 '/world',印出 'world'
print('world')
else:
# 如果路徑是其他,印出 'index'
print('index')
```
:::success
http://127.0.0.1/world
world
:::
## 4.路由實作
路由介紹:在 Web 開發中,路由(Route)是一種機制,用於將特定的 HTTP 請求(通常是 GET 或 POST)映射到應用程式中的特定端點(Endpoint)或處理函數。簡單來說,路由定義了應用程式如何回應不同的 URL 請求。
在 Flask 中,路由是使用 @app.route() 裝飾器來定義的。裝飾器將 URL 路徑(或模式)綁定到相應的函數,這樣當應用程式接收到特定的 URL 請求時,就會調用相應的處理函數。
```python=
pip install flask
from flask import Flask, request
# 創建 Flask 應用程式實例
app = Flask(__name__)
# 定義 Flask 路由
@app.route("/")
def index():
return "Hello World"
@app.route("/ncku")
def hello():
return "Hello NCKU"
# 當使用者訪問 /user 路徑時,使用 request.args 取得查詢參數 'input',如果沒有提供則預設為 'No input'
@app.route('/user', methods=['GET'])
def show_user_profile():
user = request.args.get('input', 'No input')
return f'User {user}'
# 當收到 '/calc' 路徑的 GET 請求時,執行以下函數
@app.route('/calc', methods=['GET'])
def my_calc():
# 從查詢參數 'expr' 中取得表達式
expr = request.args.get('expr')
# 使用 eval 函數計算表達式的值
result = eval(expr)
# 返回結果,格式化字符串顯示表達式和計算結果
return "{}={}".format(expr, result)
# 使用 request.args.get('expr') 從 GET 請求的查詢參數中獲取表達3#式,這個表達式應該是一個合法的 Python 運算式。
# 使用 eval(expr) 計算表達式的值。這裡使用 eval 函數,但需要注意,eval 函數可以執行任意的 Python 代碼,因此在實際應用中應謹慎使用,避免安全風險。
# 將表達式和計算結果格式化為字符串,然後返回結果。例如,如果查詢參數 'expr' 的值是 '2+3',那麼結果將是 "2+3=5"。
# 啟動 Flask 應用程式
if __name__ == '__main__':
app.run(debug=True)
app.run() #啟用server並對外連線
```
```python=
proc.terminate() # 中止
```
## 5.資訊安全鐵三角
### 1.機密性(Confidentiality)
要確保資訊未經授權不會被看到
### 2.完整性(Integrity)
確保資料不會被竄改
### 3.可用性(Availability)
自己要擁有授權隨時可更新資訊
在寫網頁或是執行程式碼時要遵守上述三個原則,以避免被攻擊