例如 C:\Webapp
pip install Flask
from flask import Flask
app = Flask(__name__) # __name__ 為 python 內建的變數,他會儲存目前程式在哪個模組下執行,如果為__main__代表主程式
@app.route("/") #函式的裝飾 Decorator,以底下函式為基礎,提供附加的功能,這邊 "/" 代表根目錄
def home():
return "Hello Flask12"
if __name__ == "__main__": #如果以主程式運行
app.run() #啟動伺服器 debug=True 修改內容將立即反應在網頁
本例為index.html
<html>
<head>
<title>{{title}}</title>
</head>
<body><h1>Hello World</h1></body>
</html>
將index.html檔放置此資料夾內
本例為index()
@app.route("/index")
def index():
title="Weichen Wu"
return render_template("index.html", title=title)
from flask import Flask, render_template
app = Flask(__name__)
@app.route("/")
def home():
return "Hello Flask"
@app.route("/test/")
def test():
return "<h2>Test Test</h2>"
@app.route("/fcu/")
def fcu():
return "<h1>fcufcu</h1>"
@app.route("/index/")
def index():
return render_template("index.html",title="aaaaaa",arg="吳威震")
if __name__ == "__main__": #如果以主程式運行
app.run(debug=True) #啟動伺服器
記得import requests與pandas
import requests
import pandas as pd
新增一個route為get2330
@app.route("/get2330/")
def get2330():
site = "https://query1.finance.yahoo.com/v7/finance/download/2330.tw?period1=0&period2=1585008000&interval=1d&events=history&crumb=hP2rOschxO0"
response = requests.get(site)
with open('file.csv', 'w') as f:
f.writelines(response.text)
df = pd.read_csv('file.csv')
return render_template('query.html', tables=[df.to_html(classes='data')], titles=df.columns.values)
新增一個route為getstock
@app.route("/getstock/", methods=['GET'])
def getstock():
stockID = request.args.get('stockID')
site = "https://query1.finance.yahoo.com/v7/finance/download/" + stockID + "?period1=0&period2=1585008000&interval=1d&events=history&crumb=hP2rOschxO0"
response = requests.get(site)
#print(response.text)
with open('file.csv', 'w') as f:
f.writelines(response.text)
df = pd.read_csv('file.csv')
return render_template('query.html', tables=[df.to_html(classes='data')], titles=df.columns.values)
使用方式為
http://127.0.0.1:5000/getstock/?stockID= 股票代號
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
{% for table in tables %}
{{titles[loop.index]}}
{{ table|safe }}
{% endfor %}
</body>
</html>