社区版pycharm flask封装接口

因为装的pycharm版本是社区版,没有单独的flask项目创建入口

1、首先和创建python项目一样创建一个项目:要选择虚拟环境(一般默认即可)

社区版pycharm flask封装接口_第1张图片

2、项目文件夹下安装flask:npm install flask

前端渲染后续研究,此次只封装接口

3 导包

notes:1、调试过程中要手动打开debug模式

            2、cors是解决前端跨域问题

import os
import json
os.environ['NLS_LANG'] = 'SIMPLIFIED CHINESE_CHINA.UTF8'
from flask import Flask,jsonify,request
from flask_cors import *   #solve cross-domain problems
from flask import render_template
import pymysql
app = Flask(__name__) #must have
#app.config['DEBUG'] = True
CORS(app, supports_credentials=True) #solve cross-domain problems

4 连接数据库,对数据库进行增删改

notes:如果请求的参数是一个参数,要注意是不是元组格式,如果是需要在参数后加逗号,因为元组只有一个元素的话 不加逗号 就不是元祖(参考:select2函数)

import os
import json
#from flask_cors import *
os.environ['NLS_LANG'] = 'SIMPLIFIED CHINESE_CHINA.UTF8'
from flask import Flask,jsonify,request
from flask_cors import *
from flask import render_template
import pymysql

app = Flask(__name__)
#app.config['DEBUG'] = True
CORS(app, supports_credentials=True)
class MysqldbHelper(object):
    def __init__(self):
     try:
        self.db = pymysql.connect(
            host="127.0.0.1",
            user="root",
            passwd="123456",
            port=55111,
            db="test_suit",
            charset='utf8')
        #self.db = pymysql.connect(self.host, self.user, self.passwd, self.dbase, self.port, charset='utf8')
     except pymysql.err:
         print('error')

    def select1(self, sql):
        ''' 数据库查询 '''
        self.cursor = self.db.cursor()
        try:
            self.cursor.execute(sql)  # 返回 查询数据 条数 可以根据 返回值 判定处理结果

            data = self.cursor.fetchall()  # 返回所有记录列表
            return data
        except:
            print('Error: unable to fecth data')
        finally:
            self.cursor.close()
            self.db.close()


        # return {c.name: getattr(self, c.name) for c in self.__table__.columns}
        # 上面的有缺陷,表字段和属性不一致会有问题


    def select2(self, sql,args):
        ''' 数据库查询 '''
        self.cursor = self.db.cursor()
        try:
            self.cursor.execute(sql,(args,))  # 返回 查询数据 条数 可以根据 返回值 判定处理结果

            data = self.cursor.fetchall()  # 返回所有记录列表
            return data
        except:
            print('Error: unable to fecth data')
        finally:
            self.cursor.close()
            self.db.close()

    def insert(self,sql,args):
        self.cursor = self.db.cursor()
        try:
            # 执行sql
            #data = (Tsuitname, Tname, Tdescriber, Tstate, Tresult, Tresultdes)
           # self.cursor.execute(sql,(args['Tsuitname'],args['Tname'],args['Tdescriber'],args['Tstate'],args['Tresult'],args['Tresultdes'],)) 字典的方式
            self.cursor.execute(sql,args)
            # tt = self.cursor.execute(sql)  # 返回 插入数据 条数 可以根据 返回值 判定处理结果
            # print(tt)
            self.db.commit()
            return True
        except:
            # 发生错误时回滚
            self.db.rollback()
            return  False
        finally:
            self.cursor.close()
            self.db.close()

    def delete(self,sql,args):
        ''' 操作数据库数据删除 '''
        self.cursor = self.db.cursor()
        try:
            # 执行sql
            self.cursor.execute(sql,(args,))
            # tt = self.cursor.execute(sql) # 返回 删除数据 条数 可以根据 返回值 判定处理结果
            # print(tt)
            self.db.commit()


        except:
            # 发生错误时回滚
            self.db.rollback()
        finally:
            self.cursor.close()
            self.db.close()

    def update(self,sql,args):
        self.cursor = self.db.cursor()
        try:
            self.cursor.execute(sql,args)
            self.db.commit()
            return True
        except:
            self.db.rollback()
        finally:
            self.cursor.close()
            self.db.close()








5、设置接口路由 及传参/返回值等

