from flask import *
from flask_sqlalchemy import SQLAlchemy
#导入captcha 用于生成验证码
from captcha.captcha import captcha
#图文混排导包
from flask_uploads import UploadSet, IMAGES, configure_uploads
import sys
import os
import re #正则
app = Flask(name)
app.secret_key = ‘1812B1234567890’
app.config[‘SQLALCHEMY_DATABASE_URI’] = ‘mysql+pymysql://root:@127.0.0.1:3306/gaoqian’
db = SQLAlchemy(app)
fn = getattr(sys.modules[‘main’], ‘file’)
root_path = os.path.abspath(os.path.dirname(fn)) + “/static/upload”
app.config[‘UPLOADED_PHOTO_DEST’] = root_path
app.config[‘UPLOADED_PHOTO_ALLOW’] = IMAGES
photos = UploadSet(‘PHOTO’) # 用来保存图片的对象 photos.save()
configure_uploads(app, photos)
#分类表
class Cate(db.Model):
tablename = ‘cate’
id = db.Column(db.Integer,primary_key=True)
name = db.Column(db.String(30),unique=True,nullable=False)
image = db.Column(db.String(255))
new = db.relationship(‘News’,backref=‘cate’,lazy=‘dynamic’)
#新闻表
class News(db.Model):
tablename = ‘news’
id = db.Column(db.Integer,primary_key=True)
name = db.Column(db.String(30),unique=True,nullable=False)
content = db.Column(db.String(255))
cid = db.Column(db.Integer,db.ForeignKey(‘cate.id’))
db.create_all()
#添加分类
@app.route(’/addcate’,methods=[‘POST’,‘GET’])
def addcate():
if request.method == ‘POST’:
data = request.form
name = data[‘name’]
image = request.files.get(‘image’)
filename = ‘’
if image:
filename = ‘/static/upload/’+photos.save(image)
cate = Cate(name=name,image=filename)
db.session.add(cate)
db.session.commit()
flash(“添加成功”)
return render_template(“addcate.html”)
#添加新闻
@app.route(’/addnews’,methods=[‘POST’,‘GET’])
def addnews():
if request.method == ‘POST’:
data = request.form
name = data[‘name’]
content = data[‘content’]
cid = data[‘cid’]
if not all([name,content,cid]):
flash(“请输入完整”)
else:
news = News(name=name,content=content,cid=cid)
db.session.add(news)
db.session.commit()
flash(“添加成功”)
cate = Cate.query.all()
return render_template(“addnews.html”,cate=cate)
#获取图片
@app.route(’/upload_image’,methods=[‘POST’])
def upload_image():
image = request.files[‘file’]
image_name = photos.save(image)
image_url = ‘/static/upload/’+image_name
mes = {}
mes[‘path’] = image_url
mes[‘error’] = False
return jsonify(mes)
#首页
@app.route(’/’)
def index():
cate = Cate.query.all()
news = News.query.all()
return render_template(“index.html”,cate=cate,news=news)
#详情页
@app.route(’/detail’)
def detail():
id = request.args.get(‘id’)
news = News.query.filter(News.cid==id).all()
return render_template(‘detail.html’,news=news)
if name == ‘main’:
app.run(debug=True)
模板
addcate.html
{{i.name}}{% for c in news %} {% if c.cid==i.id %}
|
addnews.html
index.html
{{i.name}}{% for c in news %} {% if c.cid==i.id %}
|
detail.html
{{i.content | safe}} |
|