当前位置:网站首页>Quick start CherryPy (1)
Quick start CherryPy (1)
2022-06-27 09:08:00 【Denglong】

CherryPy It's a lightweight python Network framework , Used to create web applications . Such as rapid implementation api Interface 、 Do the back end of the website . Sense and flask almost .
The simplest example
The following code creates a class “HelloWorld”, Defined a cherryPy Application , And then through quickstart Method to start the application
import cherrypy
class HelloWorld(object):
@cherrypy.expose
def index(self):
return "Hello world!"
if __name__ == '__main__':
cherrypy.quickstart(HelloWorld())After execution , Open the browser , You can see the output ”Hello World” word
Implement the second interface
On top of that , We add a second interface , Realize the function of generating random string .
import random
import string
import cherrypy
class StringGenerator(object):
@cherrypy.expose
def index(self):
return "Hello World!"
@cherrypy.expose
def generate(self):
return ''.join(random.sample(string.hexdigits, 8))
if __name__ == '__main__':
cherrypy.quickstart(StringGenerator())Then we visit the browser http://127.0.0.1/generate You can see the randomly generated string .
Combined with these two examples, we can see ,@cherrypy.expose Decorator decorated functions will be exposed , Become an independent interface . also ,index Function will be used as interface ’/’ The objective function of the route . The rest of the exposed functions will be routed by their function names .
What if the interface has parameters ?
To implement an interface with parameters , Just specify the parameter name in the input parameter of the function .
The code looks like this :
import random
import string
import cherrypy
class StringGenerator(object):
@cherrypy.expose
def index(self):
return "Hello World!"
@cherrypy.expose
def generate(self, length=16):
return ''.join(random.sample(string.hexdigits, int(length)))
if __name__ == '__main__':
cherrypy.quickstart(StringGenerator())This is the time , If we visit directly http://127.0.0.1:8080/generate The default parameters will be used length=16, Generate a length of 16 String . If we use such a link to access :
http://127.0.0.1:8080/generate?length=19
Then a length of 19 String .URL The input format of the parameter in is , The first parameter is preceded by a ?, Then each of the following parameters is key=value The format of . If our function has multiple arguments , You only need to add one between the parameters & It can be connected .
Create a simple form
next , We can create a simple form page to enter this length
Our code changes to this :
import random
import string
import cherrypy
class StringGenerator(object):
@cherrypy.expose
def index(self):
return """<html>
<head></head>
<body>
<form method="get" action="generate">
<input type="text" value="8" name="length" />
<button type="submit">Give it now!</button>
</form>
</body>
</html>"""
@cherrypy.expose
def generate(self, length=16):
return ''.join(random.sample(string.hexdigits, int(length)))
if __name__ == '__main__':
cherrypy.quickstart(StringGenerator())It should be noted that , The form here uses GET Method , Therefore, the parameter will be added to URL above . Finally generated URL The same format as before .
Enable Session
Session It's very common , We can go through Session To identify the different clients that interact with the server .CherryPy Chinese vs Session Have support . The following code demonstrates that in CherryPy Enable Session Middleware and set it manually Session
import random
import string
import cherrypy
class StringGenerator(object):
@cherrypy.expose
def index(self):
return """<html>
<head></head>
<body>
<form method="get" action="generate">
<input type="text" value="8" name="length" />
<button type="submit">Give it now!</button>
</form>
</body>
</html>"""
@cherrypy.expose
def generate(self, length=16):
s = ''.join(random.sample(string.hexdigits, int(length)))
# Store in session in
cherrypy.session['mystring'] = s
return s
@cherrypy.expose
def display(self):
return cherrypy.session['mystring']
if __name__ == '__main__':
conf = {
'/': {
'tools.sessions.on': True, # stay cherryPy Enable session
}
}
cherrypy.quickstart(StringGenerator(), '/', conf)In the code above , We are conf Enabled in the dictionary sessions middleware , Then this conf Pass in cherryPy
We first generate a random string , Then save it to Session Of mystring in , Then you can visit display To show this session Field
It should be noted that , By default, the server memory is used to store session Value . in fact ,CherryPy There are also other storage back ends to choose from .
Introduce static files
Our website will contain some static files more or less .cherrypy adopt tools.staticdir It supports the introduction of static files .
First we need to create a static css file , be called style.css Just go . Placed in the current directory public/css/ Under the folder .
style.css:
body {
background-color: blue;
}next , We put conf Change the name to :
conf = {
'/': {
'tools.sessions.on': True, # stay cherryPy Enable session
'tools.staticdir.root': os.path.abspath(os.getcwd()), # Set the root directory of static files
},
# Set to static Everything at the beginning is static , And put URL Mapping to public Catalog
'/static': {
'tools.staticdir.on': True,
'tools.staticdir.dir': './public', # Set the folder for static files
}
}In this code , First of all ’/’ Of all directories at the beginning staticdir Root directory . For security reasons ,CherryPy The path here is required to be absolute .
And then we specify that ’/static’ All of the beginning URL Are static resources , And the corresponding url Mapping to public Catalog .
Finally, we put index Back to html Change it , introduce style.css, You can see the effect . It should be a page with a blue background .( It's ugly though )
@cherrypy.expose
def index(self):
return """<html>
<head>
<link href="/static/css/style.css" rel="stylesheet">
</head>
<body>
<form method="get" action="generate">
<input type="text" value="8" name="length" />
<button type="submit">Give it now!</button>
</form>
</body>
</html>"""
This one goes here first , The rest will continue to write another article tomorrow ~
Please indicate the original : Quick start CherryPy(1) | | Longjin's blog
https://longjin666.cn/?p=1438
Welcome to my official account. : Denglong
Let's explore more interesting things together !

边栏推荐
- 快速入门CherryPy(1)
- JVM common garbage collector
- 数字IC-1.9 吃透通信协议中状态机的代码编写套路
- ucore lab4
- MATLAB小技巧(18)矩阵分析--熵权法
- Redis master-slave replication and sentinel mode
- 粗读DS-TransUNet: Dual Swin Transformer U-Net for Medical Image Segmentation
- 高等数学第七章微分方程
- Rough reading DS transunet: dual swing transformer u-net for medical image segmentation
- Fake constructor???
猜你喜欢

MySQL lock details

不容置疑,这是一个绝对精心制作的项目

高等数学第七章微分方程

(original) custom drawable

Digital ic-1.9 understands the coding routine of state machine in communication protocol

The markdown plug-in of the browser cannot display the picture

我大抵是卷上瘾了,横竖睡不着!竟让一个Bug,搞我两次!

Oracle uses an SQL to find out which data is not in a table

0号进程,1号进程,2号进程

ucore lab5
随机推荐
ucore lab3
How Oracle converts strings to multiple lines
fastadmin 安装后访问后台提示模块不存在
[cloud native] 2.3 kubernetes core practice (Part 1)
Rockermq message sending and consumption mode
ServletConfig and ServletContext
VIM from dislike to dependence (19) -- substitution
Preliminary understanding of pytorch
Redis master-slave replication and sentinel mode
内部类~锁~访问修饰符
Introduction to websocket protocol
AQS underlying source code of concurrent programming JUC
多网络设备存在时,如何配置其上网优先级?
Flow chart of Alipay wechat payment business
[diffusion model]
I'm almost addicted to it. I can't sleep! Let a bug fuck me twice!
我大抵是卷上瘾了,横竖睡不着!竟让一个Bug,搞我两次!
HiTek电源维修X光机高压发生器维修XR150-603-02
main()的参数argc与argv
The background prompt module for accessing fastadmin after installation does not exist