foreword
Today we are going to do web development with Python, and make a simple website. As we all know, the function of the confession wall is generally more about publishing to find someone, lost and found, or a platform where everyone can publicly confess with their favorite people.
A brief introduction to the Tornado framework
In Python, there are three main WEB development frameworks, and today the Tornado framework is mainly used (although this framework is a lightweight framework that few people use)
Install Tornado framework module code
pip install tornado
- Django
- Flask
- Tornado
Tornado Framework Advantages
- Microframework, high performance
- Asynchronous support
Tornado Framework Disadvantages
- Fewer wheels, unlike Django and other frameworks that support a large number of plugins
- Lack of the best actual combat, the company does not use much, and the learning materials are few
Tornado framework usage scenarios
- Build microservices
The composition of the frame
Try Tornado first
First import the modules to be used this time
import time
from tornado import web, ioloop, httpserver
view
class MainPageHandler(web.RequestHandler):
def get(self, *args, **kwargs): # 对应get请求
self.wrilt('hello tornado')
set route
app = web.Application(
[
(r"/", MainPageHandler),
]
)
"/" means to visit the home page, for example, the local domain name is 127.0.0.1:8000/, which means visiting this website, you will visit the home page
Set the front-end socket, call
if __name__ == "__main__":
# 前端socket
http_server = httpserver.HTTPServer(app)
http_server.listen(8000)
ioloop.IOLoop.current().start()
Run the program and test the water first
When Tornado starts, it will not prompt you to start it like Django and Flask
Set the home page, call the front-end file template
# 首页
class MainPageHandler(web.RequestHandler):
def get(self, *args, **kwargs):
self.render('index.html', name='表白墙', messages=MESSAGES)
This time the front-end file is called directly, and there are still a lot of materials on this website.
Website: https://www.17sucai.com/
set up
settings = {
'template_path': 'templates', # 设置模板文件路径
'static_path': 'statics' # 静态文件路径
}
confession wall view
class WishHandler(web.RequestHandler):
def get(self, *args, **kwargs): # 对应get请求
self.render('wish.html',name='表白墙')
def post(self, *args, **kwargs):
# 获取前端传递数据
content = self.get_argument('content', default=None)
name = self.get_argument('name', default='匿名')
if content:
# 添加数据
MESSAGES.append({
'name': name,
'content': content,
'id': len(MESSAGES) + 1,
'num': len(MESSAGES) + 1,
'time': time.strftime('%Y-%m-%d %H:%M:%S')
})
# 跳转
self.redirect('/')
else:
self.write('内容不能为空')
message
# 留言保存在全局变量中
MESSAGES = [
{
'id': 1, 'name': '学员', 'time': '2022-02-10 21:16:00', 'content': '真帅', 'num': 1}
]