Skip to content

Commit

Permalink
登录接口的具体实现
Browse files Browse the repository at this point in the history
  • Loading branch information
bxx committed May 24, 2018
1 parent 0c9032b commit 39e7fb0
Show file tree
Hide file tree
Showing 4 changed files with 68 additions and 1 deletion.
11 changes: 10 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -53,4 +53,13 @@ Mysql版本: 5.7.22
---
> 定义接口基础类,所以其它接口实现都需要继承此类,统一进行认证、异常、返回数据等操作
具体讲解请查看文件```api/__init__.py```
具体讲解请查看文件```api/__init__.py```

八、实现具体的一个接口
---
> 实现一个最基础的登录接口,来演示controller、views、urls、model之间的相互关系
具体讲解请分别查看文件:
```account/controllers.py```
```account/views.py```
```account/urls.py```
14 changes: 14 additions & 0 deletions account/controllers.py
Original file line number Diff line number Diff line change
@@ -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
16 changes: 16 additions & 0 deletions account/urls.py
Original file line number Diff line number Diff line change
@@ -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)
28 changes: 28 additions & 0 deletions account/views.py
Original file line number Diff line number Diff line change
@@ -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

0 comments on commit 39e7fb0

Please sign in to comment.