2020-04-22

Flask 接收表單資料及 query string

Flask 接收表單資料及 query string

本文的參考專案 https://github.com/shinder/flask-practice

  • request.args 可取得 GET 參數(query string)
  • request.form 可取得 POST 參數(表單資料)
  • request.files 可取得表單上傳的檔案

以下為取得 GET 和 POST 參數的例子:

@app.route('/try-qs') def queryString(): # query string 轉成 dict # http://localhost:5000/try-qs?a[]=1&b=34&a[]=5 output = { 'args': request.args, 'a[]': request.args.getlist('a[]'), 'get_b': request.args.get('b'), 'get_a[]': request.args.get('a[]'), } return output @app.route('/try-post', methods=['POST']) # 限定使用 POST def try_post(): # 表單資料 urlencoded, form-data 皆可, 使用 postman 測試 output = { 'form': request.form, 'a[]': request.form.getlist('a[]'), 'post_b': request.form.get('b'), 'post_a[]': request.form.get('a[]'), } return output @app.route('/try-post2', methods=['POST']) def try_post2(): # 使用 postman post json 資料: {"a":11,"b":22} output = { 'content_type': request.content_type, 'data': request.data.decode('utf-8'), 'json': request.get_json(), } return output

測試時,/try-post 和 /try-post2 可以使用 postman 測試。 getlist() 能取得所有相同名稱的參數,而拿到 list 類型的物件(陣列)。但不會將名稱有帶中括號的參數自動轉換為陣列。

使用 postman 將 json 文件 post 給 /try-post2 路由。request.data.decode('utf-8') 可以拿到字串;request.get_json() 可以拿到由 JSON 字串轉換而成的 dict 或 list。

2020-04-20

Flask 的樣版系統 Jinja

Flask 的樣版系統 Jinja

本文的參考專案 https://github.com/shinder/flask-practice

Flask 樣版說明可以參考 這裡

在主程式加入以下片段:

from flask import render_template @app.route('/basic-template') def basic_template(): return render_template('basic.html', name='是在哈囉', age=25) @app.route('/basic-template2') def basic_template2(): output = { 'name': '小明', 'age': 30 } return render_template('basic.html', ** output)

render_template() 用來呈現頁面,第一個參數為樣版檔(樣版檔必須放在 app/templates 資料夾內),第二個參數之後為欲傳入樣版的資料。

如 basic_template2() 也可以將資料包成 dict 然後再傳入。

樣版 app/templates/basic.html 的內容如下:

<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>{{ name }}</title> </head> <body> <h2>Hello, {{ name }}</h2> <h6>{{ age }}</h6> </body> </html>

2020-04-19

Flask 靜態檔案資料夾

在專案的資料夾的 app 內建立 static 資料夾,並在建立 app 物件時給第二個參數,指定路徑。

app = Flask(__name__, '/')

static 資料夾就會看成類似 apache 的 document root。

將處理的方法放到不同的 .py 檔

將處理的方法放到不同的 .py 檔

本文的參考專案 https://github.com/shinder/flask-practice

將處理的方法寫到 modules/functions.py 裡

from flask import request # 滙入 request def show_cookies(): return request.cookies

在主要檔案 main.py 滙入:

import modules.functions # 語法:add_url_rule(rule, endpoint=None, view_func=None, provide_automatic_options=None, **options) app.add_url_rule('/show-cookies', 'show-cookies', modules.functions.show_cookies) # app.add_url_rule('/show-cookies', 'show-cookies') # app.view_functions['show-cookies'] = modules.functions.show_cookies
  • 使用 add_url_rule() 可以將處理函式設定給路由。
  • endpoint 用來做處理函式及路由的對應。給 None 時,則使用函式名稱。
  • 這樣的方式可以將處理函式放在不同的檔案,以方便維護。

將 request headers 寫入檔案

將 request headers 寫入檔案

本文的參考專案 https://github.com/shinder/flask-practice

from flask import request # 滙入 request import json @app.route('/save-headers') def save_headers(): dict1 = { 'cookies': {} } for i in request.headers: print(i) # 查看取出的 headers 資料 dict1[i[0]] = i[1] # 查看 cookies for i in request.cookies: dict1['cookies'][i] = request.cookies[i] file1 = open('headers.json', 'w') file1.write(json.dumps(dict1)) # 存成 JSON return dict1
  • dict1 為用來暫存資料的 dict,並設定好結構
  • request.headers 用 for/in 取出,為 tuple
  • request.cookies 為 dict
  • json 為預設套件,dumps 為轉換為 JSON 字串
  • return dict 會自動轉換為 JSON 格式
  • 拜訪 localhost:5000/save-headers 可以看到結果

