Python Web專案Cherrypy使用方法映象
1、介紹
搭建Java Web專案,需要Tomcat伺服器才能進行。而搭建Python Web專案,因為cherrypy自帶伺服器,所以只需要下載該模組就能進行Web專案開發。
2、最基本用法
實現功能:訪問html頁面,點選按鈕後接收後臺py返回的值
html頁面(test_cherry.html)
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>Test Cherry</title> <script src="https://cdn.staticfile.org/jquery/1.10.2/jquery.min.js"></script> </head> <body> <h1>Test Cherry</h1> <p id="p1"></p> <button type="button" onclick="callHelloWorld()">hello_world</button> <script> function callHelloWorld() { $.get('/hello_world',function (data,status) { alert('data:' + data) alert('status:' + status) }) } </script> </body> </html>
編寫指令碼py
# -*- encoding=utf-8 -*- import cherrypy class TestCherry(): @cherrypy.expose() # 保證html能請求到該函式 def hello_world(self): print('Hello') return 'Hello World' @cherrypy.expose() # 保證html能請求到該函式http://127.0.0.1:8080/index def index(self): # 預設頁為test_cherry.html return open(u'test_cherry.html') cherrypy.quickstart(TestCherry(),'/')
執行結果
[27/May/2020:09:04:42] ENGINE Listening for SIGTERM.
[27/May/2020:09:04:42] ENGINE Bus STARTING
CherryPy Checker:
The Application mounted at '' has an empty config.[27/May/2020:09:04:42] ENGINE Set handler for console events.
[27/May/2020:09:04:42] ENGINE Started monitor thread 'Autoreloader'.
[27/May/2020:09:04:42] ENGINE Serving on http://127.0.0.1:8080[27/May/2020:09:04:42] ENGINE Bus STARTED
能看到啟動的路徑為127.0.0.1::8080埠號是8080
The Application mounted at '' has an empty config.表示沒有自己配置,使用預設配置,如果需要可自己配置
執行py指令碼後,開啟瀏覽器輸入http://127.0.0.1:8080/或者http://127.0.0.1:8080/index就可以看到test_cheery.html
點選hello_world按鈕,就會訪問py中的hello_world函式
解釋:test_cherry.html中
function callHelloWorld() {
$.get('/hello_world',status) {
alert('data:' + data)
alert('status:' + status)
})}
1)請求/hello_world需要與py中的函式名一致
2)預設埠是8080,如果8080被佔用,可以重新配置
cherrypy.quickstart(TestCherry(),'/')可以接收配置引數
若多次調試出現portend.Timeout: Port 8080 not free on 127.0.0.1.錯誤
是因為8080埠被佔用了,如果你第一次除錯時成功了,則你可以開啟工作管理員把python程序停掉,8080就被釋放了
3、匯入webbrowser進行除錯開發(可以自動開啟瀏覽器,輸入網址)
py程式碼
# -*- encoding=utf-8 -*- import cherrypy import webbrowser class TestCherry(): @cherrypy.expose() # 保證html能請求到該函式 def hello_world(self): print('Hello') return 'Hello World' @cherrypy.expose() # 保證html能請求到該函式http://127.0.0.1:8080/index def index(self): # 預設頁為test_cherry.html return open(u'test_cherry.html') def auto_open(): webbrowser.open('http://127.0.0.1:8080/') cherrypy.engine.subscribe('start',auto_open) #啟動前每次都呼叫auto_open函式 cherrypy.quickstart(TestCherry(),'/')
這樣執行py就能自動開啟網頁了,每次改變html程式碼如果沒達到預期效果,可以試一試清理瀏覽器快取!!!
4、帶引數的請求
實現傳入引數並接收返回顯示在html上
py中新增一個函式(get_parameters)
# -*- encoding=utf-8 -*- import cherrypy import webbrowser class TestCherry(): @cherrypy.expose() # 保證html能請求到該函式 def hello_world(self): print('Hello') return 'Hello World' @cherrypy.expose() # 保證html能請求到該函式http://127.0.0.1:8080/index def index(self): # 預設頁為test_cherry.html return open(u'test_cherry.html') @cherrypy.expose() def get_parameters(self,name,age,**kwargs): print('name:{}'.format(name)) print('age:{}'.format(age)) print('kwargs:{}'.format(kwargs)) return 'Get parameters success' def auto_open(): webbrowser.open('http://127.0.0.1:8080/') cherrypy.engine.subscribe('start',auto_open) # 啟動前每次都呼叫auto_open函式 cherrypy.quickstart(TestCherry(),'/')
html中新增一個新按鈕和對應按鈕事件
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>Test Cherry</title> <script src="https://cdn.staticfile.org/jquery/1.10.2/jquery.min.js"></script> </head> <body> <h1>Test Cherry</h1> <p id="p1"></p> <button type="button" onclick="callHelloWorld()">hello_world</button> <button type="button" id="postForParameters">get_parameters</button> <p id="getReturn"></p> <script> function callHelloWorld() { $.get('/hello_world',status) { alert('data:' + data) alert('status:' + status) }) } $(document).ready(function () { $('#postForParameters').click(function () { alert('pst') $.post('/get_parameters',{ name: 'TXT',age: 99,other: '123456' },status) { if (status === 'success') { $('#getReturn').text(data) } }) }) }) </script> </body> </html>
執行結果
點選get_parameters按鈕後
D:\Python37_32\python.exe D:/B_CODE/Python/WebDemo/test_cherry.py
[27/May/2020:09:58:40] ENGINE Listening for SIGTERM.
[27/May/2020:09:58:40] ENGINE Bus STARTING
CherryPy Checker:
The Application mounted at '' has an empty config.[27/May/2020:09:58:40] ENGINE Set handler for console events.
[27/May/2020:09:58:40] ENGINE Started monitor thread 'Autoreloader'.
[27/May/2020:09:58:41] ENGINE Serving on http://127.0.0.1:8080
[27/May/2020:09:58:41] ENGINE Bus STARTED
127.0.0.1 - - [27/May/2020:09:58:41] "GET / HTTP/1.1" 200 1107 "" "Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML,like Gecko) Chrome/83.0.4103.61 Safari/537.36"
127.0.0.1 - - [27/May/2020:09:59:37] "GET / HTTP/1.1" 200 1136 "" "Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML,like Gecko) Chrome/83.0.4103.61 Safari/537.36"
127.0.0.1 - - [27/May/2020:09:59:37] "GET /favicon.ico HTTP/1.1" 200 1406 "http://127.0.0.1:8080/" "Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML,like Gecko) Chrome/83.0.4103.61 Safari/537.36"
127.0.0.1 - - [27/May/2020:10:02:50] "GET / HTTP/1.1" 200 1208 "" "Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML,like Gecko) Chrome/83.0.4103.61 Safari/537.36"
127.0.0.1 - - [27/May/2020:10:02:50] "GET /favicon.ico HTTP/1.1" 200 1406 "http://127.0.0.1:8080/" "Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML,like Gecko) Chrome/83.0.4103.61 Safari/537.36"
name:TXT
age:99
kwargs:{'other': '123456'}
127.0.0.1 - - [27/May/2020:10:02:54] "POST /get_parameters HTTP/1.1" 200 22 "http://127.0.0.1:8080/" "Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML,like Gecko) Chrome/83.0.4103.61 Safari/537.36"
能看出傳入的引數已經打印出來了
5、config配置以及對應url(追加,所以程式碼不同了)
# -*- encoding=utf-8 -*- import json import os import webbrowser import cherrypy class Service(object): def __init__(self,port): self.media_folder = os.path.abspath(os.path.join(os.getcwd(),'media')) self.host = '0.0.0.0' self.port = int(port) self.index_html = 'index.html' pass @cherrypy.expose() def index(self): return open(os.path.join(self.media_folder,self.index_html),'rb') def auto_open(self): webbrowser.open('http://127.0.0.1:{}/'.format(self.port)) @cherrypy.expose() def return_info(self,sn): cherrypy.response.headers['Content-Type'] = 'application/json' cherrypy.response.headers['Access-Control-Allow-Origin'] = '*' my_dict = {'aaa':'123'}# 或者用list[]可保證有序 return json.dumps(my_dict).encode('utf-8') def main(): service = Service(8090) conf = { 'global': { # 主機0.0.0.0表示可以使用本機IP訪問,如http://10.190.20.72:8090,可部署給別人訪問 # 否則只可以用http://127.0.0.1:8090 'server.socket_host': service.host,# 埠號 'server.socket_port': service.port,# 當代碼變動時,是否自動重啟服務,True==是,False==否 # 設為True時,當該PY程式碼改變,服務會重啟 'engine.autoreload.on': False },# 根目錄設定 '/': { 'tools.staticdir.on': True,'tools.staticdir.dir': service.media_folder },'/static': { 'tools.staticdir.on': True,# 可以這麼訪問http://127.0.0.1:8090/static加上你的資源,例如 # http://127.0.0.1:8090/static/js/jquery-1.11.3.min.js 'tools.staticdir.dir': service.media_folder },} # 可以使用該種寫法代替config配置 # cherrypy.config.update( # {'server.socket_port': service.port}) # cherrypy.config.update( # {'server.thread_pool': int(service.thread_pool_count)}) # 當代碼變動時,是否重啟服務,True==是,False==否 # cherrypy.config.update({'engine.autoreload.on': False}) # 支援http://10.190.20.72:8080/形式 # cherrypy.server.socket_host = '0.0.0.0' # 啟動時呼叫函式 cherrypy.engine.subscribe('start',service.auto_open) cherrypy.quickstart(service,'/',conf) if __name__ == '__main__': pass main()
工程資料夾
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支援我們。