Daily Log - 12/08/2024

makkawai

MAK KA WAI

Posted on August 12, 2024

Daily Log - 12/08/2024

I try python Flask and interact with html.

from flask import Flask, render_template, request, redirect, url_for
import os
from werkzeug.utils import secure_filename

# app = Flask(__name__, template_folder="./templates2") # if folders name templates, no need [, template_folder="./templates2"]
app = Flask(__name__)

@app.route('/hello/', methods=['GET', 'POST'])
def hello():
    if request.method == 'POST':
        name1 = request.form['yourname']
        age = request.form['yourage']
        return render_template('hello.html', name=name1, age4=age)
    return render_template('hello.html')

@app.route('/login/', methods=['GET', 'POST'])
def login():
    if request.method == 'POST':

        return render_template('login.html')
    return render_template('login.html')

''' File Upload '''

# 設置上傳文件夾
UPLOAD_FOLDER = 'uploads'
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER

# 確保上傳文件夾存在
os.makedirs(UPLOAD_FOLDER, exist_ok=True)

# 允許上傳的文件類型
ALLOWED_EXTENSIONS = {'txt', 'pdf', 'png', 'jpg', 'jpeg', 'gif'}

def allowed_file(filename):
    return '.' in filename and \
           filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS

@app.route('/upload/', methods=['GET', 'POST'])
def upload_file():
    if request.method == 'POST':
        # 檢查是否有文件部分
        if 'file' not in request.files:
            return 'No file part'
        file = request.files['file']
        # 如果用戶沒有選擇文件,瀏覽器也會提交一個空的文件名
        if file.filename == '':
            return 'No selected file'
        if file and allowed_file(file.filename):
            filename = secure_filename(file.filename)
            file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
            return redirect(url_for('upload_file'))
    return render_template('upload.html')



if __name__ == '__main__':
    app.run(debug=True)
Enter fullscreen mode Exit fullscreen mode

Also, the sample of ‘Front-End and Back-End Communication.zip’ was tested. Success.


I attended the AWS Bootcamp.

💖 💪 🙅 🚩
makkawai
MAK KA WAI

Posted on August 12, 2024

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related