Web2py

1.簡介

Web2py是一個(gè)開源的全棧web應(yīng)用框架,使用Python編寫。它提供了一套完整的工具和功能,使開發(fā)者能夠快速構(gòu)建、部署和管理Web應(yīng)用。

本文介紹 Web2py 該如何連接使用瀚高數(shù)據(jù)庫。

2.Web2py的應(yīng)用架構(gòu)

  • Models(模型): 數(shù)據(jù)庫交互和業(yè)務(wù)邏輯定義在模型中。Web2py使用Python腳本作為模型文件,負(fù)責(zé)定義數(shù)據(jù)表結(jié)構(gòu)、驗(yàn)證規(guī)則等。
  • Views(視圖): 視圖是用戶界面的呈現(xiàn)部分,使用HTML和Web2py的模板語言創(chuàng)建。
  • Controllers(控制器): 控制器是處理用戶請(qǐng)求的邏輯層。Web2py的控制器是用Python編寫的,負(fù)責(zé)接收用戶輸入,調(diào)用相應(yīng)的模型和視圖,并將結(jié)果返回給用戶。

3.加載 psycopg2

具體操作步驟請(qǐng)參考 Psycopg2 接口說明文檔。

4.創(chuàng)建一個(gè)簡單的 Web2py 應(yīng)用

4.1模型

web2py/applications/<your_app>/models目錄下創(chuàng)建一個(gè)新的Python文件,例如db.py,定義一個(gè)簡單的數(shù)據(jù)表

# models/db.py

db = DAL('postgres://web2py:Qwer1234@192.168.100.101:5866/web2py')

db.define_table('task',
Field('title', requires=IS_NOT_EMPTY()),
Field('description', 'text'),
Field('completed', 'boolean', default=False))

4.2.控制器

web2py/applications/<your_app>/controllers目錄下創(chuàng)建一個(gè)新的Python文件,例如default.py,編寫控制器代碼

# controllers/default.py

def index():
tasks = db().select(db.task.ALL)
return dict(tasks=tasks)

4.3.視圖

web2py/applications/<your_app>/views目錄下創(chuàng)建一個(gè)新的HTML文件,例如index.html,使用Web2py的模板語言呈現(xiàn)數(shù)據(jù)

<!-- views/default/index.html -->

{{extend 'layout.html'}}

<h2>Task List</h2>

<table>
<tr>
<th>Title</th>
<th>Description</th>
<th>Completed</th>
</tr>
{{for task in tasks:}}
<tr>
<td>{{=task.title}}</td>
<td>{{=task.description}}</td>
<td>{{='Yes' if task.completed else 'No'}}</td>
</tr>
{{pass}}
</table>

5.啟動(dòng)Web應(yīng)用

重新啟動(dòng)Web2py應(yīng)用,訪問http://127.0.0.1:8000/<your_app>/default/index,你將看到一個(gè)簡單的任務(wù)列表頁面。