建立 Flask 專案

建立 Flask 專案

本文的參考專案 https://github.com/shinder/flask-practice

首先如之前的文章 建立專案

md flask-practice #建立專案資料夾 cd flask-practice #到專案目錄 python3 -m venv venv #安裝虛擬環境 source venv/bin/activate #啟動虛擬環境(mac)

安裝 Flask:

pip install flask

可以使用下列兩個命列中的一個查看安裝的套件:

pip list pip freeze

建立 app 資料夾,用來存放自己撰寫的程式,並在裡面建立 main.py

from flask import Flask # __name__ 用來 application 的相對位置 # 若是直接啟動的程式 __name__ 為 '__main__' # 若是被滙入, __name__ 會是被滙入的名稱 app = Flask(__name__) # decorators 後面定義的 function 會變成 decorators 的參數 # 類似 JavaScript 的 callback function @app.route('/') def index(): return '<h2>哈囉 Flask</h2>'

在專案目錄建立執行的 run.sh,在 mac 記得將檔案屬性設定為 +x 可執行:

# mac export FLASK_APP=app/main.py export FLASK_ENV=development flask run --host=localhost --port=5000 # windows # set FLASK_APP=app/hello.py # set FLASK_ENV=development # flask run

在 terminal 執行 run.sh,並在瀏覽器拜訪 localhost:5000 即可看到我們的第一個頁面。

2020-04-15

VSCode 簡便的 MySQL 管理外掛

VSCode 外掛 MySQL (MySQL management tool)
作者: Jun Han
外掛 ID: formulahendry.vscode-mysql

算是簡單易用的 MySQL 管理工具

2020-04-09

在 VSCode 上編寫 Markdown 文件

若要在 VSCode 上編寫 MD 文件,官方的建議,我自己安裝了:
  • markdownlint
  • Markdown Theme Kit
  • Markdown Shortcuts
另外還安裝了:
  • Markdown All in One
  • Markdown PDF
這樣基本工具都有了,Markdown PDF 可以很方便輸出成 pdf 及 html。

以下是語法的小筆記:


# 大標題

## 次標題

### 細標題

另一種大標 (不建議使用)
===

另一種次標  (不建議使用)
---

條列方式一: - (建議不要用 * 和 +)

- 123
- 456
- 789

條列方式二: *  (不建議使用)

* 123
* 456
* 789

條列方式三: +  (不建議使用)

+ 123
    + 111
        + 333
    + 222
+ 456
+ 789

條列方式四: 使用數字加點  (數字可以不管順序,但不建議)

1. 123
    1. 333
    2. 777
2. 456
3. 789

### 程式碼呢? 前面加 \t 或 4個空白

    const func = a => a*a;
    
    const func2 = ()=>{
        let r = 0;
        for(let i=1; i<=10; i++){
            r+=i;
        }
        return r;
    };

    const func = a => a*a;

``` javascript
const func2 = ()=>{
    let r = 0;
    for(let i=1; i<=10; i++){
        r+=i;
    }
    return r;
};
```

### 行內程式碼

這是個行內的 `console.log(me);` 程式碼

這是個行內的 ``console.log(bill`s);`` 程式碼

---
上下是分隔線  (不建議使用 *** )

***

*斜體*
**粗體**
_斜體_
__粗體__

區塊引言
>123
>456
>78945

### 連結

[This link](http://example.net/) has no title attribute.

### 表格

 | column0 | column1 | aaa
 | ------- | ------- | -----
 | 123 | 456 | 789
 | abc | def | ghi
 | aaa | bbb | ccc



2019-11-08

Angular 環境

官網:https://angular.io/

安裝:
npm i @angular/cli -g

建立專案:
ng new my-proj

或建立專案時產生routes模組:
ng new hello-cli --routing

啟動測試的 web server:
ng serve
ng serve --prod

測試網址:
http://localhost:4200

建立產品版本:
ng build --prod

建立 component:
ng generate component my-component
ng g c my-component










2019-10-20

建立 python 虛擬環境

預先安裝:
1. 已經安裝好 homebrew
2. 並使用 brew 安裝 python3

python3 在 3.5 之後的版本,都會隨附安裝 pip3 和 pyvenv,因此要建立虛擬環境,十分容易。建立專案資料夾後,進入專案目錄,並執行:

python3 -m venv venv

建立之後,Mac 在專案的資料夾內的 terminal 命令列執行下式以啟動虛擬設定:
source venv/bin/activate

離開則是下:
deactivate

FB 留言