您的位置:首页 > 编程语言 > Python开发

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

2019-06-14 17:34 651 查看

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.pyrun.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)

运行结果:

界面:

博客内容:

查看列表:

删除博客:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: