昨天專題需要用到Flask,所以學了一下怎麼寫
當成功的時候,超開心的,
我想在資工最快樂的時候就是code寫出來吧XD
from flask import Flask
app = Flask(__name__)
@app.route("/")
def index():
return "<h1>我是飛飛,飛飛是我</h1>"
if __name__ == "__main__":
app.run()
# -*- coding: utf-8 -*-
import os
from flask import Flask, request, url_for, send_from_directory
# 安全性問題
from werkzeug import secure_filename
ALLOWED_EXTENSIONS = set(['png', 'jpg', 'jpeg', 'gif']) #允許的附檔名
app = Flask(__name__)
app.config['UPLOAD_FOLDER'] = os.getcwd()+'/media' #取得伺服器目前路徑
app.config['MAX_CONTENT_LENGTH'] = 16 * 1024 * 1024 # 限制大小 16MB
#創建一個上傳表單:
html = '''
<!DOCTYPE html>
<title>上傳檔案測試頁</title>
<h1>上傳圖片</h1>
<form method="post" enctype="multipart/form-data">
<input type="file" name="file">
<input type="submit" value="上傳">
</form>
'''
#檢查上傳檔案是否合法的函數
def allowed_file(filename):
return '.' in filename and filename.rsplit('.', 1)[1] in ALLOWED_EXTENSIONS
#取得上傳後的檔案
@app.route('/uploads/<filename>')
def uploaded_file(filename):
return send_from_directory(app.config['UPLOAD_FOLDER'],
filename)
@app.route('/', methods=['GET', 'POST'])
def upload_file():
if request.method == 'POST':
#我們透過request上的files取得上傳檔案
file = request.files['file']
#確認有檔案且上傳文件合法
if file and allowed_file(file.filename):
#secure_filename函數來檢查上傳檔案檔名,會回傳ASCII,中文被省略,空格變成底線
filename = secure_filename(file.filename)
#將上傳的檔案存進去伺服器內並存放在指定資料夾中
file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
file_url = url_for('uploaded_file', filename=filename)
return html + '<br><img src=' + file_url + '>'
return html
if __name__ == '__main__':
app.run()