接口編寫

首先安裝第三方flask模塊,pip install flaskpython

練習編寫註冊接口mysql

分析:git

1.註冊須要有註冊函數,最多輸錯3次,用戶名不存在數據庫,密碼兩次輸入一致等redis

2.註冊成功密碼要加密,須要md5加密方法sql

3.註冊成功後,存到數據庫中數據庫

import flask,json,hashlib,pymysql
#讀取數據庫,sql是select爲查詢功能,insert則插入功能
def my_db(sql,port=3306,charset='utf8'):
    ip, user, password, db = '118.24.3.40','jxz','123456','jxz'
    conn = pymysql.connect(host=ip,user=user,password=password,
                    db=db,port=port,charset=charset,autocommit=True)
    cur = conn.cursor()
    cur.execute(sql)
    sql = sql.strip()
    sql = sql[:6].lower()#取到執行語句的前6個字符,用來判斷是select、show查詢 仍是其餘增刪改(insert,delete,update)
    if sql.startswith('select') or sql.startswith('show'):
        data = cur.fetchall()#將查詢的結果保存在data裏
    else:
        data = 'ok'
    cur.close()
    conn.close()
    return data
#加密,返回加密後的字符串
def my_md5(s):
    m = hashlib.md5(s.encode())
    return m.hexdigest()


server = flask.Flask(__name__)#把這個當前python文件當作一個服務
@server.route('/register',methods=['post'])#@server.route裝飾器,下面不是普通的函數 是一個接口
def reg():

    username = flask.request.values.get('username')#入參爲form-data形式
    passwd = flask.request.values.get('passwd')
    cpasswd = flask.request.values.get('cpasswd')
    # json_data = flask.request.json  # 獲取入參是json類型的
    # username = json_data.get('username')
    # passwd = json_data.get('passwd')
    # cpasswd = json_data.get('cpasswd')
    if not(username and passwd and cpasswd):
        res =  {'code':'2003','msg':'缺乏必填參數'}
    else:
        sql1 = "select * from lina_users where username = '%s';"%username
        res = my_db(sql1)
        if res:
            res = {'code':'2001','msg':'該用戶已被註冊'}
        else:
            if passwd == cpasswd:
                res = {'code':'1000','msg':'註冊成功'}
                sql = "insert into lina_users (username,password) VALUES ('%s','%s')"%(username, my_md5(passwd))
                my_db(sql)
            else:
                res =  {'code':'2002','msg':'兩次密碼不一致'}
    return json.dumps(res,ensure_ascii=False)

#默認5000端口,127.0.0.1 IP、啓動服務,host0.0.0.0  就能夠使別人訪問這個接口了 debug=TRUE就能夠不用重啓服務
server.run(host='0.0.0.0',port=8989,debug=True)

目錄分層結構json

服務器bin目錄放啓動文件,conf下放配置文件,lib中放方法文件flask

因此提取文件中的啓動程序,常量,函數,接口,分別放在bin,conf,lib目錄下,經過import方式導入調用api

調用時,文件夾需在python的環境變量裏,在pycharm中能夠直接點擊文件夾右鍵加入環境變量中服務器

 

文件分層以下:

 

 setting.py程序以下:

#mysql配置信息
MYSQL_INFO = {
    'host':'118.xx.3.40',
    'port':3306,
    'user':'jxz',
    'password':'123456',
    'db':'jxz',
    'charset':'utf8',
    'autocommit':True
}
#redis配置信息
REDIS_INFO = {
    'host':'118.xx.3.40',
    'port':6379,
    'password':'HK139bc&*',
    'db':9
}
#服務接口
SERVER_PORT=8989
#redis失效時間
EXPIRE_TIME=24*3600

func.py程序

from conf.setting import MYSQL_INFO,REDIS_INFO,EXPIRE_TIME
import pymysql,hashlib,redis
#操做mysql
def my_db(sql):
    conn = pymysql.connect(**MYSQL_INFO)
    cur = conn.cursor()
    cur.execute(sql)
    sql = sql.strip()
    sql = sql[:6].lower()#取到執行語句的前6個字符,用來判斷是select、show查詢 仍是其餘增刪改(insert,delete,update)
    if sql.startswith('select') or sql.startswith('show'):
        data = cur.fetchall()#將查詢的結果保存在data裏

    else:
        data = 'ok'
    cur.close()
    conn.close()
    return data

