diff --git a/README.md b/README.md index 7467740..8c25c18 100644 --- a/README.md +++ b/README.md @@ -53,4 +53,13 @@ Mysql版本: 5.7.22 --- > 定义接口基础类,所以其它接口实现都需要继承此类,统一进行认证、异常、返回数据等操作 -具体讲解请查看文件```api/__init__.py``` \ No newline at end of file +具体讲解请查看文件```api/__init__.py``` + +八、实现具体的一个接口 +--- +> 实现一个最基础的登录接口,来演示controller、views、urls、model之间的相互关系 + +具体讲解请分别查看文件: +```account/controllers.py``` +```account/views.py``` +```account/urls.py``` \ No newline at end of file diff --git a/account/controllers.py b/account/controllers.py new file mode 100644 index 0000000..cd56569 --- /dev/null +++ b/account/controllers.py @@ -0,0 +1,14 @@ +# 这里密码使用了明文存储,在实际使用中需要替换成加密后的密码来存储、比较 +from account.models import User +from sqlalchemy import or_ + + +def login(username, password): + user = User.query.filter(or_(User.username==username, User.phone==username, + User.email==username)).filter_by(is_deleted=False).one_or_none() + if not user: + return + if user.password != password: + return + + return user diff --git a/account/urls.py b/account/urls.py new file mode 100644 index 0000000..c5e0749 --- /dev/null +++ b/account/urls.py @@ -0,0 +1,16 @@ +# 这里将url进行统一的管理,每添加一个接口,只需要在urls中添加即可 +from flask import Blueprint + +from .views import Login +from .views import Logout +from .views import Logup + +account_router = Blueprint('account', __name__, url_prefix='/account') + +urls = ( + ('/login', Login()), +) + +methods = ['GET', 'POST'] +for path, view in urls: + account_router.add_url_rule(path, view_func=view, methods=methods) diff --git a/account/views.py b/account/views.py new file mode 100644 index 0000000..f9c7e9c --- /dev/null +++ b/account/views.py @@ -0,0 +1,28 @@ +# 这里有一个点需要说明一下,return data +# 这个data最好采用dict的形式返回,这样在以后接口扩展时可以更好的支持 +from flask import request +from api import Api +from api import errors +from . import controllers as account_ctl +from trace import session + + +class Login(Api): + NEED_LOGIN = False + + def get(self): + pass + + def post(self): + data = request.get_json() + username = data.get('username') + password = data.get('password') + if not (username and password): + raise errors.InvalidArgsError('请填写用户名和密码') + user = account_ctl.login(username, password) + token = session.set_session(user.id) + data = { + 'token': token, + } + + return data