Perl, C เป็นภาษาที่นิยมนำมาใช้งานเป็นตัวเชื่อมต่อ (interface) ระหว่าง servers ภาษา Python ยัง
ทำงานเป็นภาษา CGI (Common Gateway Interface) ดังนั้นเพื่อรันผ่าน Apache web server ต้องนำ
ไฟล์ที่เขียนขึ้นไปเก็บไว้ที่ไดเรกทอรีที่สามารถรันภาษา CGI ได้ ในที่นี้บน Debian 7.7 GNU/Linux
เราจะรันภาษา Python ที่ไดเรกทอรี /usr/lib/cgi-bin
การรันภาษา Python บน Aperche web server เราเพียงใช้คำสั่งข้างล่างนี้สั่งให้แสดงข้อมูล
บน web server ผ่านทางบราวเซอร์ เพียงแต่สั่งคำสั่งแสดงผลไว้ส่วนนำของโปรแกรม
print "Content-Type: text/plain;charset=utf-8"
print
ตัวอย่างไฟล์ ชื่อ test.py เพื่อทดสอบการใช้งานภาษา Python บน Web server รายละเอียด
โปรแกรม มีดังนี้
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
# enable debugging
import cgitb
cgitb.enable()
print "Content-Type: text/plain;charset=utf-8"
print "Hello World! ทดสอบภาษา Python บน Apache web server with Debian 7.7 GNU/Linux"
เมื่อแสดงผลทางบราวเซอร์จะได้ดังภาพ
ลองนำไฟล์ select_data.py มาเพิ่มคำสั่งให้แสดงผลผ่านบราวเซอร์ และเก็บไว้ในไดเรคทอรี
ที่รันภาษา CGI ได้ กำหนดสิทธิ์ให้อ่านเขียนข้อมูลได้ และเรียกใช้งานผ่านบราวเซอร์
รายละเอียดโปรแกรมมี ดังนี้
ที่รันภาษา CGI ได้ กำหนดสิทธิ์ให้อ่านเขียนข้อมูลได้ และเรียกใช้งานผ่านบราวเซอร์
รายละเอียดโปรแกรมมี ดังนี้
#!/usr/bin/python
import psycopg2
print "Content-Type: text/plain;charset=utf-8"
print
conn = psycopg2.connect(database="python", user="submarine", password="xxxxxxxxxxxx", host="127.0.0.1", port="5432")
print "Opened database successfully"
cur = conn.cursor()
cur.execute("SELECT id, name, address, salary from persons")
rows = cur.fetchall()
for row in rows:
print "ID = ", row[0]
print "NAME = ", row[1]
print "ADDRESS = ", row[2]
print "SALARY = ", row[3], "\n"
print "Operation done successfully";
conn.close()
เรียกใช้งานที่ http://localhost/cgi-bin/select_data.py จะได้ผลดังภาพ


ไม่มีความคิดเห็น:
แสดงความคิดเห็น