ในภาษา Python สามารถเขียนเว็บไซต์ได้การ flask framework ซึ่งเป็นตัวจัดการเว็บไซต์ของภาษา Python ส่วนมากเว็บไซต์ต่างๆ จะทำมาให้รองรับ 2 ภาษา และสำหรับคนที่กำลังหาวิธีการทำหรือตัวอย่างสามารถนำไปใช้หรือประยุกต์ได้ ส่วนวิธีขั้นตอน เป็นการใช้ไฟล์ config มาเก็บตัวแปรของทั้งสองภาษา แล้วให้ส่งไปยังหน้าไฟล์ HTML เพื่อแสดง จะต้องทำการเรียกใช้ library configparser ของ Python เพื่อใช้ตัวแปรในไฟล์ config โดยวิธีการก็จะมีดังนี้
คำสั่งติดตั้ง flask และ configparser
โค้ด: เลือกทั้งหมด
pip install flask
โค้ด: เลือกทั้งหมด
pip install configparser
โค้ด: เลือกทั้งหมด
from flask import Flask, render_template
import configparser
โค้ด: เลือกทั้งหมด
config = configparser.ConfigParser()
config.read('config.conf')
โค้ด: เลือกทั้งหมด
[TH]
str1=สวัสดี ไพธอน
str2=วันนี้วันอะไร
[EN]
str1=Hallo python
str2=What's today
โค้ด: เลือกทั้งหมด
from flask import Flask, render_template, request
import configparser
config = configparser.ConfigParser()
config.read('config.conf')
text_en=config['EN']
text_th=config['TH']
โค้ด: เลือกทั้งหมด
@app.route('/')
def index():
return render_template('home.html')
โค้ด: เลือกทั้งหมด
@app.route('/', methods=['GET'])
def index():
text = text_th
if request.values.get('lang') and request.values.get('lang') == 'en':
text=text_en
return render_template('home.html' , text=text)
โค้ด: เลือกทั้งหมด
from flask import Flask, render_template, request
import configparser
config = configparser.ConfigParser()
config.read('config.conf')
text_en=config['EN']
text_th=config['TH']
app = Flask(__name__)
@app.route('/', methods=['GET'])
def index():
text = text_th
if request.values.get('lang') and request.values.get('lang') == 'en':
text=text_en
return render_template('home.html' , text=text)
if __name__=='__main__':
app.run(debug=True)
โค้ด: เลือกทั้งหมด
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
ข้อความ : <span>{{text['str1']}}</span><br>
ข้อความ : <span>{{text['str2']}}</span><br>
<a href="?lang=th">ภาษาไทย</a>
<a href="?lang=en">ภาษาอังกฤษ</a>
</body>
</html>
จะสังเกตได้ตัวแปร get เท่ากัน th
เมื่อตัวแปรเปลี่ยนเป็น en ข้อความก็เปลี่ยนภาษาอังกฤษ
เท่านี้ก็เป็นอันที่เรียบร้อย
อ้างอิง
https://www.mindphp.com/forums/viewtopic.php?p=161740#p161740
https://www.mindphp.com/บทเรียนออนไลน์/python-framework-flask/6442-flask-framework-html-css-python.html
https://www.mindphp.com/คู่มือ/73-คืออะไร/2417-python-คืออะไร.html