## Flask Python Flask 是一種輕量級的網頁框架,只需要簡單的幾行程式碼,就能輕鬆架設網站或建構網路服務。 ### 安裝套件 ``` pip install flask ``` ### 建立第一個網頁服務 先建立一個app.py的檔案並輸入下列程式碼並執行 ``` from flask import Flask app = Flask(__name__) @app.route("/") #代表網頁路徑 def hello(): #該路徑下所要做的行為 return "Hello, World!" if __name__ == '__main__': app.run() #執行app ``` 若出現如下面的回應代表開啟成功,可以前往127.0.0.1:5000查看是否有畫面   ### 使用網頁樣板 呼叫 Flask 所建立的網頁服務後,除了可以在網頁上顯示特定的文字,只要額外載入 render_template 套件,就能顯示位於同一層的 templates 文件夾裡的網頁樣板,而相對應的css檔案則存放在 static 資料夾中 建立一個為home.html的網頁 將此檔案放置在templates資料夾中 ``` <html> <head> <center> <meta http-equiv="content-type" content="text/html; charset=utf-8"> <title>Mongo</title> <link rel="stylesheet" type="text/css" href=""> </head> <body> <p align="center">MongoDB資料庫操作</p> </center> </body> </html> ``` ``` from flask import render_template #導入render_template套件 @app.route("/home") #查詢 def home(): return render_template("home.html") #去尋找templates資料夾中的home.html網頁 ``` 將程式碼複製並執行  ### PyMongo操作 #### 安裝套件 ``` pip install pymongo ``` #### 和資料庫進行連接 ``` client=MongoClient("mongodb://localhost:27017/") ``` #### 選取資料表 ``` db_name = 'project' collection_name='table' database=client[db_name] collection=database[collection_name] ``` ### 讀取網路公開json檔案並放入MongoDB中 #### insert.html ``` <html> <head> <center> <meta http-equiv="content-type" content="text/html; charset=utf-8"> <title>新增資料庫</title> <link rel="stylesheet" type="text/css" href=""> </head> <body> <form method="post"> <p><label for ="1">Insert an json URL:</label> <input type="text" name="URL"></p> <input type="submit" name="send" value="送出"> </form> </center> </body> </html> ``` #### URL ``` https://odws.hccg.gov.tw/001/Upload/25/opendataback/9059/232/56e42a6a-31e1-4f30-a513-dcfbc44471b7.json ``` #### 插入 ``` from flask import request from pymongo import MongoClient import requests @app.route("/insert", methods=["POST","GET"]) def insert(): if request.method =='POST': #如果有收到送出的資料 #request.form取得使用者在網頁輸入之資料(此處為網址) n = request.form["URL"] web = requests.get(n) #request.get取得該網址之json資料 web_json=web.json() db_name = 'table' collection_name='teacher' #選擇要插入的資料表,如果沒有的話會自己新增 client=MongoClient("mongodb://localhost:27017/") database=client[db_name] collection=database[collection_name] collection.insert_many(web_json) #執行插入 return "insert success!" return render_template("insert.html") #初始連結到http://127.0.0.1:5000會先顯示insert.html之頁面 ```   
×
Sign in
Email
Password
Forgot password
or
By clicking below, you agree to our
terms of service
.
Sign in via Facebook
Sign in via Twitter
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
New to HackMD?
Sign up