【Python】网络开发之高效Web 框架 - CherryPy 库
CherryPy 简介
CherryPy 是一个用 Python 编写的简单快速的 Web 框架。它是一个高性能的,可以轻松扩展的 Web 服务器,可以支持高负载的应用。CherryPy 主要特点包括:
简单易用:CherryPy 的 API 非常简洁,易于学习和使用。
高效:CherryPy 是一个高性能的 Web 服务器,可以处理大量的请求。
功能强大:CherryPy 包括了多种内置功能,如 URL 路由,模板渲染,会话管理等。
跨平台:CherryPy 可以在各种平台上运行,包括 Windows、Linux、Mac OS。
可扩展:CherryPy 可以通过插件来扩展其功能。
CherryPy 在学习难度和性能方面都有着不错的表现,适用于开发小型的 Web 应用,或作为 Web 服务的后端。
CherryPy 的基本用法
安装 CherryPy:可以通过 pip 安装 CherryPy。命令:
pip install cherrypy。
创建一个 CherryPy 应用:创建一个 Python 文件,导入 CherryPy 模块,并创建一个类来定义一个 CherryPy 应用。
import cherrypy
class HelloWorld(object):
@cherrypy.expose
def index(self):
return "Hello, World!"
cherrypy.quickstart(HelloWorld())
启动 CherryPy 应用:在命令行中运行刚才创建的 Python 文件,启动 CherryPy 应用。
访问 CherryPy 应用:在浏览器中访问 http://localhost:8080/,将会看到“Hello, World!”的输出。
CherryPy 高级用法
CherryPy 的高级用法如下:
URL 路由:CherryPy 支持对请求的 URL 进行路由,从而对请求分配到对应的处理函数。
import cherrypy
class HelloWorld(object):
@cherrypy.expose
def index(self):
return "Hello, World!"
@cherrypy.expose
def greet(self, name):
return "Hello, %s!" % name
cherrypy.quickstart(HelloWorld())
在浏览器中访问
http://localhost:8080/greet/John,将会看到“Hello, John!”的输出。
模板渲染:CherryPy 支持使用模板引擎来渲染页面。
import cherrypy
from jinja2 import Environment, FileSystemLoader
class HelloWorld(object):
@cherrypy.expose
def index(self):
env = Environment(loader=FileSystemLoader('templates'))
template = env.get_template('index.html')
return template.render(name='John')
cherrypy.quickstart(HelloWorld(), '/', 'app.conf')
在 templates 目录中创建一个 index.html 模板文件:
<html>
<body>
<h1>Hello, {{ name }}!</h1>
</body>
</html>
在浏览器中访问 http://localhost:8080/,将会看到“Hello, John!”的输出。
会话管理:CherryPy 支持对会话进行管理,可以存储和读取会话数据。
import cherrypy
class HelloWorld(object):
@cherrypy.expose
def index(self):
count = cherrypy.session.get('count', 0) + 1
cherrypy.session['count'] = count
return "Hello, World! You have accessed this page %d times." % count
cherrypy.quickstart(HelloWorld(), '/', 'app.conf')
在 app.conf 中配置会话:
[/]
tools.sessions.on = True
tools.sessions.storage_type = file
tools.sessions.storage_path = sessions
tools.sessions.timeout = 60
在浏览器中访问 http://localhost:8080/,每次访问该页面,计数器将会增加 1。
数据库支持:CherryPy 支持对数据库进行操作,例如使用 SQLAlchemy 进行数据库操作。
import cherrypy
from sqlalchemy import create_engine, Column, Integer, String
from sqlalchemy.orm import scoped_session, sessionmaker
from sqlalchemy.ext.declarative import declarative_base
Base = declarative_base()
class User(Base):
__tablename__ = 'users'
id = Column(Integer, primary_key=True)
name = Column(String(50))
age = Column(Integer)
engine = create_engine('sqlite:///users.db', convert_unicode=True)
db_session = scoped_session(sessionmaker(autocommit=False,
autoflush=False,
bind=engine))
Base.query = db_session.query_property()
class HelloWorld(object):
@cherrypy.expose
def index(self):
users = User.query.all()
return '\n'.join(['%s, %d' % (user.name, user.age) for user in users])
cherrypy.quickstart(HelloWorld(), '/', 'app.conf')
在 app.conf 中配置数据库连接:
[/]
tools.db.on = True
tools.db.uri = sqlite:///users.db
tools.db.session = cherrypy.lib.sessions.SqlAlchemySession(cherrypy.engine, User.metadata, Base.metadata, cherrypy.engine)
在浏览器中访问 http://localhost:8080/,将会看到所有用户的姓名和年龄。