基于兴趣尝试使用Python开发语言搭建一个基础的web框架,本次采用的方案是集成tornado方式。项目源码
系统需要具备以下开发环境:
如果当前的环境里没有tornado依赖库,使用以下命令安装
pip install tornado
需具备上述开发环境后,方可进入以下搭建流程。推荐使用PyCharm开发工具,也可以使用其他的开发工具替代。
config.py:项目环境的基础配置文件
application.py:自定义tornado Application启动类,自定义相关的配置等
server.py:项目的启动类
views:项目的路由定义及相关业务处理的目录,类似SpringBoot中的controller
static:该目录为项目的静态资源目录,用于存放js/css/img等静态资源
templates:该目录为项目的模板页面资源文件,用于渲染相关的显示页面
upfile:该目录为项目的文件上传基础目录
该文件统一管理项目的配置文件,包含启动的端口,tornado支持的一些web启动配置参数,项目的请求路由注册等。
import os
"""
#config
配置参数
"""
options = {
"port": 8080
}
"""
#config
配置文件,相当于django里面的setting
配置application应用程序路由,即文件地址路径
BASE_DIRS = os.path.dirname(__file__)
当前file文件路径
##os.path.join(BASE_DIRS,"static")
拼接路径:如(BASE_DIRS/static),当然BASE_DIRS=当前文件的父类的文件路径
"""
BASE_DIRS = os.path.dirname(__file__)
print("******config******")
print("BASE_DIRS",BASE_DIRS)
"""
静态路由配置
"""
STATIC_ROUTERS_CONFIGS = {
"STATIC_PATH":os.path.join(BASE_DIRS,"static"),
"CSS_URL": os.path.join(BASE_DIRS,"static","css"),
"JS_URL":os.path.join(BASE_DIRS,"static","js"),
"IMG_URL":os.path.join(BASE_DIRS,"static","img")
}
"""
tornado配置
"""
settings = {
"static_path": os.path.join(BASE_DIRS, "static"), # 静态文件
# "static_url_prefix": "/static",
"template_path": os.path.join(BASE_DIRS, "templates"), # 视图
"compiled_template_cache":True,
"autoescape":None,
"debug": True,
"cookie_secret": "OrGWKG+lTja4QD6jkt0YQJtk+yIUe0VTiy1KaGBIuks",
"xsrf_cookies": True,
"login_url": "/login"
}
import tornado.web
import os
import config
from views import *
from config import settings
from tornado.web import StaticFileHandler,URLSpec
"""
创建Application
"""
class MainApplication(tornado.web.Application):
def __init__(self):
# BASE HANDLERS
handlers = [
# 静态文件
URLSpec(r"/static/(.*)", StaticFileHandler, {"path": config.STATIC_ROUTERS_CONFIGS["STATIC_PATH"]}),
URLSpec(r"/css/(.*)", StaticFileHandler, {"path": config.STATIC_ROUTERS_CONFIGS["CSS_URL"]}),
URLSpec(r"/js/(.*)", StaticFileHandler, {"path": config.STATIC_ROUTERS_CONFIGS["JS_URL"]}),
URLSpec(r"/img/(.*)", StaticFileHandler, {"path": config.STATIC_ROUTERS_CONFIGS["IMG_URL"]}),
]
# SERVICE HANDLERS
handlers.extend(all_router_configs())
super().__init__(handlers=handlers, **settings)
print("******tornado web application configs******")
print("handlers", handlers)
print("setting", config.settings)
项目的启动入库类server.py,启动命令:python server.py
import tornado.web
import tornado.ioloop
import tornado.httpserver
import tornado.options
import config #导入自定义配合的py文件
import application #导入自定义的应用程序模块
"""
server服务配置
"""
if __name__ == "__main__":
app = application.MainApplication()
httpServer = tornado.httpserver.HTTPServer(app)
httpServer.bind(config.options["port"])
httpServer.start(1)
print("server success start, port:",config.options["port"])
tornado.ioloop.IOLoop.current().start()
views目录为项目所有的路由定义的地方及相关业务处理的模块,建议按业务模块化的方式管理。
接口统一定义获取注册路由方法,便于获取每个handler注册的路由配置。
"""
统一定义路由配置URL
"""
from abc import ABCMeta,abstractmethod
"""
定义公共的路由方法
"""
class ViewRouterInterface(metaclass=ABCMeta):
"""
配置路由,要求返回数组行驶
"""
@abstractmethod
def configRouter(self):
raise NotImplementedError
"""
请求路由定义及相关的业务处理
Handler相当于Web中的Controller
ViewRouterInterface定义了获取路由配置的统一接口
即configRouter方法返回路由配置数组
"""
print("******start to import view Request Handler packages******")
from views.test.TestHandlerKit import TestHandler
from views.index.index import IndexHandler,LoginHandler
from views.upload.UploadUtilsHandlerKit import UploadFileHandler
# 定义所有的RequestHandler
ALL_HANDLERS = [
TestHandler,IndexHandler,LoginHandler,UploadFileHandler
]
"""
获取所有的路由
"""
def all_router_configs():
allRouters = []
for viewRouterInterface in ALL_HANDLERS:
routerConfigs = viewRouterInterface.configRouter(viewRouterInterface)
if routerConfigs is None:
continue
allRouters.extend(routerConfigs)
print("ALL ROUTER CONFIGS",allRouters)
return allRouters
from tornado.web import RequestHandler
from views.ViewRouterInterface import ViewRouterInterface
"""
Test view
"""
class TestHandler(ViewRouterInterface,RequestHandler):
# 配置路由
def configRouter(self):
return [
(r"/test",TestHandler)
]
# Get方法
def get(self):
items = ["item1", "item2", "item3"]
items2 = ["item1", "item2"]
def checked(item):
return 'checked=checked' if item in items2 else ''
self.render("test/test.html", items=items, add=add, items2=items2, checked=checked)
"""
Html Page Function
"""
def add(x, y):
return (x+y)
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Test1 HTMLtitle>
head>
<body>
{% for item in items %}
<li>{{ escape(item) }}li>
<li>
<input value={{item}} name={{item}} type="checkbox"
{{checked(item)}}
/> {{item}}
li>
{% end %}
add func test: 2+2={{ add(2,2) }}
body>
html>
启动方式:
python server.py
工作之余学习了解下如何基于python开发语言实现一个web开发框架,若有不足或者错误之处,请多多指教!!!