python使用flask框架的例子

app.py

# -*- coding:utf-8 -*-
from flask import Flask, render_template, request, redirect, url_for,jsonify
from models import Article
from exts import db

from aip import AipFace

import json
import config

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

APP_ID = '11360814'
API_KEY = 'iorBZFPbIgPlhfdlDcnKZzXf'
SECRET_KEY = 'gTCrEjuxm0Dna7M3tzDz14j12HMjuXHT'

client = AipFace(APP_ID, API_KEY, SECRET_KEY)

db.init_app(app)

@app.route('/')
def index():
    context = {
        'articles': Article.query.all()
    }
    return render_template('index.html', **context)


@app.route('/add_article/', methods=['GET', 'POST'])
def add_article():
    if request.method == 'GET':
        return render_template('add_article.html')
    else:
        title = request.form.get('title')
        author = request.form.get('author')
        body = request.form.get('body')
        members = []
        jsonstr = json.dumps(members, ensure_ascii=False)
        article_model = Article.query.filter(Article.title == title).first()
        if(article_model!=None):
            return jsonify({'status': '-1'})
        atl = Article(title=title, author=author, content=body, applyNum=0, checkNum=0, members=jsonstr)
        db.session.add(atl)
        db.session.commit()
        return jsonify({'status':'0'})
        # return redirect(url_for('index'))

@app.route('/article/<article_id>/')
def article(article_id):
    if request.method == 'GET':
        article_model = Article.query.filter(Article.id == article_id).first()
        memberslist = json.loads(article_model.members)
        return render_template('article.html', article=article_model, members=memberslist)
    else:
        pass

@app.route('/edit_article/<article_id>/',methods=['GET', 'POST'])
def edit_article(article_id):
    if request.method == 'POST':
        article_model = Article.query.filter(Article.id == article_id).first()
        return render_template('edit_article.html', article=article_model)
    else:
        pass

@app.route('/update_article/<article_id>/',methods=['GET', 'POST'])
def update_article(article_id):
    if request.method == 'POST':
        title = request.form.get('title')
        author = request.form.get('author')
        content = request.form.get('body')
        article_model = Article.query.filter(Article.id != article_id and Article.title == title).first()
        if (article_model != None):
            return jsonify({'status': '-1'})
        article_model = Article.query.filter(Article.id == article_id).first()
        article_model.title = title
        article_model.author = author
        article_model.content = content
        db.session.commit()
        return jsonify({'status': '0'})
    else:
        pass

@app.route('/delete_article/<article_id>/',methods=['GET', 'POST'])
def delete_article(article_id):
    if request.method == 'POST':
        article_model = Article.query.filter(Article.id == article_id).first()
        db.session.delete(article_model)
        db.session.commit()
        return redirect(url_for('index'))
    else:
        pass
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
@app.route('/meetinglist',methods=['GET'])
def meetinglist():
    if request.method == 'GET':
        articles_model = Article.query.all()
        articles = []
        for article in articles_model:
            articles.append({'id': article.id, 'title': article.title, 'author': article.author, 'content': article.content,
                             'applyNum': article.applyNum, 'checkNum': article.checkNum})
        jsonstr = json.dumps(articles,  ensure_ascii=False)
        return jsonstr
    else:
        pass

@app.route('/facereg',methods=['POST'])
def facereg():
    if request.method == 'POST':
        article_id = request.form.get('id')
        image = request.form.get('image')
        imageType = "BASE64"
        groupId = request.form.get('groupId')
        userId = request.form.get('uid')

        article = Article.query.filter(Article.id == article_id).first()

        result = client.addUser(image, imageType, groupId, userId)

        if result and result[u'error_msg'] == u'SUCCESS' and result[u'error_code'] == 0:
            memberslist = json.loads(article.members)
            isreg = False
            for member in memberslist:
                if member['id'] == userId:
                    isreg = True

            if not isreg:
                article.applyNum = article.applyNum + 1
                memberslist.append({'id': userId, 'state': '否'})
                jsonstr = json.dumps(memberslist,  ensure_ascii=False)
                article.members = jsonstr
                db.session.commit()

                res = json.dumps(result,  ensure_ascii=False)
                return res
        else:
            return ''
    else:
        pass

@app.route('/facelogin',methods=['POST'])
def facelogin():
    if request.method == 'POST':
        article_id = request.form.get('id')
        image = request.form.get('image')
        imageType = "BASE64"
        groupId = request.form.get('groupId')

        article = Article.query.filter(Article.id == article_id).first()

        result = client.search(image, imageType, groupId)

        if result and result[u'error_msg'] == u'SUCCESS' and result[u'error_code'] == 0:
            memberslist = json.loads(article.members)
            ischeck = False
            userInfo = result[u'result'][u'user_list'][0]
            userId = userInfo[u'user_id']
            print (userId)
            for member in memberslist:
                if member['id'] == userId:
                    if member['state'] != u'是':
                        print ('change state')
                        member['state'] = u'是'
                        ischeck = True
                        print (member)
                    else:
                        pass
                else:
                    pass

            if ischeck:
                article.checkNum = article.checkNum + 1
                jsonstr = json.dumps(memberslist, ensure_ascii=False)
                article.members = jsonstr
                db.session.commit()

                res = json.dumps(result, ensure_ascii=False)
                return res
        else:
            return ''
    else:
        pass

if __name__ == '__main__':
    app.run(host='localhost',port=5001)
    #app.run(host='192.168.73.126', port=8000, debug=True)

manage.py

# -*- coding:utf-8 -*-
from flask_script import Manager
from flask_migrate import Migrate, MigrateCommand
from app import app
from exts import db
from models import Article
manager = Manager(app)
#使用Migrate绑定app和db
migrate = Migrate(app, db)
#添加迁移脚本
manager.add_command('db', MigrateCommand)

if __name__ == "__main__":
    manager.run()
#生成最migrations文件夹
#python manage.py db init
#生成版本号也就是versions中的py文件,并且迁移脚本
#每次运行这个命令都会刷新版本号
#python manage.py db migrate
#创建articles
#python manage.py db upgrade
#如果再次修改数据库模型,直接执行 migrate 后执行 upgrade即可

exts.py

from flask_sqlalchemy import SQLAlchemy
db = SQLAlchemy()

config.py

# -*- coding:utf-8 -*-
import os
DEBUG = True
SECRET_KEY = os.urandom(24)
HOSTNAME = '127.0.0.1'
PORT    = '3306'
DATABASE = 'aiface'
USERNAME = 'root'
PASSWORD = '320481wht'
DB_URI = 'mysql+pymysql://{}:{}@{}:{}/{}?charset=utf8'.format(USERNAME,PASSWORD,HOSTNAME,PORT,DATABASE)
SQLALCHEMY_DATABASE_URI = DB_URI
SQLALCHEMY_TRACK_MODIFICATIONS = False

models.py

# -*- coding:utf-8 -*-

from exts import db

class Article(db.Model):
    __tablename__ = 'articles'
    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    title = db.Column(db.String(100), nullable=False)
    author = db.Column(db.String(30), nullable=False)
    content = db.Column(db.Text, nullable=False)
    applyNum = db.Column(db.Integer, nullable=False)
    checkNum = db.Column(db.Integer, nullable=False)
    members = db.Column(db.Text, nullable=False)

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值