def my_md5(s):
    m = hashlib.md5(s.encode())
    return m.hexdigest()

#redis操做str類型
def op_str_redis(key, value=None):
    conn = redis.Redis(**REDIS_INFO)
    if value:
        conn.set(key,value)#傳value,則插入或者修改key
        conn.expire(key,EXPIRE_TIME)
        return 'set操做成功'
    elif not conn.get(key):
        return '%s不存在'%key#沒傳value,且key不存在
    else:
        res = conn.get(key).decode()#查詢key對應的value值
        return res
#判斷是否爲正數
def check_float_int(s):

    if s.isdigit() and not s.startswith('0'):
        return True
    elif s.count('.') == 1:
        slist = s.split('.')
        left = slist[0]
        right = slist[1]
        if left.isdigit() and right.isdigit():#判斷正小數的
            return True
    else:
        return False

interfaces.py程序

import flask,json,time
from lib.func import my_db,my_md5,op_str_redis,check_float_int
#
server = flask.Flask(__name__)
@server.route('/login',methods=['get'])
def login():
    username = flask.request.values.get("username")
    password = flask.request.values.get("pwd")

    sql = "select password from lina_users where username = '%s'"%username
    res_pwd = my_db(sql)
    if not(username and password):
        res = {'code':'2001','msg':'必填參數未填,請查看接口文檔'}
    elif not res_pwd:
        res = {'code': '2002', 'msg': '用戶名不存在'}
    elif res_pwd[0][0] != my_md5(password):
        res = {'code': '2003', 'msg': '密碼不正確'}
    else:
        id = username+str(int(time.time()))
        sessionid =my_md5(id)
        op_str_redis("session:%s"%username,sessionid)
        res = {'code': '1000', 'login_ info':{'msg': '登陸成功','sessionid':sessionid,'login_time':int(time.time())}}
    return json.dumps(res,ensure_ascii=False)

@server.route('/pay',methods=['get','post'])
def pay():
    username = flask.request.values.get("username")
    payment = flask.request.values.get("payment")
    sessionid = flask.request.values.get("sessionid")
    key_res = 'session:%s'%username
    val_res = op_str_redis(key_res)
    if not(username and payment and sessionid):
        res = {'code': '2001', 'msg': '必填參數未填,請查看接口文檔'}
    elif not check_float_int(payment):
        res = {'code': '2005', 'msg': '參數不合法'}
    else:
        res_db = my_db("select username,account from lina_account where username = '%s'"%username)
        if not res_db:
            res = {'code': '2002', 'msg': '用戶不存在'}
        elif val_res==sessionid:
            remain = res_db[0][1]-float(payment)
            if remain>=0:
                res = {'code': '1000', 'msg': '付款成功','pay_time':int(time.time())}
                my_db("update lina_account set account = '%s' where username = '%s'"%(remain,username))
            elif remain<0:
                res = {'code': '2003', 'msg': '餘額不足'}
        else:
            res = {'code': '2004', 'msg': '用戶未登陸'}
    return json.dumps(res, ensure_ascii=False)

@server.route('/register',methods=['post'])
def reg():
    username = flask.request.values.get('username')
    passwd = flask.request.values.get('pwd')
    cpasswd = flask.request.values.get('cpwd')

    if not(username and passwd and cpasswd):
        res = {'code':'2003','msg':'缺乏必填參數'}
    else:
        sql1 = "select * from lina_users where username = '%s';"%username
        res = my_db(sql1)
        if res:
            res = {'code':'2001','msg':'該用戶已被註冊'}
        else:
            if passwd == cpasswd:
                res = {'code':'1000','msg':'註冊成功','method':flask.request.method}
                sql = "insert into lina_users (username,password) VALUES ('%s','%s')"%(username, my_md5(passwd))
                my_db(sql)
            else:
                res = {'code':'2002','msg':'兩次密碼不一致'}
    return json.dumps(res,ensure_ascii=False)

running.py函數

import sys,os
base_path = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))#獲取lina_api絕對路徑
sys.path.insert(0,base_path)#加入到環境變量中,在任何路徑或者系統都不會報錯了

from lib.interfaces import server
from conf.setting import SERVER_PORT

server.run(port=SERVER_PORT,debug=True)
相關文章
相關標籤/搜索