当前位置:网站首页>快速入门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
欢迎关注我的公众号:灯珑
我们一起探索更多有趣的事物!

边栏推荐
- 我大抵是卷上瘾了,横竖睡不着!竟让一个Bug,搞我两次!
- 使线程释放锁资源的操作/方法重载一点注意事项
- Analysis of key technologies for live broadcast pain points -- second opening, clarity and fluency of the first frame
- Chapter 11 signal (I) - concept
- Rough reading DS transunet: dual swing transformer u-net for medical image segmentation
- fastadmin 安装后访问后台提示模块不存在
- Redis主从复制以及哨兵模式
- Getting started with webrtc: 12 Rtendpoint and webrtcendpoint under kurento
- ThreadLocal digs its knowledge points again
- 粗读DS-TransUNet: Dual Swin Transformer U-Net for Medical Image Segmentation
猜你喜欢

JVM common garbage collector

win10为任意文件添加右键菜单

Analysis of orthofinder lineal homologous proteins and result processing

Redis installation under Linux

MySQL锁详解

Object含有Copy方法?

Getting started with webrtc: 12 Rtendpoint and webrtcendpoint under kurento

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

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

Markem imaje马肯依玛士喷码机维修9450E打码机维修
随机推荐
That is, a one-stop live broadcast service with "smooth live broadcast" and full link upgrade
粗读DS-TransUNet: Dual Swin Transformer U-Net for Medical Image Segmentation
Advanced mathematics Chapter 7 differential equations
Introduction to websocket protocol
AQS underlying source code of concurrent programming JUC
Order by injection of SQL injection
Internal class ~ lock ~ access modifier
我大抵是卷上瘾了,横竖睡不着!竟让一个Bug,搞我两次!
MySQL index details
vim 从嫌弃到依赖(20)——global 命令
Imx8qxp DMA resources and usage (unfinished)
(original) custom drawable
1098 Insertion or Heap Sort(堆排序解释)(PAT甲级)
Linux下Redis的安装
RMAN-08137 主库无法删除归档文件
[diffusion model]
How much do you know about the cause of amplifier distortion?
Redis transactions
招聘需求 视觉工程师
Nosql 数据库 -Redis 安装