• 发布功能完成。


    • 编写要求登录的装饰器

    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):
    • 完成发布函数。

    保存到数据库。

    重定向到首页。

    py:

    from flask import Flask,render_template,request,redirect,url_for,session
    from flask_sqlalchemy import SQLAlchemy
    import config
    from datetime import datetime
    from functools import wraps
    
    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),nullable=False)
    
    class Question(db.Model):
        __tablename__ = 'question'
        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)
        creatTime = db.Column(db.DateTime,default=datetime.now)
        authorID = db.Column(db.Integer,db.ForeignKey('User.id'))
        author = db.relationship('User',backref=db.backref('question'))
    #db.create_all()
    
    
    
    @app.route('/')
    def index():
        return render_template('index.html')
    
    @app.route('/denglu/',methods=['GET','POST'])
    def denglu():
        if request.method == 'GET':
            return render_template('denglu.html')
        else:
            usern = request.form.get('username')
            passw = request.form.get('password')
            user = User.query.filter(User.username == usern).first()
            if user:
                 if user.password == passw:
                     session['user'] = usern
                     session.permanent = True
                     return redirect(url_for('index'))
                 else:
                        return 'password error.'
            else:
                  return 'username is not existed'
    @app.route('/zhuc/',methods=['GET','POST'])
    def zhuc():
        if request.method=='GET':
            return render_template('zhuc.html')
        else:
            usern = request.form.get('username')
            passw = request.form.get('password')
            nickn = request.form.get('nickname')
            user=User.query.filter(User.username==usern).first()
            if user:
                return u'username existed.'
            else:
                user = User(username=usern,password=passw,nickname=nickn)
                db.session.add(user)
                db.session.commit()
                return redirect(url_for('denglu'))
    
    
    
    
    def loginFirst(func):
        @wraps(func)
        def wrapper(*args,**kwargs):
            if session.get('user'):
                return func(*args, **kwargs)
            else:
                return redirect(url_for('denglu'))
        return wrapper
    
    @app.route('/label/',methods=['GET','POST'])
    @loginFirst
    def label():
        if request.method == 'GET':
            return render_template('label.html')
        else:
            title = request.form.get('title')
            detail = request.form.get('detail')
            authorID = User.query.filter(User.username == session.get('user')).first().id
            question = Question(title=title,detail=detail,authorID=authorID)
            db.session.add(question)
            db.session.commit()
            return redirect(url_for(('index')))
    
    @app.context_processor
    def mycontext():
        usern = session.get('user')
        if usern:
            return {'username':usern}
        else:
            return {}
    
    @app.route('/logout/')
    def logout():
            session.clear()
            return redirect(url_for('index'))
    
    if __name__ == '__main__':
        app.run(debug=True)

    html:

    {% extends'base.html' %}
    {% block title %}
        wenda
    {% endblock %}
    
    {% block head %}
        <link rel="stylesheet" href="{{ url_for('static',filename='css/label.css')}}">
    {% endblock %}
    
    {% block main %}
        <div class="question">
        <p class="name">欢迎你,{{ username }}</p>
    {#    {% if username %}#}
    {#        <p class="name">欢迎你,{{ username }}</p>#}
    {#    {% else %}#}
    {#        <p class="name">欢迎你,请先<a href="{{ url_for('sign_in') }}" >登录</a>或者<a href="{{ url_for('sign_up') }}">注册</a></p>#}
    {#    {% endif %}#}
        <h3>发布问答</h3>
        <form action="{{ url_for('label') }}" method="post" >
            <div class="form-group">
                <label for="ask">问题</label>
                <br>
                <textarea class="form-control" rows="1" id="ask" name="title"></textarea>
            </div>
            <br>
            <div class="form-group">
                <label for="questionDetail">详情</label>
                <br>
                <textarea class="form-control" rows="8" id="questionDetail" name="detail"></textarea>
            </div>
            <label>
            <input type="checkbox">check me
            <br><br>
            <button type="submit" class="btn-default">发布</button>
            </label>
        </form>
        </div>
    {% endblock %}

  • 相关阅读:
    uni-app中showModel会阻碍 uni.navigateBack跳转
    vue中使用Bus
    vue中class动态绑定值拼接字符串
    使用moment格式化
    sublimit中智能提示插件的安装
    element-table
    全球十大顶级俱乐部
    java的几种对象(PO,VO,DAO,BO,POJO)解释
    软件工程术语(上)
    职场秘笈:聪明人离职后必做的5件事
  • 原文地址:https://www.cnblogs.com/0055sun/p/7911714.html
Copyright © 2020-2023  润新知