import React from 'react';
import ReactDom from 'react-dom';
-import {HashRouter as Router, Route, Link, Redirect, Switch} from 'react-router-dom';
+import {BrowserRouter as Router, Route, Link, Redirect, Switch} from 'react-router-dom';
import createHistory from 'history/createHashHistory'
const history = createHistory()
import {spring, AnimatedRoute, AnimatedSwitch} from 'react-router-transition';
}
// logout
- onLogout(){
- _user.logout().then(res => {
- _util.removeStorage('userInfo');
- window.location.href = '/login';
- }, errMsg => {
- _util.errorTips(errMsg);
- });
+ onLogout() {
+ _util.removeStorage('userInfo');
+ window.location.href = '/login';
}
render() {
if (isLoggedIn) {
button = <li className="dropdown loggedin">
<a className="dropdown-toggle" data-toggle="dropdown" href="#" aria-expanded="false">
- <img className="img-circle img-thumbnail user-head-pic" src={require('image/slonik.png')} alt="headPic"/>
+ <img className="img-circle img-thumbnail user-head-pic" src={require('image/slonik.png')}
+ alt="headPic"/>
</a>
<ul className="dropdown-menu dropdown-alerts loggedin-ul">
<li>
- <a href="#">
+ <Link to="/portal">
<div>
<i className="fa fa-tasks fa-fw"></i> My machines
</div>
- </a>
+ </Link>
</li>
<li className="divider"></li>
<li>
- <a href="#">
+ <a onClick={() => {this.onLogout()}}>
<div>
<i className="fa fa-upload fa-fw"></i> Log out
</div>
Farm</b></a>
</div>
<ul className="nav navbar-top-links navbar-left">
- <li><Link to="/home"> <span className="glyphicon glyphicon-home" aria-hidden="true"></span> Home</Link>
+ <li><Link to="/home"> <span className="glyphicon glyphicon-home" aria-hidden="true"></span>
+ Home</Link>
</li>
<li><Link to="/status"><span className="glyphicon glyphicon-tasks" aria-hidden="true"></span>Status</Link>
</li>
userinfo: res.userinfo,
});
}, errMsg => {
- _mm.errorTips(errMsg);
+ _util.errorTips(errMsg);
});
}
isLoading: false
});
}, errMsg => {
- _mm.errorTips(errMsg);
+ _util.errorTips(errMsg);
});
}
+ onLogout(){
+ _util.removeStorage('userInfo');
+ window.location.href = '/login';
+ // _user.logout().then(res => {
+ // _util.removeStorage('userInfo');
+ // window.location.href = '/login';
+ // }, errMsg => {
+ // _util.errorTips(errMsg);
+ // });
+ }
render() {
let show = this.state.isLoading ? "none" : "block";
<a href="\add-machine" className="list-group-item">
<i className="fa fa-globe fa-fw"></i> Add a New Mchine
</a>
- <a href="\logout" className="list-group-item">
+ <a onClick={() => {this.onLogout()}} className="list-group-item">
<i className="fa fa-arrow-left fa-fw"></i> Logout
</a>
</div>
}
// logout
logout(){
- let url = PGConstant.base_url + '/logout';
- return _util.request({
- type : 'post',
- url : url
- });
+ // let url = PGConstant.base_url + '/logout';
+ // return _util.request({
+ // type : 'post',
+ // url : url
+ // });
+ return true;
}
getUserMachineManageList(pageNum){
name:'好123',
- USER_UNLOGIN_CODE:10,
+ UnauthorizedCode:401,// unlogin
};
export default object;
\ No newline at end of file
-
import PGConstant from 'util/constant.jsx'
// const _const = new PGConstant();
class PGUtil {
request(param) {
return new Promise((resolve, reject) => {
let user = this.getStorage('userInfo')
+ let beforeSendFunc = (xhr) => {}
+ if (user.token) {
+ beforeSendFunc = (xhr) => xhr.setRequestHeader("Authorization", 'Token ' + user.token);
+ }
$.ajax({
type: param.type || 'get',
url: param.url || '',
dataType: param.dataType || 'json',
data: param.data || null,
- headers:{
- 'Authorization': 'Token ' + user.token
- },
+ // headers: {
+ // 'Authorization': 'Token ' + user.token
+ // },
+ beforeSend: beforeSendFunc,
success: res => {
// request success
-
+ console.dir(res)
typeof resolve === 'function' && resolve(res, res.msg);
if (0 === res.status) {
typeof resolve === 'function' && resolve(res.data, res.msg);
- }
- // nologin force to login
- else if (PGConstant.USER_UNLOGIN_CODE === res.status) {
- this.doLogin();
- }
- else {
+ } else {
typeof reject === 'function' && reject(res.msg || res.data);
}
},
error: err => {
- typeof reject === 'function' && reject(err.statusText);
+ console.log('here is err')
+ console.dir(err.status)
+ // nologin force to login
+ if (PGConstant.UnauthorizedCode === err.status) {
+ this.doLogin();
+ } else {
+ typeof reject === 'function' && reject(err.statusText);
+ }
+
}
});
});
}
// redirect to login
- doLogin(){
+ doLogin() {
window.location.href = '/login?redirect=' + encodeURIComponent(window.location.pathname);
+ // window.location.href = '/login';
}
- getUrlParam(name){
+ getUrlParam(name) {
// param=123¶m1=456
let queryString = window.location.search.split('?')[1] || '',
- reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)"),
- result = queryString.match(reg);
+ reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)"),
+ result = queryString.match(reg);
return result ? decodeURIComponent(result[2]) : null;
}
getDateStr(AddDayCount) {
let dd = new Date();
- dd.setDate(dd.getDate()+AddDayCount);
+ dd.setDate(dd.getDate() + AddDayCount);
let y = dd.getFullYear();
- let m = (dd.getMonth()+1)<10?"0"+(dd.getMonth()+1):(dd.getMonth()+1);
- let d = dd.getDate()<10?"0"+dd.getDate():dd.getDate();
- return y+"-"+m+"-"+d;
+ let m = (dd.getMonth() + 1) < 10 ? "0" + (dd.getMonth() + 1) : (dd.getMonth() + 1);
+ let d = dd.getDate() < 10 ? "0" + dd.getDate() : dd.getDate();
+ return y + "-" + m + "-" + d;
}
}
"""
List test records
"""
+
queryset = TestRecord.objects.all().order_by('add_time')
serializer_class = TestRecordListSerializer
pagination_class = StandardResultsSetPagination
from __future__ import unicode_literals
from django.shortcuts import render
-from rest_framework import mixins, viewsets, permissions
+from rest_framework import mixins, viewsets, permissions, status
from rest_framework import authentication
+from rest_framework.response import Response
+from rest_framework.views import APIView
from rest_framework_jwt.authentication import JSONWebTokenAuthentication
-
+from util.response import PGJsonResponse
from models import UserMachine
from serializer import UserMachineManageSerializer
serializer_class = UserMachineManageSerializer
# pagination_class = StandardResultsSetPagination
+
+
+# class UserMachineList(APIView):
+# authentication_classes = (JSONWebTokenAuthentication,)
+# permission_classes = (permissions.IsAuthenticated,)
+#
+# def get(self, request, format=None):
+# machines = UserMachine.objects.all().order_by('add_time')
+# serializer = UserMachineManageSerializer(machines, many=True)
+#
+# return PGJsonResponse(data=serializer.data, code=status.HTTP_200_OK, desc='get user machine list success')
+
+
class UserMachinePermission(permissions.BasePermission):
"""
- Machine permission check
+ Machine upload permission check
"""
def has_permission(self, request, view):
secret = request.data.secret
- ret = UserMachine.objects.filter(machine_secret=secret,is_active=1).exists()
- return ret
\ No newline at end of file
+ ret = UserMachine.objects.filter(machine_secret=secret, is_active=1).exists()
+ return ret
--- /dev/null
+from rest_framework.views import exception_handler
+
+
+def custom_exception_handler(exc, context):
+ # Call REST framework's default exception handler first,
+ # to get the standard error response.
+ response = exception_handler(exc, context)
+
+ # Now add the HTTP status code to the response.
+ if response is not None:
+ response.data['code'] = response.status_code
+ response.data['desc'] = response.data['detail']
+ # response.data['data'] = None #可以存在
+ del response.data['detail'] # 删除detail字段
+
+ return response
--- /dev/null
+from django.utils import six
+from rest_framework.response import Response
+from rest_framework.serializers import Serializer
+
+class PGJsonResponse(Response):
+ """
+ An HttpResponse that allows its data to be rendered into
+ arbitrary media types.
+ """
+
+ def __init__(self, data=None, code=None, desc=None,
+ status=None,
+ template_name=None, headers=None,
+ exception=False, content_type=None):
+ """
+ Alters the init arguments slightly.
+ For example, drop 'template_name', and instead use 'data'.
+ Setting 'renderer' and 'media_type' will typically be deferred,
+ For example being set automatically by the `APIView`.
+ """
+ super(Response, self).__init__(None, status=status)
+
+ if isinstance(data, Serializer):
+ msg = (
+ 'You passed a Serializer instance as data, but '
+ 'probably meant to pass serialized `.data` or '
+ '`.error`. representation.'
+ )
+ raise AssertionError(msg)
+
+ self.data = {"code": code, "desc": desc, "data": data}
+ self.template_name = template_name
+ self.exception = exception
+ self.content_type = content_type
+
+ if headers:
+ for name, value in six.iteritems(headers):
+ self[name] = value
\ No newline at end of file
# ),
# 'DEFAULT_FILTER_BACKENDS': ('django_filters.rest_framework.DjangoFilterBackend',),
-
+ # 'EXCEPTION_HANDLER': (
+ # 'dataAPI.common.api_exception.custom_exception_handler'
+ # ),
'DEFAULT_AUTHENTICATION_CLASSES': (
'rest_framework_jwt.authentication.JSONWebTokenAuthentication',
'rest_framework.authentication.BasicAuthentication',
}
DB_ENUM = {
- "mode":{
- "simple":1,
- "other":2
+ "mode": {
+ "simple": 1,
+ "other": 2
},
"status": {
"none": -1,
APPEND_SLAS = False
-
CORS_ALLOW_CREDENTIALS = True
CORS_ORIGIN_ALLOW_ALL = True
CORS_ORIGIN_WHITELIST = (
JWT_AUTH = {
'JWT_RESPONSE_PAYLOAD_HANDLER':
- 'users.jwt_handler.jwt_response_payload_handler',
+ 'users.jwt_handler.jwt_response_payload_handler',
'JWT_EXPIRATION_DELTA': datetime.timedelta(seconds=7200),
'JWT_AUTH_HEADER_PREFIX': 'Token',
-}
\ No newline at end of file
+}
# url(r'status/$', TestListView.as_view(), name='test-list'),
# url(r'detail', TestRecordDetailViewSet ,name="detail"),
url(r'upload/$', TestRecordCreate, name='test-upload'),
+ # url(r'my-machine/$', UserMachineList.as_view(), name='my-machine'),
+
url(r'docs/', include_docs_urls(title='pgperffarm')),
# Static pages
# url(r'^$', 'pgperffarm.views.index', name='index'),