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

边栏推荐
- Getting started with webrtc: 12 Rtendpoint and webrtcendpoint under kurento
- 我大抵是卷上瘾了,横竖睡不着!竟让一个Bug,搞我两次!
- Understanding mvcc in MySQL transactions is super simple
- Matlab tips (19) matrix analysis -- principal component analysis
- June 26, 2022 (LC 6100 counts the number of ways to place houses)
- Design of a solar charge pump power supply circuit
- 2022.06.26(LC_6100_统计放置房子的方式数)
- IO管脚配置和pinctrl驱动
- Object contains copy method?
- 有关二叉树的一些练习题
猜你喜欢
![[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

ucore lab4

This, constructor, static, and inter call must be understood!

I'm almost addicted to it. I can't sleep! Let a bug fuck me twice!

ServletConfig and ServletContext

Correctly understand MySQL mvcc

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

提高效率 Or 增加成本,开发人员应如何理解结对编程?

经典的一道面试题,涵盖4个热点知识

One week's experience of using Obsidian (configuration, theme and plug-in)
随机推荐
When multiple network devices exist, how to configure their Internet access priority?
经典的一道面试题,涵盖4个热点知识
Rman-08137 main library failed to delete archive file
Redis configuration file details
win10为任意文件添加右键菜单
fastadmin 安装后访问后台提示模块不存在
Win10 add right-click menu for any file
[vivid understanding] the meanings of various evaluation indicators commonly used in deep learning TP, FP, TN, FN, IOU and accuracy
Conception de plusieurs classes
Summary of three basic interview questions
[MySQL basic] general syntax 1
冒牌构造函数???
Fake constructor???
Creation process and memory layout of objects at JVM level
June 26, 2022 (LC 6100 counts the number of ways to place houses)
【云原生】2.3 Kubernetes 核心实战(上)
The largest rectangle in the bar graph of force buckle 84
Rockermq message sending and consumption mode
有关二叉树的一些练习题
2022.06.26 (LC Luo 6101 Luo determines whether the matrix is an X matrix)