- 编写要求登录的装饰器
from functools import wraps
def loginFirst(func): #参数是函数
@wraps(func)
def wrapper(*args, ** kwargs): #定义个函数将其返回
#要求登录
return func(*args, ** kwargs)
return wrapper #返回一个函数
- 应用装饰器,要求在发布前进行登录,登录后可发布。
@app.route('/question/',methods=['GET','POST'])
@loginFirst
def question():
- 建立发布内容的对象关系映射。
class Question(db.Model):
- 完成发布函数。
保存到数据库。
重定向到首页。
from flask import Flask, render_template,url_for,redirect,request,session from flask_sqlalchemy import SQLAlchemy from functools import wraps from datetime import datetime import config app = Flask(__name__) app.config.from_object(config) db = SQLAlchemy(app) class User(db.Model): __tablename__ = 'user' id = db.Column(db.Integer, primary_key=True, autoincrement=True) username = db.Column(db.String(20), nullable=False) password = db.Column(db.String(20), nullable=False) nickname = db.Column(db.String(20)) # db.create_all() class Question(db.Model): # 建立发布内容的对象关系映射 __tablename__='wenda' id = db.Column(db.Integer, primary_key=True, autoincrement=True) title =db.Column(db.String(100), nullable=False) detail = db.Column(db.Text, nullable=False) creat_time=db.Column(db.DateTime,default=datetime.now) author_id = db.Column(db.Integer,db.ForeignKey('user.id')) author=db.relationship('User',backref=db.backref('wenda')) db.create_all() @app.route('/') def hh(): return render_template('hh.html') @app.route('/login/', methods=['GET', 'POST']) def login(): if request.method == 'GET': return render_template("dl.html") else: username = request.form.get('username') password = request.form.get('password') user = User.query.filter(User.username == username).first() if user: if user.password == password: return redirect(url_for('hh')) else: return '密码错误' else: return '用户名不存在' @app.context_processor def mycontext(): username = session.get('user') if username: return {'username':username} else: return {} @app.route('/logout/') def logout(): session.clear() return redirect(url_for('hh')) # return render_template("homepage.html") @app.route('/regist/',methods=['GET','POST']) def regist(): if request.method=='GET': return render_template("zc.html") else: username = request.form.get("username") password = request.form.get("password") user = User.query.filter(User.username == username).first() if user: return ' 用户名已存在' else: user = User(username=username, password=password) db.session.add(user)#数据库,添加操作 db.session.commit() return redirect(url_for('login')) #行动前需要登录,定义装饰器 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('/wenda/',methods=['GET','POST']) @loginFirst def wenda(): if request.method == 'GET': return render_template("wenda.html") else: title=request.form.get('title') detail=request.form.get('detail') author_id=User.query.filter(User.username==session.get('user')).first().id wenda = Question(title=title, detail=detail, author_id=author_id) db.session.add(wenda) # 数据库,添加操作 db.session.commit() return redirect(url_for('hh')) if __name__ == '__main__': app.run(debug=True)
{% extends 'base.html' %} {% block title %}问答{% endblock %} {% block head %} <link type="text/css" rel="stylesheet" href="{{ url_for('static',filename='css/hh.css') }}"> <script src="{{ url_for('static',filename='js/wenda.js') }}"></script> {% endblock %} {% block main %} <br><br> <form action="{{ url_for('question') }}" method="post"> <div class="label"> <h1 style="color:red",align="center"> 发布问答</h1> <div class="q"> <label for="question">问题</label> <textarea id="question" cols="50" rows="1" name='title'></textarea> </div> <div class="form-group"> <label for="questionDetail">详情</label> <textarea class="form-control" id="questionDetail" cols="50" rows="5" name='detail'></textarea> </div> <br> <div class="input-area"> <button onclick="fnQuestion">发布问答</button> </div> </div> </form> {% endblock %}