1. 基本结构,采用 MVC 模式。
控制器(controller)负责转发请求,对请求进行处理
视图 (View): 界面设计人员进行图形界面设计。
模型 (Model): 程序员编写程序应有的功能(实现算法等)、数据库管理
2。一个基本架势
做一个基本的框架,建立好各级目录 /. handlers methods statics templates application.py server.py url.py
handler: 我准备在这个文件夹中放后端 python 程序,主要处理来自前端的请求,并且操作数据库。
method: 这里准备放一些函数或者类,比如用的最多的读写数据库的函数,这些函数被 handlers 里面的程序使用。
staics: 这里准备放一些静态文件,比如图片、css\JavaScript文件等
template: 这里放模板文件,都以html为扩展名
2.1 url.py 主要设置网站的目录结构
#!/usr/bin/env python
# coding=utf-8
"""
the url structure of website
"""
import sys
reload (sys)
sys.setdefaultencoding("utf-8")
from handlers.index import IndexHandler
url = [
(r'/',IndexHandler),
]
2.2 application.py 该文件完成了对网站系统的基本配置,建立网站请求处理集合
#!/usr/bin/env python
#coding:utf-8
from url import url
import tornado.web
import os
settings = dict(
template_path = os.path.join(os.path.dirname(__file__),"templates"),
static_path = os.path.join(os.path.dirname(__file__),"statics")
)
application = tornado.web.Application(
handlers = url,
**settings
)
2.3 server.py 作用是将tornado服务器运行起来,并且囊括前面两个文件的对象属性设置。
#!/usr/bin/env/python
#coding:utf-8
import tornado.ioloop
import tornado.options
import tornado.httpserver
from application import application
from tornado.options import define,options
define("port",default = 8088 , help = "run on the given port" , type = int)
def main():
tornado.options.parse_command_line()
http_server = tornado.httpserver.HTTPServer(application)
http_server.listen(options.port)
print "Development server is running at http://127.0.0.1:%s" % options.port
print "Quit the server with Control-C"
tornado.ioloop.IOLoop.instance().start()
if __name__ == "__main__":
main()
2.4 登录界面 index.html
<! DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title>Learming Python</title>
</head>
<body>
<h2>Login</h2>
<form method="POST">
<p><span>UserName:</span><input type = "text" id = "username" /></p>
<p><span>Password:</span><input type = "text" id = "password" /></p>
<p><input type="BUTTON" value="LOGIN" id ="login" /></p>
</form>
</body>
</html>