本项目以Flask为基础Python后端框架,搭建一个包含后端的网站。

一、项目准备

新建一个文件夹easy_blog_flask,再新建3个文件夹:static、templates和venv和config.py和run.py两个python文件。其中static用于存放静态资源文件,templates用于存放HTML模板,venv用于搭建环境。安装虚环境。

1、激活虚环境

虚环境中会使用的道德Python包与系统中的Python以及其他功能包相互隔离,便于项目的管理的开发。
激活虚环境

2、编辑run.py

设置UTF-8为默认字符集,从Flask中夹杂急需要使用的全部内容,设置忽略警告信息,加载MySQLdb操作数据库,最后加载config.py中定义的配置项内容。

#!/usr/bin/env python
# coding:utf8

import sys
reload(sys)
sys.setdefaultencoding( "utf8" )
from flask import *
import warnings
warnings.filterwarnings("ignore")
import MySQLdb
import MySQLdb.cursors
from config import *
import time

app = Flask(__name__)
app.config.from_object(__name__)

# 连接数据库
def connectdb():
	db = MySQLdb.connect(host=HOST, user=USER, passwd=PASSWORD, db=DATABASE, port=PORT, charset=CHARSET, cursorclass = MySQLdb.cursors.DictCursor)
	db.autocommit(True)
	cursor = db.cursor()
	return (db,cursor)

# 关闭数据库
def closedb(db,cursor):
	db.close()
	cursor.close()

# 首页
@app.route('/')
def index():
	return render_template('index.html')

# 文章列表
@app.route('/list')
def list():
	(db,cursor) = connectdb()
	cursor.execute("select * from post")
	posts = cursor.fetchall()
	for x in xrange(0,len(posts)):
		posts[x]['timestamp'] = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(float(posts[x]['timestamp'])))
	closedb(db,cursor)
	return render_template('list.html', posts=posts)

# 文章内容
@app.route('/post/<post_id>')
def post(post_id):
	(db,cursor) = connectdb()
	cursor.execute("select * from post where id=%s", [post_id])
	post = cursor.fetchone()
	post['timestamp'] = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(float(post['timestamp'])))
	closedb(db,cursor)
	return render_template('post.html', post=post)

# 处理提交
@app.route('/handle', methods=['POST'])
def handle():
	data = request.form
	(db,cursor) = connectdb()
	cursor.execute("insert into post(title, content, timestamp) values(%s, %s, %s)",[data['title'],data['content'],int(time.time())])
	closedb(db,cursor)
	return redirect(url_for('list'))

if __name__ == '__main__':
	app.run(debug=True)

二、渲染模板

1、Flask使用Jinjia2进行前端模板渲染

使用layout.html作为其他HTML页面渲染的模板,index.html设置首页、list.html文章列表页,post.html设置文章详情页

layout.html

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>极客范儿的博客</title>
	<link rel="stylesheet" href="{{url_for('static', filename='blogcss.css')}}">
</head>

<body>
	<header>
		<a href="{{url_for('index')}}">首页</a>
		<a href="{{url_for('list')}}">文章列表</a>
	</header>
	<div id="content">
		{% block body %} {% endblock %}
	</div>
	<footer>Copyright @ Geekfanr</footer>

</body>
</html>

index.html

{% extends 'layout.html' %}
{% block body %}
<link rel="stylesheet" href="{{url_for('static', filename='test.css')}}">
<h1>欢迎来到极客园地</h1>
<p>来逛逛<a href="https://blog.csdn.net/Prototype___" target="_blank">我的csdn</a>跟我一起交流</p>
<form class="form" action="{{url_for('handle')}}" method="post">
	<h4>添加文章</h4>
	<input class="input" type="text" name="title" placeholder="标题">
	<textarea class="textarea" name="content" cols="30" rows="10" placeholder="内容"></textarea>
	<button class="button" type="submit">提交</button>
</form>
{% endblock %}

list.html

{% extends 'layout.html' %}
{% block body %}
<style>
.p {
	padding: 10px 30px;
	border: 1px solid #888;
	margin: 20px 0;
}
</style>
<h1>文章列表</h1>
<div id="list">
	{% for item in posts %}
		<div class="p">
			<h4><a href="{{url_for('post', post_id=item['id'])}}">{{item['title']}}</a></h4>
			<p>{{item['timestamp']}}</p>
		</div>
	{% endfor %}
</div>
{% endblock %}

post.html

{% extends 'layout.html' %}
{% block body %}
<h1>文章内容</h1>
<h4>{{post['title']}}</h4>
<h5>{{post['timestamp']}}</h5>
<p>{{post['content']}}</p>
{% endblock %}

2、将所有网页样式放到static文件夹下

bolgcss.css

html, body {
	margin: 0;
	padding: 0;
}
header, footer {
	padding: 30px 40px;
	background-color: #f2f2f2;
	color: #666;
}
header a {
	padding: 0 20px;
	color: #999;
	text-decoration: none;
}
header a:hover {
	color: #333;
}
footer {
	text-align: center;
	margin-top: 250px;
}
#content {
	padding: 30px 40px;
}
.button {
  display: inline-block;
  padding: 15px 25px;
  font-size: 24px;
  cursor: pointer;
  text-align: center;   
  text-decoration: none;
  outline: none;
  color: #fff;
  background-color: #4CAF50;
  border: none;
  border-radius: 15px;
  box-shadow: 0 9px #999;
  margin-left: 90px;
}

.button:hover {background-color: #3e8e41}

.button:active {
  background-color: #3e8e41;
  box-shadow: 0 5px #666;
  transform: translateY(4px);
}
.form {
	width: 505px;
	height: 100px;
}
.input {
	border: 0;
	border-radius: 5px;
	background-color: rgba(241,241,241,.98);
	width: 205px;
	height: 20px;
	padding: 10px;
}
.textarea {
	border: 0;
	border-radius: 5px;
	background-color: rgba(241,241,241,.98);
	width: 355px;
	height: 100px;
	padding: 10px;
	resize:none;
	margin-top: 20px;
}

index
list

三、操作数据库

run.py中定义handle()函数,获取表单数据后,连接数据库、添加数据、关闭数据库,最后使用redirect()函数跳转至index()

# 处理表单提交
@app.route('/handle', methods=['POST'])
def handle():
	# 获取post数据
	data = request.form
	# 连接数据库
	(db,cursor) = connectdb()
	
	#添加数据
	cursor.execute("insert into post(title, content, timestamp) values(%s, %s, %s)",[data['title'],data['content'],int(time.time())])
	
	# 关闭数据库
	closedb(db,cursor)
	
	return redirect(url_for('index'))

database

四、总结

通过这次个人博客项目,接触了搭建一个包含后端的网站可能涉及的一些内容:处理表单提交、在后端操作数据库、前端和后端之间的数据传递、在前端渲染模板。

Logo

CSDN联合极客时间,共同打造面向开发者的精品内容学习社区,助力成长!

更多推荐