当前位置:网站首页>快速入门CherryPy(1)
快速入门CherryPy(1)
2022-06-27 08:55:00 【灯珑】

CherryPy是一个轻量级的python网络框架,用来创建网络应用。比如快速实现api接口、做网站后端这样。感觉和flask差不多。
最简单的一个例子
下面这段代码通过创建一个类“HelloWorld”,定义了一个cherryPy的应用,然后通过quickstart方法启动这个应用
import cherrypy
class HelloWorld(object):
@cherrypy.expose
def index(self):
return "Hello world!"
if __name__ == '__main__':
cherrypy.quickstart(HelloWorld())执行后,打开浏览器,可以看到输出的”Hello World”字样
实现第二个接口
在上面的基础上,我们增加第二个接口,实现了生成随机字符串的功能。
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())然后我们访问浏览器的http://127.0.0.1/generate 就能看到随机生成的字符串。
结合这两个例子我们可以看到,@cherrypy.expose装饰器修饰的函数会被暴露出去,成为独立的接口。并且,index函数将会作为接口的’/’路由的目标函数。其余的被暴露的函数就会以其函数名作为路由。
如果接口带有参数怎么办?
要实现一个带有参数的接口,只需要在函数的输入参数里面指定参数名称即可。
代码长这样:
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())这个时候,我们如果直接访问http://127.0.0.1:8080/generate 则会使用默认的参数length=16,生成一个长度为16的字符串。如果我们使用这样的链接来访问:
http://127.0.0.1:8080/generate?length=19
那么就会返回一个长度为19的字符串。URL中参数的输入格式就是,第一个参数前面带有一个?,然后后面的每个参数都是key=value的格式。如果我们的函数具有多个参数,只需要在参数之间增加一个&就可以连起来了。
创建一个简单的表单
接着,我们可以创建一个简单的表单页面来输入这个length
我们的代码改成这样的:
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())需要注意的是,这里的表单采用的是GET方法,因此会将参数加到URL上面。最终生成的URL和前面的格式相同。
启用Session
Session是很常见的,我们可以通过Session来辨别与服务器交互的不同的客户端。CherryPy中对Session具有支持。下面的代码演示了在CherryPy中启用Session中间件并手动设置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)))
# 存储到session中
cherrypy.session['mystring'] = s
return s
@cherrypy.expose
def display(self):
return cherrypy.session['mystring']
if __name__ == '__main__':
conf = {
'/': {
'tools.sessions.on': True, # 在cherryPy中启用session
}
}
cherrypy.quickstart(StringGenerator(), '/', conf)在上面的代码中,我们在conf字典中启用了sessions中间件,随后将这个conf传入cherryPy
我们先是生成一个随机字符串,然后将它存到Session的mystring中,然后可以通过访问display来显示这个session字段
需要注意的是,这里默认采用服务器内存来存储session的值。事实上,CherryPy还提供了其他存储后端可以选择。
引入静态文件
我们的网站或多或少会包含一些静态文件。cherrypy通过tools.staticdir为静态文件的引入提供了支持。
首先我们需要创建一个静态的css文件,叫做style.css就行。放置在当前目录下的public/css/文件夹下。
style.css:
body {
background-color: blue;
}接着,我们把conf更改称这样:
conf = {
'/': {
'tools.sessions.on': True, # 在cherryPy中启用session
'tools.staticdir.root': os.path.abspath(os.getcwd()), # 设置静态文件的根目录
},
# 设置以static开头的所有内容都是静态内容,并把URL映射到public目录
'/static': {
'tools.staticdir.on': True,
'tools.staticdir.dir': './public', # 设置静态文件的文件夹
}
}这段代码中,首先指定了’/’开头的所有目录的staticdir的根目录。出于安全性考虑,CherryPy要求这里的路径是绝对路径。
接着就指定以’/static’开头的所有URL都是静态资源,并将对应的url映射到public目录。
最后我们把index返回的html改一下,引入style.css,就能看到效果了。应该是一个蓝色背景的页面。(虽然但是挺丑的)
@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>"""
这篇先写到这里,剩下的明天开另一篇继续写~
转载请注明原文:快速入门CherryPy(1) | | 龙进的博客
https://longjin666.cn/?p=1438
欢迎关注我的公众号:灯珑
我们一起探索更多有趣的事物!

边栏推荐
- The markdown plug-in of the browser cannot display the picture
- Tips for using Jupiter notebook
- Static code block vs construction code block
- 关于el-date-picker点击清空参数变为null的问题
- Process 0, process 1, process 2
- 我大抵是卷上瘾了,横竖睡不着!竟让一个Bug,搞我两次!
- VIM from dislike to dependence (19) -- substitution
- oracle用一条sql查出哪些数据不在某个表里
- 【mysql篇-基础篇】通用语法1
- June 26, 2022 (LC 6100 counts the number of ways to place houses)
猜你喜欢

Matlab tips (18) matrix analysis -- entropy weight method

MATLAB小技巧(18)矩阵分析--熵权法
![[vivid understanding] the meanings of various evaluation indicators commonly used in deep learning TP, FP, TN, FN, IOU and accuracy](/img/d6/119f32f73d25ddd97801f536d68752.png)
[vivid understanding] the meanings of various evaluation indicators commonly used in deep learning TP, FP, TN, FN, IOU and accuracy

Semi-supervised Learning入门学习——Π-Model、Temporal Ensembling、Mean Teacher简介

力扣84柱状图中最大的矩形

NoSQL database redis installation

100%弄明白5种IO模型

Rockermq message sending and consumption mode
![[cloud native] 2.3 kubernetes core practice (Part 1)](/img/f8/dbd2546e775625d5c98881e7745047.png)
[cloud native] 2.3 kubernetes core practice (Part 1)

Redis installation under Linux
随机推荐
ThreadLocal再次挖掘它的知识点
Redis的事务
The largest rectangle in the bar graph of force buckle 84
0号进程,1号进程,2号进程
oracle怎样将字符串转为多行
Redis五种基本类型
this,构造器,静态,之间调用,必须搞懂啊!
Parameters argc and argv of main()
Redis master-slave replication and sentinel mode
Improving efficiency or increasing costs, how should developers understand pair programming?
ucore lab3
Fake constructor???
提高效率 Or 增加成本,开发人员应如何理解结对编程?
ThreadLocal digs its knowledge points again
Markem imaje马肯依玛士喷码机维修9450E打码机维修
Chapter 11 signal (I) - concept
vim 从嫌弃到依赖(20)——global 命令
【生动理解】深度学习中常用的各项评价指标含义TP、FP、TN、FN、IoU、Accuracy
MATLAB小技巧(19)矩阵分析--主成分分析
March into machine learning -- Preface