1. Flask介紹
Flask是一個(gè)使用 Python 編寫的輕量級(jí) Web 應(yīng)用框架哈恰,使用簡(jiǎn)單操作方便散罕,很適合開發(fā)輕量級(jí)的API接口蹭睡,讓Android程序員從此不再去問后臺(tái)要測(cè)試接口了车海。
2. 簡(jiǎn)單使用
1.安裝
pip3 install Falsk
2.使用
from flask import Flask
#初始化
app = Flask(__name__)
#路由
@app.route('/')
def gello_world():
return 'Hello Flask'
if __name__ == '__main__':
#開啟service
app.run()
運(yùn)行這個(gè)python文件變啟動(dòng)了服務(wù)碧浊,默認(rèn)8080端口
3. 項(xiàng)目實(shí)戰(zhàn)
實(shí)戰(zhàn)目標(biāo):實(shí)現(xiàn)一個(gè)注冊(cè)登陸的接口砚尽,JSON格式
1.準(zhǔn)備數(shù)據(jù)庫(kù)相關(guān)
字段 | 長(zhǎng)度 | 說(shuō)明 |
---|---|---|
id | bigint | 自增長(zhǎng)主鍵ID |
user | varchar | 用戶名 |
psw | varchar | 用戶密碼 |
registerTime | timestamp | 注冊(cè)時(shí)間 |
phone | varchar | 手機(jī)號(hào)碼 |
2.db.py
數(shù)據(jù)庫(kù)使用的是sqlalchemy
# -*- coding:utf-8 -*-
from operator import or_
from sqlalchemy import create_engine, Table, MetaData
from sqlalchemy.ext.automap import automap_base
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker, mapper
from sqlalchemy.pool import NullPool
import traceback
'''
解決中文亂碼
1.create_engine中添加charset=utf8,encoding='utf-8'
2.表中添加__table_args__ = {
"mysql_charset": "utf8"
}
'''
# 獲取實(shí)體數(shù)據(jù)庫(kù)連接
engine = create_engine('mysql+pymysql://root:1234@127.0.0.1:3306/python?charset=utf8',
encoding='utf-8',
echo=False,
poolclass=NullPool)
metadata = MetaData(engine)
# 反射全庫(kù) 開始
metadata.reflect(bind=engine)
print('獲取所有表名:', metadata.tables.keys())
# 反射全庫(kù) 結(jié)束
Base = automap_base()
Base.prepare(engine, reflect=True)
print('獲取所有對(duì)象名:', Base.classes.keys())
db_session = sessionmaker(bind=engine)
def login(user_name, user_psw):
'''
登陸
:param user_name:
:param user_psw:
:return:
'''
session = db_session()
db_user = Base.classes.user
try:
user = session.query(db_user).filter(
db_user.user == user_name,
db_user.psw == user_psw).one()
return user
except BaseException:
message = traceback.format_exc()
if not message.__contains__('No row was found for one()'):
#無(wú)此用戶信息
print(message)
session.close()
return None
def register(user_name, user_psw, user_phone):
'''
注冊(cè)
:param user_name:
:param user_psw:
:param user_phone:
:return:
'''
session = db_session()
db_user = Base.classes.user
count = session.query(db_user).filter(
or_(db_user.phone == user_phone,
db_user.user == user_name)
).count()
if int(count) > 0:
return False
user = db_user(user=user_name, psw=user_psw, phone=user_phone)
session.add(user)
session.commit()
session.close()
return True
3.servier.py
# 簡(jiǎn)單的flask接口服務(wù)
from flask import Flask, request, jsonify
import sys
import threading
import time
import db
from util import is_phone_num
server = Flask(__name__)
@server.route('/test/login', methods=['GET', 'POST'])
def login():
print(threading.current_thread().name)
username = request.values.get("username")
psw = request.values.get('psw')
if not username or not psw:
return jsonify({'code': 400, 'msg': '參數(shù)缺省'})
user = db2.login(username, psw)
if user:
res = {'code': 200, 'msg': '登錄成功', 'user': {
'username': user.user,
'phone': user.phone,
'registerTime': str(user.registerTime)
}}
else:
res = {'code': 400, 'msg': '賬號(hào)或密碼錯(cuò)誤'}
return jsonify(res)
@server.route('/test/register', methods=['GET', 'POST'])
def register():
username = request.values.get("username")
psw = request.values.get('psw')
phone = request.values.get('phone')
if not username or not psw or not phone:
return jsonify({'code': 400, 'msg': '參數(shù)缺省'})
if not is_phone_num(phone):
return jsonify({'code': 400, 'msg': '手機(jī)號(hào)非法'})
success = db2.register(username, psw, phone)
return jsonify(
{'code': 200 if success else 400, 'msg': '尊敬的{},恭喜您注冊(cè)成功'.format(username) if success else '用戶信息已被注冊(cè)'})
if __name__ == '__main__':
server.run(
port=8889, #自定義端口
debug=True,#是否開啟debug模式
host='192.168.0.105',#指定host
threaded=True#是否開啟多線程
)
4.接口
◣
Path:
http://192.168.0.105:8889/test/register?username=TangRen&psw=m123456&phone=18600000000
{
"code": 200,
"msg": "尊敬的TangRen,恭喜您注冊(cè)成功"
}
◣
Path:
http://192.168.0.105:8889/test/login?username=TangRen&psw=m123456
{
"code": 200,
"msg": "登錄成功",
"user": {
"phone": "18600000000",
"registerTime": "2019-06-24 22:11:46",
"username": "TangRen"
}
}
4. 總結(jié)
Python大法好