python--web.py使用


web.py 是一個輕量級Python web框架。

下面我將使用web.py框架,創建一個簡單的html頁面示例。

 

1.項目的目錄結構如下所示:

exweb2\
  uniqueenv\
  app.py
  templates\

      base.html

      hello_form.html
                 index.html


2.創建網站根目錄exweb2
mkdir exweb2


3.在網站根目錄下創建一個虛擬環境
cd exweb2
virtualenv uniqueenv

 

4.安裝flask
uniqueenv/bin/pip install lpthw.web

 

5.web.py使用,app.py代碼如下

#-*- coding: UTF-8 -*-                                                           
import web 

urls =(
        '/','Index'
)

app = web.application(urls,globals())
 #base為基礎模板頁
render = web.template.render('templates/',base="base")

class Index(object):
         #get方式提交,若url參數不為空,直接跳轉到顯示界面,否則跳轉到輸入信息界面
        def GET(self):
                form = web.input(name="",greet="")
                if form.greet!="" and form.name!="":
                        greeting="%s,%s"%(form.greet,form.name)
                        return render.index(greeting=greeting)
                return render.hello_form()
        #post方式提交表單,
        def POST(self):
                form = web.input(name="Nobody",greet="Hello")
                greeting="%s,%s"%(form.greet,form.name)
                return render.index(greeting=greeting)
if __name__ == "__main__":
        app.run() 

 

 

6.接着創建模板頁,模板放在templates文件夾下.

mkdir templates

首先創建一個基礎模板頁 base.html

$def with (content)                                                              
<html>                                                                               
        <head>
                <title>
                </title>
        </head>
        <body>
                $:content
        </body>
</html>

輸入信息頁 hello_form.html

<h1>Fill out this form</h1>                                                      
<form action="/" method="POST">
A Greeting:<input type="text" name="greet">
<br/>
Your Name:<input type="text" name="name">
<br/>
<input type="submit">
</form>

顯示信息頁 index.html

$def with (greeting)                                                             

$if greeting: 
        I just wanted to say <em style="color: green; font-size: 2em;">$greeting</em>. 
$else: 
        <em>Hello</em>, world!

 

 7.運行:uniqueenv/bin/python app.py

注意運行的時候要使用虛擬目錄中的python解釋器

 

 

8.結果:

(1)Get方式

(2)Post方式

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM