完整堆栈应用程序提供了通过命令或执行文件来创建新应用程序的工具.
考虑像web2py框架这样的Python应用程序;整个项目/应用程序是根据MVC框架创建的.同样,CherryPy允许用户根据需要设置和配置代码的布局.
在本章中,我们将详细了解如何创建CherryPy应用程序并执行它.
文件系统
应用程序的文件系统显示在以下屏幕截图中 :
以下是文件系统中各种文件的简要说明 :
config.py : 每个应用程序都需要配置文件和加载它的方法.此功能可以在config.py中定义.
controllers.py : MVC是用户遵循的流行设计模式. controllers.py是实现将安装在 cherrypy.tree 上的所有对象的地方.
模型.py : 此文件直接与数据库交互以获取某些服务或存储持久数据.
server.py : 此文件与生产就绪的Web服务器交互,该服务器可与负载平衡代理正常工作.
静态 : 它包括所有CSS和图像文件.
视图 : 它包括给定应用程序的所有模板文件.
示例
让我们学习详细介绍了创建CherryPy应用程序的步骤.
步骤1 : 创建一个应该包含该应用程序的应用程序.
步骤2 : 在目录中,创建一个与项目对应的python包.创建gedit目录并在其中包含_init_.py文件.
步骤3 : 在包内,包含具有以下内容的减去的controllers.py文件;
#!/usr/bin/env pythonimport cherrypyclass Root(object): def __init__(self, data): self.data = data @cherrypy.expose def index(self): return 'Hi! Welcome to your application'def main(filename): data = {} # will be replaced with proper functionality later # configuration file cherrypy.config.update({ 'tools.encode.on': True, 'tools.encode.encoding': 'utf-8', 'tools.decode.on': True, 'tools.trailing_slash.on': True, 'tools.staticdir.root': os.path.abspath(os.path.dirname(__file__)), }) cherrypy.quickstart(Root(data), '/', { '/media': { 'tools.staticdir.on': True, 'tools.staticdir.dir': 'static' } })if __name__ == '__main__':main(sys.argv[1])
第4步 : 考虑用户通过表单输入值的应用程序.我们在应用程序中包含两个表单 - index.html和submit.html.
步骤5 : 在上面的控制器代码中,我们有 index(),这是一个默认函数,如果调用了特定的控制器,则首先加载.
步骤6 : index()方法的实现可以通过以下方式更改 :
@cherrypy.expose def index(self): tmpl = loader.load('index.html') return tmpl.generate(title='Sample').render('html', doctype='html')
第7步 : 这将在启动给定应用程序时加载index.html并将其指向给定的输出流. index.html文件如下 :
index.html
Sample Sample Application
Welcome!
第8步 : 如果要创建一个接受名称和标题等值的表单,则必须在 controller.py 中向Root类添加方法.
@cherrypy.expose def submit(self, cancel = False, **value): if cherrypy.request.method == 'POST': if cancel: raise cherrypy.HTTPRedirect('/') # to cancel the action link = Link(**value) self.data[link.id] = link raise cherrypy.HTTPRedirect('/') tmp = loader.load('submit.html') streamValue = tmp.generate() return streamValue.render('html', doctype='html')
第9步 : submit.html中包含的代码如下 :
Input the new link Submit new link