Python基于Flask,ThinkPHP开发简易个人博客

12 篇文章 0 订阅

Flask是一款基于Python的轻量级后端框架
下载链接:
Flask官网:http://flask.pocoo.org/docs/0.10/
其他流行的Python框架:Django:https://www.djangoproject.com/

基于ThinkPHP和基于Flask的简易博客下载地址
https://download.csdn.net/download/weixin_43746433/11241631

1.项目准备
准备项目:templates/,config.py、run.py,数据库
表单实现
处理表单并跳转

文件目录
在这里插入图片描述
2.数据库配置:
虚拟环境我使用的是以前PHP开发使用的wampserver: http://www.wampserver.com/
在这里插入图片描述
config.py文件

HOST = 'localhost'
PORT = 8889
USER = 'root'
PASSWORD = 'root'
DATABASE = 'easy_blog'
CHARSET = 'utf8'

3.具体的代码实现run.py

from flask import *
import warnings
warnings.filterwarnings("ignore")
import pymysql
# 提供了许多函数和变量来处理 Python 运行时环境的不同部分.
import importlib,sys
importlib.reload(sys)
#import MySQLdb.cursors
import datetime
import os
from datetime import timedelta
app = Flask(__name__)
#静态文件缓存时间设置
app.config['SEND_FILE_MAX_AGE_DEFAULT']=timedelta(seconds=1)
app.config.from_object(config)
app.config['SECRET_KEY']=os.urandom(24)   #设置为24位的字符,每次运行服务器都是不同的,所以服务器启动一次上次的session就清除。
app.config['PERMANENT_SESSION_LIFETIME']=timedelta(days=7) #设置session的保存时间。
app.config.from_object(__name__)
#coding=utf8
# 连接数据库
def connectdb():
	db = pymysql.connect(host='localhost', user='root', passwd='root', db='easy_blog',charset='utf8')
	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('/handle', methods=['POST'])
def handle():
	dt = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
	print(dt)
	# 获取post数据
	data = request.form
	print(data['title'])
	print(data['content'])

	# 连接数据库
	(db,cursor) = connectdb()

	a=1
	# 添加数据
	##, str(int(time.time()))])
	sql="insert into post(title, content, timestamp) values('%s', '%s', '%s')" %(data['title'], data['content'],dt)
	cursor.execute(sql)
	result=cursor.fetchone()
	if (result is None):
		print('flase')
	else:
		print('插入')
	# 最后添加行的id
	db.commit()
	post_id = cursor.lastrowid
	print(post_id)
	cursor.execute("update post set id='%s' where title='%s'" %(post_id,data['title']))
	db.commit()
	# 关闭数据库
	closedb(db,cursor)
	return redirect(url_for('post', post_id=post_id))

# 文章列表页
@app.route('/list')
def list():
	# 连接数据库
	(db,cursor) = connectdb()

	# 获取数据
	cursor.execute("select * from post order by id desc")
	posts = cursor.fetchall()

	## 格式化时间戳
	#for x in range(0, len(posts)):
	#	posts[x][2] = time.strftime('%Y-%m-%d %H:%M:%S',posts[x][2])

	# 关闭数据库
	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('/delete/<post_id>')
def delete(post_id):
	print('post_id',post_id)
	print('666')
	(db, cursor) = connectdb()
	cursor.execute("delete from post where id=%s" % (post_id))
	db.commit()
	result=cursor.fetchone()
	if (result is None):
		print('flase')
	else:
		print('插入')
	return redirect(url_for('list'))
	#return render_template('list.html')
#<h4><a href="{{url_for('post', post_id=item[3])}}">{{item[0]}}</a></h4>

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

运行结果:
在这里插入图片描述
界面:
在这里插入图片描述
博客内容:
在这里插入图片描述
查看列表:
在这里插入图片描述
删除博客:
在这里插入图片描述

  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值