YWEIEN

导航

发布功能完成。

  • 编写要求登录的装饰器

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, request, redirect, url_for, session
from flask_sqlalchemy import SQLAlchemy
import config
from functools import wraps
from datetime import datetime


app = Flask(__name__)
app.config.from_object(config)
db = SQLAlchemy(app)


class User(db.Model):
    __tablename__ = 'user'
    id = db.Column(db.Integer, primary_key=TabError, autoincrement=True)
    username = db.Column(db.String(20), nullable=False)
    password = db.Column(db.String(20), nullable=False)
    nickname = db.Column(db.String(20), nullable=True)


class Wenda(db.Model):
    __tablename__ = 'wenda'
    id = db.Column(db.Integer, primary_key=TabError, 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 daohang():
    return render_template('daohang.html')


@app.route('/denglu/', methods=['GET', 'POST'])
def denglu():
    if request.method == 'GET':
        return render_template('denglu.html')
    else:
        username = request.form.get('user')
        password = request.form.get('psw')
        user = User.query.filter(User.username == username).first()  # 判断用户名是否存在
        if user:
           if user.password == password:
               session['user']=username
               session.permanent = True
               return redirect(url_for('daohang'))
        else:
            return '用户名不存在'


@app.context_processor
def mycontext():
    username=session.get('user')
    if username:
        return {'username':username}
    else:
        return {}

@app.route('/zhuce/', methods=['GET', 'POST'])  # 跳转注册,methods定义它有两种请求方式
def zhuce():
    if request.method == 'GET':
        return render_template('zhuce.html')
    else:

        username = request.form.get('user')
        password = request.form.get('psw')
        nickname = request.form.get('nickname')
        user = User.query.filter(User.username == username).first()  # 判断用户名是否存在
        if user:
            return u'该用户已存在'
        else:
            user = User(username=username, password=password, nickname=nickname)
            db.session.add(user)
            db.session.commit()
            return redirect(url_for('denglu'))

@app.route('/logout/')
def logout():
    session.clear()
    return render_template('daohang.html')

def DengluFirst(func):
    @wraps(func)
    def wrapper(*args,**kwargs):
        if session.get('user'):
            return func(*args,**kwargs)
        else:
            return redirect(url_for('zhuce'))
    return wrapper


@app.route('/wenda/',methods=['GET','POST'])
@DengluFirst
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 = Wenda(title=title,detail=detail,author_id=author_id)
        db.session.add(wenda)
        db.session.commit()
        return redirect(url_for('daohang'))

if __name__ == '__main__':
    app.run(debug=True)
{% extends 'moban.html' %}
{% block wendatitle %}问答界面{% endblock %}
{% block wendahead %}{% endblock %}
{% block wendabody %}
    <form action="{{ url_for('wenda') }}" method="post">
    <div class="from-group">
        <label for="gb">标题</label>
        <br>
        <textarea class="from-control" cols="50" rows="1" id="gb" name="title"></textarea>
    </div>
    <hr>
    <div class="from-group">
        <label for="gb1">详情</label>
        <br>
        <textarea class="from-control" cols="50" rows="10" id="gb1" name="detail"></textarea><br>
        <button type="submit">发送</button>
    </div>

</form>
{% endblock %}
</html>

 

posted on 2017-11-29 20:20  YWEIEN  阅读(119)  评论(0编辑  收藏  举报