1. Introduction
To build Java Web projects, you need Tomcat server to do it. And build Python Web projects, because cherrypy comes with a server, so you only need to download the module to carry out Web project development.
2. Minimum usage
Realization function: visit html page, click the button to receive the value returned by the backend py
html page (test_cherry.html)
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>Test Cherry</title> <script src="/jquery/1.10.2/"></script> </head> <body> <h1>Test Cherry</h1> <p ></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>
Write script py
# -*- encoding=utf-8 -*- import cherrypy class TestCherry(): @() # Ensure that html can request the function def hello_world(self): print('Hello') return 'Hello World' @() # Ensure html can request this function http://127.0.0.1:8080/index def index(self): # Default page is test_cherry.html return open(u'test_cherry.html') (TestCherry(), '/')
running result
[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
I can see that the startup path is 127.0.0.1::8080 and the port number is 8080.
The Application mounted at '' has an empty config. indicates that there is no self-configuration, using the default configuration, if necessary, you can configure yourself.
After running the py script, open your browser and type http://127.0.0.1:8080/orhttp://127.0.0.1:8080/indexThen you can seetest_cheery.html
Clicking the hello_world button accesses the hello_world function in py
Explanation: in test_cherry.html
function callHelloWorld() {
$.get('/hello_world', function (data, status) {
alert('data:' + data)
alert('status:' + status)
})}
1) The request /hello_world needs to match the function name in py
2) The default port is 8080, if 8080 is occupied, you can reconfigure the
(TestCherry(), '/') can receive configuration parameters
If you debug multiple times, you get the error: Port 8080 not free on 127.0.0.1.
It's because port 8080 is occupied, if you succeed in debugging for the first time, then you can open the task manager to stop the python process, and 8080 will be released.
3, import webbrowser for debugging development (you can automatically open the browser, enter the URL)
py code
# -*- encoding=utf-8 -*- import cherrypy import webbrowser class TestCherry(): @() # Ensure that html can request the function def hello_world(self): print('Hello') return 'Hello World' @() # Ensure html can request this function http://127.0.0.1:8080/index def index(self): # Default page is test_cherry.html return open(u'test_cherry.html') def auto_open(): ('http://127.0.0.1:8080/') ('start', auto_open) # Call auto_open function every time before startup (TestCherry(), '/')
Running py in this way will automatically open the web page, each time you change the html code if you don't get the desired effect, try clearing your browser cache!!!!
4. Requests with parameters
Implemented to pass parameters and receive the return to be displayed on the html
Add a function to py (get_parameters)
# -*- encoding=utf-8 -*- import cherrypy import webbrowser class TestCherry(): @() # Ensure that html can request the function def hello_world(self): print('Hello') return 'Hello World' @() # Ensure html can request this function http://127.0.0.1:8080/index def index(self): # Default page is test_cherry.html return open(u'test_cherry.html') @() 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(): ('http://127.0.0.1:8080/') ('start', auto_open) # Call auto_open function every time before startup (TestCherry(), '/')
Add a new button and corresponding button event in html
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>Test Cherry</title> <script src="/jquery/1.10.2/"></script> </head> <body> <h1>Test Cherry</h1> <p ></p> <button type="button" onclick="callHelloWorld()">hello_world</button> <button type="button" >get_parameters</button> <p ></p> <script> function callHelloWorld() { $.get('/hello_world', function (data, status) { alert('data:' + data) alert('status:' + status) }) } $(document).ready(function () { $('#postForParameters').click(function () { alert('pst') $.post('/get_parameters', { name: 'TXT', age: 99, other: '123456' }, function (data, status) { if (status === 'success') { $('#getReturn').text(data) } }) }) }) </script> </body> </html>
running result
After clicking the get_parameters button
D:\Python37_32\ 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 / 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 / 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"
You can see that the incoming parameters have been printed out
5. config configuration and the corresponding url (append, so the code is different)
# -*- encoding=utf-8 -*- import json import os import webbrowser import cherrypy class Service(object): def __init__(self, port): self.media_folder = (((), 'media')) = '0.0.0.0' = int(port) self.index_html = '' pass @() def index(self): return open((self.media_folder, self.index_html), 'rb') def auto_open(self): ('http://127.0.0.1:{}/'.format()) @() def return_info(self, sn): ['Content-Type'] = 'application/json' ['Access-Control-Allow-Origin'] = '*' my_dict = {'aaa':'123'}# Or use list[] to keep things organized. return (my_dict).encode('utf-8') def main(): service = Service(8090) conf = { 'global': { # Host 0.0.0.0 means that it can be accessed using a local IP, such as http://10.190.20.72:8090, which can be deployed for access by others # Otherwise only http://127.0.0.1:8090 'server.socket_host': , # Port number 'server.socket_port': , # Whether to restart the service automatically when the code changes, True==Yes, False==No # When set to True, the service restarts when this PY code changes '': False }, # Root directory settings '/': { '': True, '': service.media_folder }, '/static': { '': True, # You can access http://127.0.0.1:8090/staticPlus your resources this way, for example # http://127.0.0.1:8090/static/js/jquery-1.11. '': service.media_folder }, } # Instead of config, you can use this style of writing # ( # {'server.socket_port': }) # ( # {'server.thread_pool': int(service.thread_pool_count)}) # Whether to restart the service when the code changes, True==Yes, False==No # ({'': False}) # Support http://10.190.20.72:8080/format # .socket_host = '0.0.0.0' # Call the function at startup ('start', service.auto_open) (service, '/', conf) if __name__ == '__main__': pass main()
Project Folder
This is the whole content of this article, I hope it will help you to learn more.