from functools import wraps
from flask import Flask, render_template, url_for, redirect, request, session
from werkzeug.security import generate_password_hash,check_password_hash
import config
from datetime import datetime
from sqlalchemy import or_,and_
from models import Question,User,Comment
from exts import db
app = Flask(__name__)
app.config.from_object(config)
db.init_app(app)
# db.create_all()
# 增加
# user = User(username='tan1997',password='19961021')
# db.session.add(user)
# db.session.commit()
# 查询
# user = User.query.filter(User.username == 'tan1997').first()
# print(user.username,user.password)
# 修改
# user=User.query.filter(User.username == 'tan1997').first()
# user.password=1234567
# db.session.commit()
# 删除
# user=User.query.filter(User.username == 'tan1997').first()
# db.session.delete(user)
# db.session.commit()
@app.route('/')
def index():
context = {
'question': Question.query.order_by('-create_time').all()
}
return render_template("index.html", **context)
@app.route('/login/', methods=['GET', 'POST'])
def login():
if request.method == 'GET':
return render_template("login.html")
else:
usern = request.form.get('username')
password1 = request.form.get('password')
user = User.query.filter(User.username == usern).first()
if user:
if user.check_password(password1):
session['user'] = usern
session['id'] = user.id
session.permanent = True
return redirect(url_for('index'))
else:
return '密码错误'
else:
return '用户名不存在'
@app.context_processor
def mycontext():
usern = session.get('user')
if usern:
return {
'sessusername': usern,
}
else:
return {}
def loginFirst(func): # 定义需要装饰器
@wraps(func)
def wrapper(*args, **kwargs): # 定义个函数将其返回
if session.get('user'):
return func(*args, **kwargs)
else:
return redirect(url_for('login'))
return wrapper # 返回一个函数
@app.route('/regist/', methods=['GET', 'POST'])
def regist():
if request.method == 'GET':
return render_template("regist.html")
else:
username = request.form.get('username')
password = request.form.get('password')
nickname = request.form.get('nickname')
user = User.query.filter(User.username == username).first()
if user:
return ' 用户名已存在'
else:
user = User(username=username, password=password, nickname=nickname)
db.session.add(user) # 数据库,添加操作
db.session.commit()
return redirect(url_for('login'))
@app.route('/logout/')
def logout():
session.clear()
return redirect(url_for('index'))
@app.route('/edit_password/', methods=['GET', 'POST'])
def edit_password():
if request.method == 'GET':
return render_template("edit_password.html")
else:
newpassword = request.form.get('password')
user = User.query.filter(User.id == session.get('id')).first()
user.password = newpassword
db.session.commit()
return redirect(url_for('index'))
@app.route('/question/', methods=['GET', 'POST'])
@loginFirst # 使用定义的装饰器
def question():
if request.method == 'GET':
return render_template('question.html')
else:
title = request.form.get('title')
detail = request.form.get('detail')
author_id = User.query.filter(User.username == session.get('user')).first().id
question = Question(title=title, detail=detail, author_id=author_id)
db.session.add(question)
db.session.commit() # 事务提交,将数据添加进数据库
return redirect(url_for('index'))
@app.route('/detail/<question_id>') # 和idea的update一样,将id带到控制器
def detail(question_id):
quest = Question.query.filter(Question.id == question_id).first() # 根据id查询出整条元组记录,丢进quest
return render_template('detail.html', ques=quest) # 把值quest丢进键quest,在detail.html页面调用
@app.route('/comment/', methods=['POST'])
@loginFirst
def comment():
comment = request.form.get('new_comment')
ques_id = request.form.get('question_id')
auth_id = User.query.filter(User.username == session.get('user')).first().id
comm = Comment(author_id=auth_id, question_id=ques_id, detail=comment)
db.session.add(comm)
db.session.commit()
return redirect(url_for('detail', question_id=ques_id))
@app.route('/user/<user_id>/<tag>')
@loginFirst
def user(user_id, tag):
user = User.query.filter(User.id == user_id).first()
context = {
'user': user,
'username': user.username,
'questions': user.question, # 用反向定义的question
'comments': user.comments
}
if tag == '1':
return render_template('usercenter1.html', **context)
elif tag == '2':
return render_template('usercenter2.html', **context)
else:
return render_template('usercenter3.html', **context)
#
# @app.route('/usercenter1/<user_id>')
# def usercenter1(user_id):
# user = User.query.filter(User.id == user_id).first()
# context = {
# 'username_id': user.id,
# 'username': user.username,
# 'questions': user.question, # 用反向定义的question
# 'comments': user.comments
# }
# return render_template('usercenter1.html', **context)
#
#
# @app.route('/usercenter2/<user_id>')
# def usercenter2(user_id):
# user = User.query.filter(User.id == user_id).first()
# context = {
# 'username_id': user.id,
# 'username': user.username,
# 'questions': user.question, # 用反向定义的question
# 'comments': user.comments
# }
#
# return render_template('usercenter2.html', **context)
#
#
# @app.route('/usercenter3/<user_id>')
# def usercenter3(user_id):
# user = User.query.filter(User.id == user_id).first()
# context = {
# 'username_id': user.id,
# 'username': user.username,
# 'questions': user.question, # 用反向定义的question
# 'comments': user.comments
# }
@app.route('/search/')
def search():
qu = request.args.get('q')
ques = Question.query.filter\
(or_(Question.title.contains(qu),
Question.detail.contains(qu)
)
).order_by('-create_time')
return render_template('index.html',question=ques)
if __name__ == '__main__':
app.run(debug=True)
{% extends'myweb.html' %}
{% block title %}首页{% endblock %}
{% block head %}
{% endblock %}
{% block body %}
<div class="container">
<div class="row clearfix">
<div class="col-md-8 column" id="rgba1" style="border-radius: 10px">
<h3 align="center">交流区</h3>
<ul>
{% for foo in question %}
<li>
<span><img src="../static/img/touxiang.jpg " width="30px" alt=""></span><a href="{{ url_for('user',user_id = foo.author_id,tag = 1) }}">{{ foo.author.username }}</a>
<br>
<p>标题:<a href="{{ url_for('detail',question_id=foo.id) }}">{{ foo.title }}</a></p>
<p>内容:{{ foo.detail }}</p>
<span>评论数: ({{ foo.comments|length }})</span>
<span class="badge pull-right">{{ foo.create_time }}</span>
<hr>
</li>
{% endfor %}
</ul>
</div>
</div>
</div>
{% endblock %}
{% extends'myweb2.html' %}
{% block title %}发帖页面{% endblock %}
{% block head %}
{% endblock %}
{% block body %}
<div class="ques">
<form action="{{ url_for('question') }}" method="post">
<div class="form-group">
<label for="questionTitle" style="color: black">标题</label>
<textarea class="textareabg" rows="1" id="questionTitle" name="title" style="width: 700px"></textarea>
<label for="questionDatail" style="color: black">详情</label>
<textarea class="textareabg" rows="5" id="questionDatail" name="detail" style="width: 700px"></textarea>
<br>
<div id=""><br></div>
<input type="submit" value="发布" class="btn btn-default" onclick="" style="margin-left: 100%">
</div>
</form>
</div>
{% endblock %}
{% extends 'myweb2.html' %}
{% block title %}帖子详情{% endblock %}
{% block head %}
{% endblock %}
{% block body %}
<div class="col-md-2 column "></div>
<div class="col-md-8 column " id="rgba1">
<ul class="list-unstyled">
<li>
<h2 href="#" class="text-center">{{ ques.title }}</h2>
<br>
<p class="text-center">
<a href="#">
<small>{{ ques.author.username }}</small>
</a>   
<span class="pull-center"><small>{{ ques.create_time }}</small></span>
</p>
<p>{{ ques.detail }}</p>
<form action="{{ url_for('comment') }}" method="post">
<div class="form-group">
<textarea name="new_comment" class="form-control" rows="5" id="comment"
placeholder="请输入评论"></textarea>
<input type="hidden" name="question_id" value="{{ ques.id }}">
</div>
<button type="submit" class="btn btn-default" style="margin-left:48% ">发送</button>
</form>
</li>
</ul>
<hr>
<h4>评论:({{ ques.comments|length }})</h4>
<ul class="list-unstyled">
{% for foo in ques.comments %}
<li class="list-group-item">
<a href="{{ url_for('user',user_id = foo.author.id,tag = 1) }}">{{ foo.author.username }}</a>
<span class="badge pull-right">{{ foo.create_time }}</span>
<p>{{ foo.detail }}</p>
<br>
</li>
{% endfor %}
</ul>
</div>
<div class="col-md-2 column "></div>
{% endblock %}
{% extends'myweb2.html' %}
{% block title %}登陆页面{% endblock %}
{% block head %}
{% endblock %}
{% block body %}
<div class="logo_box">
<h3 class="h3">欢迎你</h3>
<form action="{{ url_for('login') }}" method="post">
<div class="input_outer">
<label for="uname">账号</label>
<input id="uname" class="text" style="color: whitesmoke" type="text" placeholder="请输入账号" name="username">
</div>
<div class="input_outer">
<label for="upass">密码</label>
<input id="upass" class="text" style="color:whitesmoke ; position:absolute; z-index:100;"
value="" type="password" placeholder="请输入密码" name="password">
</div>
<div class="errorText" id="error_box" style="color: red"><br></div>
<div>
<button onclick="return fnLogin()" class="lb1" style="color:black">登录</button>
</div>
</form>
</div>
{% endblock %}