最後更新: 2015-01-24
介紹
- Webpy 內建 web server (used for development only)
- 不用 Database 就可獨立運作 (此外, 它 support mysql sqlite ..)
- 支援 WSGI (common API between web servers and applications)
* Version 0.51 is the last release with Python 2.7 support.
功能:
- URL Handle
- Template engine
- Database Connection
- Session state
- Cookie
- GET & POST
目錄
- 安裝
- 10 min 入門
- Make url ending with or without '/' going to the same class.
- Redirect
- Send Mail
- Static content("static" Folder)
- Serving XML(web.header())
- NotFound message
安裝
人手安裝:
wget http://webpy.org/static/web.py-0.37.tar.gz
tar -zxf web.py-0.37.tar.gz
cd web.py-0.37
python setup.py install
過程中它會
- 建立 build 目錄
- byte-compiling (py -> pyc)
- 之後 copy pyc Code 去 /usr/local/lib/python2.6/dist-packages/web
easy_install:
easy_install web.py
Centos 7: v0.37 # epel
yum install python-webpy
pip
pip install web.py==0.37
10 min 入門
* URL Handling
* GET and POST
* Start the server
* Templating
建立 code.py 內容如下
# 載入 webpy 的 framework import web urls = ( '/(.*)', 'index' # regular expressions, class to send the request to ) class index: def GET(self, name): return "Hello, world!" // GET / if __name__ == "__main__": app = web.application(urls, globals()) # tell web.py to create an application with the URLs # looking up the classes in the global namespace of this file app.run() # tell web.py to start serving web pages
測試:
python code.py # 相當於 python code.py 8080
Buildin Web Server
# Runs built-in web server (CherryPy WSGI server) hosting WSGI app func.
python code.py [8080]
* The directory static/ is hosted statically.
* When running with the built-in webserver, it starts the application in debug mode.
(In debug mode any changes to code and templates are automatically reloaded.)
Make url ending with or without '/' going to the same class
# urls '/(.*)/', 'redirect', # code handle '/(.*)/' class redirect: def GET(self, path): web.seeother('/' + path)
Redirect
webpy 一共有兩種 redirect, 分別是
- web.redirect # 301
- web.seeother # 303
i.e.
urls = ( '/sms/','sms', '/(.*)', 'redirect', ) class redirect: def GET(self, path): if path == 'sms': web.seeother('/sms/') return "Server is working" class sms: def GET(self): return "sms page" if __name__ == "__main__": app = web.application(urls, globals()) app.run()
Send Mail
web.sendmail('sender', ['receive1', 'receive2'], cc='user1', bcc='user2', 'subject', 'message', headers=({'User-Agent': 'webpy.sendmail', 'X-Mailer': 'webpy.sendmail',}) )
# headers 是 tuple 來的
出信的 Server:
當在 web.config 內沒有指定 SMTP Server 時, 那就會用系統的 /usr/lib/sendmail
web.config:
web.config.smtp_server = 'YOU_SMTP_SERVER' web.config.smtp_port = 1025 web.config.smtp_username = 'LOGIN_NAME' web.config.smtp_password = 'secret' web.config.smtp_starttls = True
web.sendmail 是支援 SSL 的
i.e. Gmail
web.config.smtp_server = 'smtp.gmail.com' web.config.smtp_port = 587 web.config.smtp_username = '[email protected]' web.config.smtp_password = 'secret' web.config.smtp_starttls = True
P.S.
# sender 一定要是 gmail 的
web.sendmail('[email protected]', '[email protected]', 'subject', 'message')
Static content("static" Folder)
web.py build-in Server
Create a directory called static in the location of the script that runs the web.py server.
Then place the static files you wish to serve in the static folder.
Example:
http://localhost/static/logo.png --> ./static/logo.png
Serving XML(web.header())
$def with (code)
<?xml version="1.0"?>
<RequestNotification-Response>
<Status>$code</Status>
</RequestNotification-Response>
class index:
def GET(self, code):
# tell the client that you are sending a XML file
web.header('Content-Type', 'text/xml')
return render.response(code)
NotFound message
Not Found Page: app.notfound
i.e. 404
def GET(self): raise web.notfound()
i.e.
import web urls = (...) app = web.application(urls, globals()) def notfound(): return web.notfound("Sorry, the page you were looking for was not found.") #return web.notfound(render.notfound()) app.notfound = notfound
Error Page: app.internalerror
def internalerror(): return web.internalerror("Bad, bad server. No donut for you.") app.internalerror = internalerror
Application processors
execute common code before each request is processed
def proc(handle): # do whatever you need to here web.ctx.user = web.cookies(user=None).user # return the executed handle return handle() app = web.application(urls, globals() app.add_processor(proc)
The "handle" of the app processor refers to the code that will be dispatched by the matching URL.