@app.route('/update', methods=[ 'POST']) 路由设置,格式为:http://localhost/update

methods=[ 'POST'] 请求方法 get/post

获取json格式数据:request.json.get()可用postman调试,调试时把debug模式打开

前端渲染时:因为后端写的是json格式,前端请求时需将参数转化为json:

例如:service.post('http://localhost/insert', JSON.stringify(参数), { headers: { 'Content-Type': 'application/json; charset=UTF-8' } });

以下代码的不足:接口不够规范,请求参数/返回数据 没有放到一个有名称的元组里

@app.route('/select2', methods=[ 'POST','GET'])
def sel2():
    db = MysqldbHelper()
    try:    #z这样判断不对,需要更改

        sql = 'select * from test_suit.suit'
        fc = db.select1(sql)
        return json.dumps(fc, ensure_ascii=False, indent=4)
    except:
        return ()

@app.route('/select', methods=[ 'POST','GET'])
def sel():
    db = MysqldbHelper()
    idSuit =  request.json.get('idSuit',None)

    Tsuitname = request.json.get('Tsuitname', None)
    '''
    Tname = request.json.get('Tname', None)

    Tstate = request.json.get('Tstate', None)
    Tresult = request.json.get('Tresult', None)
    '''
    try:    #z这样判断不对,需要更改
        if idSuit != None:
            sql = 'select * from test_suit.suit where idSuit=%s '
            fc = db.select2(sql, idSuit)
        if Tsuitname != None:
            sql= 'select * from test_suit.suit where Tsuitname=%s'
            fc = db.select2(sql, Tsuitname)

        return json.dumps(fc, ensure_ascii=False, indent=4)
    except:
        return ()

@app.route('/delete', methods=[ 'POST'])
def dels():
    db = MysqldbHelper()
    idSuit=  request.json.get('idSuit')
    sql= 'delete from test_suit.suit where idSuit=%s'
    db.delete(sql,idSuit)
    return jsonify({"code": 200})


@app.route('/insert', methods=[ 'POST'])
def index():
    if request.method == 'POST':
        db = MysqldbHelper()
        Tsuitname = request.json.get('Tsuitname',None)
        #Tname = request.json['Tname']
        Tname = request.json.get('Tname', None)
        Tdescriber =request.json.get('Tdescriber',None)
        Tstate =  request.json.get('Tstate',None)
        Tresult = request.json.get('Tresult',None)
        Tresultdes =  request.json.get('Tresultdes',None)
        data=(Tname,Tdescriber,Tstate,Tresult,Tresultdes)
    #if (len(Tsuitname) != 0) & (len(Tname)!=0 ):
        sql_insert = 'insert into test_suit.suit value(default,%s,%s,%s,%s,%s,%s)'
        if db.insert(sql_insert,data):
          return jsonify({"code": 200, "mesg": "insert"})

@app.route('/update', methods=[ 'POST'])
def update():
    if request.method == 'POST':
        db = MysqldbHelper()
        idSuit = request.json.get('idSuit')
        Tsuitname = request.json.get('Tsuitname', None)
        Tsuitname = request.json.get('Tsuitname',None)
        #Tname = request.json['Tname']
        Tname = request.json.get('Tname', None)
        Tdescriber =request.json.get('Tdescriber',None)
        Tstate =  request.json.get('Tstate',None)
        Tresult = request.json.get('Tresult',None)
        Tresultdes =  request.json.get('Tresultdes',None)
        data=(Tsuitname,Tname,Tdescriber,Tstate,Tresult,Tresultdes,idSuit)
    #if (len(Tsuitname) != 0) & (len(Tname)!=0 ):
        sql_insert = 'update test_suit.suit set Tsuitname=%s,Tname=%s,Tdescriber=%s,Tstate=%s,Tresult=%s,Tresultdes=%s where idSuit=%s'

        if db.update(sql_insert,data):
          return jsonify({"code": 200, "mesg": "update"})
        else:
            return jsonify({"code": 500, "mesg": "update"})

@app.route('/hello')
def hello_world():
 name = request.args.get('name','')
 return 'Hello ' + name + '!'

if __name__=="__main__":

    #app.run(host='127.0.0.1', port='5678')
    app.run()

 

你可能感兴趣的:(flask)