本文整理汇总了Python中track.views.server_track函数的典型用法代码示例。如果您正苦于以下问题:Python server_track函数的具体用法?Python server_track怎么用?Python server_track使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了server_track函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。
示例1: process_response
def process_response(self, request, response):
"""Exit the context if it exists."""
try:
tracker.get_tracker().exit_context(CONTEXT_NAME)
except Exception: # pylint: disable=broad-except
pass
# Set spam query string into cookie
spam = request.GET.get('spam')
if spam:
response.set_cookie('spam', spam)
# track session changed
try:
origin_session = request.COOKIES.get('sessionid')
if origin_session and request.session.session_key and request.session.session_key != origin_session:
session_md5 = hashlib.md5()
session_md5.update(request.session.session_key)
origin_session_md5 = hashlib.md5()
origin_session_md5.update(origin_session)
event = {
'changed_session': session_md5.hexdigest(),
'origin_session': origin_session_md5.hexdigest(),
}
views.server_track(request, request.META['PATH_INFO'], event)
except Exception, e:
pass
开发者ID:blendedlearn,项目名称:blended_learning,代码行数:27,代码来源:middleware.py
示例2: test_server_track_with_middleware_and_google_analytics_cookie
def test_server_track_with_middleware_and_google_analytics_cookie(self):
middleware = TrackMiddleware()
request = self.request_factory.get(self.path_with_course)
request.COOKIES['_ga'] = 'GA1.2.1033501218.1368477899'
middleware.process_request(request)
# The middleware emits an event, reset the mock to ignore it since we aren't testing that feature.
self.mock_tracker.reset_mock()
try:
views.server_track(request, str(sentinel.event_type), '{}')
expected_event = {
'accept_language': '',
'referer': '',
'username': 'anonymous',
'ip': '127.0.0.1',
'event_source': 'server',
'event_type': str(sentinel.event_type),
'event': '{}',
'agent': '',
'page': None,
'time': FROZEN_TIME,
'host': 'testserver',
'context': {
'user_id': '',
'course_id': u'foo/bar/baz',
'org_id': 'foo',
'path': u'/courses/foo/bar/baz/xmod/'
},
}
finally:
middleware.process_response(request, None)
self.assert_mock_tracker_call_matches(expected_event)
开发者ID:B-MOOC,项目名称:edx-platform,代码行数:33,代码来源:test_views.py
示例3: post
def post(self, request, format=None):
file_obj = request.FILES.get('file')
now = timezone.now().strftime('%Y%m%d')
log_root = os.path.join(LOG_BASE_ROOT, now)
if not os.path.exists(log_root):
os.mkdir(log_root)
uid = request.user.id
platform = None
http_uuid = request.META.get('HTTP_UUID')
user_agent = request.META.get('HTTP_USER_AGENT', '').lower()
if 'ios' in user_agent:
platform = 'ios'
elif 'android' in user_agent:
platform = 'android'
log_path = os.path.join(log_root, '{}_{}_{}_{}.zip'.format(http_uuid,
uid, platform, uuid.uuid4().hex[:10]))
with open(log_path, 'wb+') as destination:
for chunk in file_obj.chunks():
destination.write(chunk)
server_track(request, 'api.user.upload_log', {
'uid': uid,
'uuid': http_uuid,
'sid': request.META.get('HTTP_SID'),
'log_path': log_path,
})
return Response({'success': True}, status.HTTP_200_OK)
开发者ID:blendedlearn,项目名称:blended_learning,代码行数:27,代码来源:logs.py
示例4: test_server_track_with_middleware
def test_server_track_with_middleware(self):
middleware = TrackMiddleware()
request = self.request_factory.get(self.path_with_course)
middleware.process_request(request)
# The middleware emits an event, reset the mock to ignore it since we aren't testing that feature.
self.mock_tracker.reset_mock()
try:
views.server_track(request, str(sentinel.event_type), '{}')
expected_event = {
'username': 'anonymous',
'ip': '127.0.0.1',
'event_source': 'server',
'event_type': str(sentinel.event_type),
'event': '{}',
'agent': '',
'page': None,
'time': expected_time,
'host': 'testserver',
'context': {
'user_id': '',
'course_id': u'foo/bar/baz',
'org_id': 'foo',
'path': u'/courses/foo/bar/baz/xmod/'
},
}
finally:
middleware.process_response(request, None)
self.mock_tracker.send.assert_called_once_with(expected_event)
开发者ID:AdityaKashyap,项目名称:edx-platform,代码行数:30,代码来源:test_views.py
示例5: process_request
def process_request(self, request):
try:
self.enter_request_context(request)
if not self.should_process_request(request):
return
# Set sessionid and referer if there comes a new user
if not request.COOKIES.get('sessionid'):
request.session.cycle_key()
referer = _get_request_header(request, 'HTTP_REFERER')
if request.session.get('referer') is None:
request.session['referer'] = referer
else:
host = _get_request_header(request, 'HTTP_HOST')
if host and referer and not re.match('https?://%s\/?' % request.META['HTTP_HOST'], request.META['HTTP_REFERER']):
request.session['referer'] = referer
# Removes passwords from the tracking logs
# WARNING: This list needs to be changed whenever we change
# password handling functionality.
#
# As of the time of this comment, only 'password' is used
# The rest are there for future extension.
#
# Passwords should never be sent as GET requests, but
# this can happen due to older browser bugs. We censor
# this too.
#
# We should manually confirm no passwords make it into log
# files when we change this.
censored_strings = ['password', 'newpassword', 'new_password', 'repassword',
'oldpassword', 'old_password', 'new_password1', 'new_password2']
post_dict = dict(request.POST)
get_dict = dict(request.GET)
for string in censored_strings:
if string in post_dict:
post_dict[string] = '*' * 8
if string in get_dict:
get_dict[string] = '*' * 8
event = {'GET': dict(get_dict), 'POST': dict(post_dict)}
# EDXMERGE: 可能会对数据团队造成影响
# TODO: Confirm no large file uploads
#event = json.dumps(event)
#event = event[:512]
views.server_track(request, request.META['PATH_INFO'], event)
except Exception, e:
pass
开发者ID:blendedlearn,项目名称:blended_learning,代码行数:51,代码来源:middleware.py
示例6: post
def post(self, request):
"""Modify user's setting for receiving emails from a course."""
username = request.DATA.get('username')
try:
user = User.objects.get(username=username)
except ObjectDoesNotExist:
return Response(
status=status.HTTP_400_BAD_REQUEST,
data={"message": u"User {username} does not exist".format(username=username)}
)
course_id = request.DATA.get('course_id')
if not course_id:
return Response(
status=status.HTTP_400_BAD_REQUEST,
data={"message": u"Course ID must be specified."}
)
try:
course_key = CourseKey.from_string(course_id)
except InvalidKeyError:
return Response(
status=status.HTTP_400_BAD_REQUEST,
data={
"message": u"No course '{course_id}' found".format(course_id=course_id)
}
)
receive_emails = request.DATA.get("subscribe")
if receive_emails:
optout_object = Optout.objects.filter(user=user, course_id=course_key)
if optout_object:
optout_object.delete()
log.info(
u"User %s (%s) opted in to receive emails from course %s",
user.username,
user.email,
course_id
)
track_views.server_track(request, "change-email-settings", {"receive_emails": "no", "course": course_id})
else:
Optout.objects.get_or_create(user=user, course_id=course_key)
log.info(
u"User %s (%s) opted out of receiving emails from course %s",
user.username,
user.email,
course_id
)
track_views.server_track(request, "change-email-settings", {"receive_emails": "yes", "course": course_id})
return Response(status=status.HTTP_200_OK)
开发者ID:miptliot,项目名称:open_edx_api_extension,代码行数:50,代码来源:views.py
示例7: post
def post(self, request, course_id, format=None):
""" Enroll in Course """
user = request.user
err = {}
try:
course_key = SlashSeparatedCourseKey.from_deprecated_string(course_id)
course = course_from_key(course_key)
except ItemNotFoundError:
err['err_type'] = 'InvalidCourseId'
err['err_msg'] = _("Course id is invalid")
return Response(err, status=status.HTTP_400_BAD_REQUEST)
if not has_access(user, 'enroll', course):
err['err_type'] = 'InvalidEnrollment'
err['err_msg'] = _("Enrollment is closed")
return Response(err, status=status.HTTP_400_BAD_REQUEST)
# see if we have already filled up all allowed enrollments
is_course_full = CourseEnrollment.is_course_full(course)
if is_course_full:
err['err_type'] = 'InvalidEnrollment'
err['err_msg'] = _("Course is full")
return Response(err, status=status.HTTP_400_BAD_REQUEST)
# If this course is available in multiple modes, redirect them to a page
# where they can choose which mode they want.
available_modes = CourseMode.modes_for_course(course_id)
available_modes_dict = CourseMode.modes_for_course_dict(course_id, available_modes)
if CourseMode.has_verified_mode(available_modes_dict):
err['err_type'] = 'InvalidEnrollment'
err['err_msg'] = _("Missing course mode")
return Response(err, status=status.HTTP_400_BAD_REQUEST)
current_mode = available_modes[0]
course_key = SlashSeparatedCourseKey.from_deprecated_string(course_id)
dog_stats_api.increment(
"common.student.enrollment",
tags=[u"org:{0}".format(course_key.org),
u"course:{0}".format(course_key.course),
u"run:{0}".format(course_key.run)]
)
server_track(request, 'api.course.enrollment', {
'username': user.username,
'course_id': course_id,
})
CourseEnrollment.enroll(user, course.id, mode=current_mode.slug)
return Response()
开发者ID:blendedlearn,项目名称:blended_learning,代码行数:50,代码来源:enrollment.py
示例8: post
def post(self, request, provider):
data = request.DATA
uid = data.get('uid')
access_token = data.get('access_token')
strategy = get_strategy(provider)
social_response = {
'access_token': access_token,
'uid': uid,
'openid': uid,
'provider': provider,
}
log.info('api.oauth.bind.outer.login\n{}'.format(social_response))
if provider == 'qq':
social_response.update({
'SOCIAL_AUTH_QQ_KEY': settings.SOCIAL_AUTH_MOBILE_QQ_OAUTH_CONSUMER_KEY
})
try:
# 请求三方接口获得用户信息
detail = strategy.backend.user_data(access_token, response=social_response)
log.info('api.user.bind.oauth.login.response\n{}'.format(detail))
if 'errcode' in detail:
server_track(request, 'api.user.oauth.bind_failure', {
'bind_type': 'social_oauth',
'provider': provider,
'uid': request.user.id,
'error': {
'msg': u'三方登录失败',
'detail': detail,
},
})
raise error.Error(error.SOCIAL_OAUTH_LOGIN_FAILED, u'三分登陆失败')
except Exception as ex:
server_track(request, 'api.user.oauth.bind_failure', {
'bind_type': 'social_oauth',
'provider': provider,
'uid': request.user.id,
'error': {
'msg': ex.__class__.__name__,
}
})
raise error.Error(error.SOCIAL_OAUTH_LOGIN_FAILED, u'三分登陆失败')
try:
_new_association(strategy, detail, request.user, created_on='mobile_bind')
server_track(request, 'api.user.oauth.bind_success', {
'unbind_type': 'social_oauth',
'provider': provider,
'uid': request.user.id
})
except AuthAlreadyAssociated as ex:
server_track(request, 'api.user.oauth.bind_failure', {
'bind_type': 'social_oauth',
'provider': provider,
'uid': request.user.id,
'error': {
'msg': ex.__class__.__name__,
}
})
raise error.Error(error.SOCIAL_OAUTH_AUTH_ALREADY_ASSOCIATED, u'该账号已被其它账号绑定')
return Response(status=status.HTTP_201_CREATED)
开发者ID:blendedlearn,项目名称:blended_learning,代码行数:60,代码来源:oauth.py
示例9: test_server_track_with_no_request
def test_server_track_with_no_request(self):
request = None
views.server_track(request, str(sentinel.event_type), '{}')
expected_event = {
'username': 'anonymous',
'ip': '',
'event_source': 'server',
'event_type': str(sentinel.event_type),
'event': '{}',
'agent': '',
'page': None,
'time': expected_time,
'host': '',
'context': {},
}
开发者ID:blendedlearn,项目名称:blended_learning,代码行数:16,代码来源:test_views.py
示例10: emit_event
def emit_event(self, event_name):
"""
Emits an event to explicitly track course enrollment and unenrollment.
"""
try:
context = contexts.course_context_from_course_id(self.course_id)
data = {"user_id": self.user.id, "course_id": self.course_id, "mode": self.mode}
with tracker.get_tracker().context(event_name, context):
server_track(crum.get_current_request(), event_name, data)
except: # pylint: disable=bare-except
if event_name and self.course_id:
log.exception(
"Unable to emit event %s for user %s and course %s", event_name, self.user.username, self.course_id
)
开发者ID:hmcmooc,项目名称:edx-platform,代码行数:16,代码来源:models.py
示例11: test_server_track_with_no_request
def test_server_track_with_no_request(self):
request = None
views.server_track(request, str(sentinel.event_type), "{}")
expected_event = {
"username": "anonymous",
"ip": "",
"event_source": "server",
"event_type": str(sentinel.event_type),
"event": "{}",
"agent": "",
"page": None,
"time": expected_time,
"host": "",
"context": {},
}
self.mock_tracker.send.assert_called_once_with(expected_event)
开发者ID:Bvic,项目名称:edx-platform,代码行数:17,代码来源:test_views.py
示例12: test_server_track
def test_server_track(self):
request = self.request_factory.get(self.path_with_course)
views.server_track(request, str(sentinel.event_type), "{}")
expected_event = {
"username": "anonymous",
"ip": "127.0.0.1",
"event_source": "server",
"event_type": str(sentinel.event_type),
"event": "{}",
"agent": "",
"page": None,
"time": expected_time,
"host": "testserver",
"context": {},
}
self.mock_tracker.send.assert_called_once_with(expected_event)
开发者ID:Bvic,项目名称:edx-platform,代码行数:17,代码来源:test_views.py
示例13: test_server_track_with_no_request
def test_server_track_with_no_request(self):
request = None
views.server_track(request, str(sentinel.event_type), '{}')
expected_event = {
'username': 'anonymous',
'ip': '',
'event_source': 'server',
'event_type': str(sentinel.event_type),
'event': '{}',
'agent': '',
'page': None,
'time': self._expected_timestamp,
'host': '',
'context': {},
}
self.mock_tracker.send.assert_called_once_with(expected_event)
开发者ID:Bachmann1234,项目名称:edx-platform,代码行数:17,代码来源:test_views.py
示例14: test_server_track
def test_server_track(self):
request = self.request_factory.get(self.path_with_course)
views.server_track(request, str(sentinel.event_type), '{}')
expected_event = {
'username': 'anonymous',
'ip': '127.0.0.1',
'event_source': 'server',
'event_type': str(sentinel.event_type),
'event': '{}',
'agent': '',
'page': None,
'time': expected_time,
'host': 'testserver',
'context': {},
}
self.mock_tracker.send.assert_called_once_with(expected_event)
开发者ID:AdityaKashyap,项目名称:edx-platform,代码行数:17,代码来源:test_views.py
示例15: post
def post(self, request):
post_vars = request.DATA
check_phone_number(post_vars)
check_validate_used(post_vars)
user = request.user
phone_number = post_vars.get('phone')
password = post_vars.get('password')
if password:
if user.password != '!':
server_track(request, 'api.user.phone.bind_failure', {
'bind_type': 'phone',
'provider': '',
'uid': request.user.id,
'error': {
'msg': 'PASSWORD_ALREADY_BIND',
'detail': phone_number,
}
})
raise error.Error(error.PASSWORD_ALREADY_BIND, u'之前已绑定密码')
user.set_password(password)
profile = user.profile
if profile.phone_number:
server_track(request, 'api.user.phone.bind_failure', {
'bind_type': 'phone',
'provider': '',
'uid': request.user.id,
'error': {
'msg': 'PASSWORD_ALREADY_BIND',
'detail': phone_number,
}
})
raise error.Error(error.PASSWORD_ALREADY_BIND, u'该手机已被注册或绑定')
check_validate_used(post_vars)
profile.phone_number = phone_number
try:
profile.save()
except IntegrityError:
server_track(request, 'api.user.phone.bind_failure', {
'bind_type': 'phone',
'provider': '',
'uid': request.user.id,
'error': {
'msg': 'PHONE_NUMBER_EXIST',
'detail': phone_number,
}
})
raise error.Error(error.PHONE_NUMBER_EXIST, u'该手机已被注册或绑定')
user.save()
server_track(request, 'api.user.phone.bind_success', {
'bind_type': 'phone',
'provider': '',
'uid': user.id,
'phone_number': phone_number
})
return Response(status=status.HTTP_204_NO_CONTENT)
开发者ID:blendedlearn,项目名称:blended_learning,代码行数:55,代码来源:user.py
示例16: delete
def delete(self, request, course_id, format=None):
""" Unenroll the current course. """
user = request.user
if not CourseEnrollment.is_enrolled(user, course_id):
return error.ErrorResponse(error.USER_NOT_ENROLLED, "Course id is invalid", status=status.HTTP_404_NOT_FOUND)
course_key = SlashSeparatedCourseKey.from_deprecated_string(course_id)
CourseEnrollment.unenroll(user, course_key)
dog_stats_api.increment(
"common.student.unenrollment",
tags=["org:{0}".format(course_key.org),
"course:{0}".format(course_key.course),
"run:{0}".format(course_key.run)]
)
server_track(request, 'api.course.unenrollment', {
'username': user.username,
'course_id': course_id,
})
return Response(status=status.HTTP_204_NO_CONTENT)
开发者ID:blendedlearn,项目名称:blended_learning,代码行数:18,代码来源:course.py
示例17: post
def post(self, request, format=None):
# url(r'^s_log/?$', tv.SimpleLogView.as_view(), name='v2_simple_log')
log_content = request.DATA['log_content']
log_arrays = log_content.split('\n')
for log_content in log_arrays:
s_content = strip(log_content)
if s_content:
server_track(request, 'api.user.simple_log', {
'uid': request.user.id,
'uuid': request.META.get('HTTP_UUID'),
'sid': request.META.get('HTTP_SID'),
'log_content': s_content,
'log_content_format': 'json',
})
return Response(status=status.HTTP_201_CREATED)
开发者ID:blendedlearn,项目名称:blended_learning,代码行数:18,代码来源:tv.py
示例18: test_server_track_with_no_request
def test_server_track_with_no_request(self):
request = None
views.server_track(request, str(sentinel.event_type), '{}')
expected_event = {
'accept_language': '',
'referer': '',
'username': 'anonymous',
'ip': '',
'event_source': 'server',
'event_type': str(sentinel.event_type),
'event': '{}',
'agent': '',
'page': None,
'time': FROZEN_TIME,
'host': '',
'context': {},
}
self.assert_mock_tracker_call_matches(expected_event)
开发者ID:B-MOOC,项目名称:edx-platform,代码行数:19,代码来源:test_views.py
示例19: password
def password(self, request, data, client):
"""
Handle ``grant_type=password`` requests as defined in :draft:`4.3`.
"""
data = self.get_password_grant(request, data, client)
user = data.get('user')
scope = data.get('scope')
if constants.SINGLE_ACCESS_TOKEN:
at = self.get_access_token(request, user, scope, client)
else:
at = self.create_access_token(request, user, scope, client)
rt = self.create_refresh_token(request, user, scope, at, client)
# track user login ip
# TODO: track in authorization grant typer last login ip in auth_userprofile
user_profile = UserProfile.objects.get(user=user)
user_profile.last_login_ip = request.META.get('REMOTE_ADDR', None)
user_profile.save()
sid = request.META.get('HTTP_SID')
uid = user.id
uuid = request.META.get('HTTP_UUID')
if uuid:
device, _ = DeviceInfo.objects.get_or_create(uuid=uuid)
device.uid = uid
device.save()
if sid:
timestamp = time.time()
IDsInfo.new(sid, uid, uuid, timestamp)
response = self.access_token_response(at)
set_login_response_header(request, response)
login_type = response.get('login_type', '')
server_track(request, 'api.user.login_success', {
'uid': user.id,
'username': user.username,
'login_type': login_type,
})
return response
开发者ID:blendedlearn,项目名称:blended_learning,代码行数:41,代码来源:views.py
示例20: process_request
def process_request(self, request):
try:
self.enter_course_context(request)
if not self.should_process_request(request):
return
# Removes passwords from the tracking logs
# WARNING: This list needs to be changed whenever we change
# password handling functionality.
#
# As of the time of this comment, only 'password' is used
# The rest are there for future extension.
#
# Passwords should never be sent as GET requests, but
# this can happen due to older browser bugs. We censor
# this too.
#
# We should manually confirm no passwords make it into log
# files when we change this.
censored_strings = ['password', 'newpassword', 'new_password',
'oldpassword', 'old_password']
post_dict = dict(request.POST)
get_dict = dict(request.GET)
for string in censored_strings:
if string in post_dict:
post_dict[string] = '*' * 8
if string in get_dict:
get_dict[string] = '*' * 8
event = {'GET': dict(get_dict),
'POST': dict(post_dict)}
# TODO: Confirm no large file uploads
event = json.dumps(event)
event = event[:512]
views.server_track(request, request.META['PATH_INFO'], event)
except:
pass
开发者ID:SarthakDev,项目名称:edx-platform,代码行数:41,代码来源:middleware.py
注:本文中的track.views.server_track函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论