发布功能完成。

Posted J芷璇

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了发布功能完成。相关的知识,希望对你有一定的参考价值。

  • 编写要求登录的装饰器

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

保存到数据库。

重定向到首页。

主Python:

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=True, autoincrement=True)
    username = db.Column(db.String(20), nullable=False)
    password = db.Column(db.String(20), nullable=False)
    telephone = db.Column(db.String(11), 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)
    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(\'question\'))  # 这个不会在表单里面出现,只是与user建立一个映射关系


# db.create_all()

# 增加数据

# user=User(username = \'mis1234\',password = \'111111\',telephone = \'12345678900\')
# db.session.add(user)
# db.session.commit()

# 查询数据

# user=User.query.filter(user.username == \'mis1234\').first()
# print(user.username,user.password)


# 修改数据
# user=User.query.filter(user.username == \'mis1234\').first()
# user.password = \'000000\'
# db.session.commit()

# 删除数据
# user=User.query.filter(user.username == \'mis1234\').first()
# db.session.delete(user)
# db.session.commit()




@app.route(\'/login/\', methods=[\'GET\', \'POST\'])
def login():
    if request.method == \'GET\':
        return render_template(\'login.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
                return redirect(url_for(\'base\'))
            else:
                return \'password error.\'
        else:
            return \'username is not existed.\'


@app.route(\'/register/\', methods=[\'GET\', \'POST\'])
def register():
    if request.method == \'GET\':
        return render_template(\'register.html\')
    else:
        usern = request.form.get(\'username\')
        telep = request.form.get(\'telephone\')
        passw = request.form.get(\'password\')
        user = User.query.filter(User.username == usern).first()
        if user:
            return \'username existed.\'
        else:
            user1 = User(username=usern, password=passw, telephone=telep)
            db.session.add(user1)  # 数据库操作
            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(\'/question/\', methods=[\'GET\', \'POST\'])
@loginFirst  # 把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(\'base\'))


@app.route(\'/index\')
def index():
    return render_template(\'index.html\')


@app.route(\'/\')
def base():
    return render_template(\'base.html\')


@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(\'base\'))


if __name__ == \'__main__\':
    app.run(debug=True)

问答html:

{% extends\'base.html\' %}
{% block title %}
    发布问答
{% endblock %}
{% block head %}
    <script src="{{ url_for(\'static\',filename=\'js/question.js\') }}" type="text/javascript"></script>
    <link rel="stylesheet" href="{{ url_for(\'static\',filename=\'css/question.css\') }}" type="text/css">
{% endblock %}
{% block main %}
    <div class="chbox">
        <h3 style="font-family: 楷体;text-align: center;font-size: 40px">发布问答</h3>
        <form method="post" action="{{ url_for(\'question\') }}">
            <div class="form-group"></div>
            <div class="title" style="text-align: left">
                <label for="biaoti" style="font-size: 20px">标题</label><br>
                <input id="uname" type="text" placeholder="标题" name="title">
            </div>
            <div class="form-group" style="text-align: left">
                <label for="questionDetail" style="font-size: 20px"> 详情</label><br>
                <textarea class="form-control" rows="10" id="questionDetail" placeholder="请输入内容" name="detail"></textarea>
            </div>
            <div style="text-align: left">
                <input value="3" name="checkout" id="checkout" type="checkbox">
                <label for="checkout" style="font-size: 20px">Check me out</label>
            </div>
            <div style="text-align: center">
                <button type="submit" id="fabu">发布</button>
            </div>
        </form>
    </div>
{% endblock %}

 

以上是关于发布功能完成。的主要内容,如果未能解决你的问题,请参考以下文章

运行/调试你的PHP代码

从零开始配置vim(27)——代码片段

从零开始配置vim(27)——代码片段

从零开始配置vim(27)——代码片段

如何设置 vscode 的代码片段,以便在自动完成后自动触发 vscode 的智能感知?

Android片段布局完成膨胀