Best Python code snippet using lemoncheesecake
api.py
Source:api.py
1__author__ = 'Matteo Balasso <m.balasso@scsitaly.com>'2import json3from django.db.models import Q, ObjectDoesNotExist4from django.contrib.auth.models import User, Group5from django.http import HttpResponse6from piston.handler import BaseHandler7from permissions.utils import add_local_role8from masterinterface.scs_auth.auth import authenticate9from models import VPHShareSmartGroup, InstitutionPortal10from config import group_manager11class search_user(BaseHandler):12 """13 REST service based on Django-Piston Library.\n14 """15 def read(self, request, ticket='', term=''):16 """17 Process a search user request.18 Arguments:19 request (HTTP request istance): HTTP request send from client.20 ticket (string) : base 64 ticket.21 term (string) : search term22 Return:23 Successes - Json/xml/yaml format response24 Failure - 403 error25 """26 try:27 if request.GET.get('ticket'):28 client_address = request.META['REMOTE_ADDR']29 user, tkt64 = authenticate(ticket=request.GET['ticket'], cip=client_address)30 if user is not None:31 term = request.GET.get('term', '')32 users = User.objects.filter(33 Q(username__icontains=term) | Q(email__icontains=term) | Q(first_name__icontains=term) | Q(34 last_name__icontains=term)35 )36 return [{"username": user.username, "fullname": "%s %s" % (user.first_name, user.last_name),37 "email": user.email} for user in users]38 else:39 response = HttpResponse(status=403)40 response._is_string = True41 return response42 except Exception, e:43 from raven.contrib.django.raven_compat.models import client44 client.captureException()45 response = HttpResponse(status=500)46 response._is_string = True47 return response48class search_userandgroup(BaseHandler):49 """50 REST service based on Django-Piston Library.\n51 """52 def read(self, request, ticket='', term=''):53 """54 Process a search user request.55 Arguments:56 request (HTTP request istance): HTTP request send from client.57 ticket (string) : base 64 ticket.58 term (string) : search term59 Return:60 Successes - Json/xml/yaml format response61 Failure - 403 error62 """63 try:64 if request.GET.get('ticket'):65 client_address = request.META['REMOTE_ADDR']66 user, tkt64 = authenticate(ticket=request.GET['ticket'], cip=client_address)67 if user is not None:68 term = request.GET.get('term', '')69 users = User.objects.filter(70 Q(username__icontains=term) | Q(email__icontains=term) | Q(first_name__icontains=term) | Q(last_name__icontains=term)71 )72 groups = Group.objects.filter(name__icontains=term)73 return {74 "users": [{"username": user.username, "fullname": "%s %s" % (user.first_name, user.last_name)} for user in users],75 "groups": [{"groupname": g.name, "subscribers": len(g.user_set.all())} for g in groups],76 }77 else:78 response = HttpResponse(status=403)79 response._is_string = True80 return response81 except Exception, e:82 from raven.contrib.django.raven_compat.models import client83 client.captureException()84 response = HttpResponse(status=500)85 response._is_string = True86 return response87class search_group(BaseHandler):88 """89 REST service based on Django-Piston Library.\n90 """91 def read(self, request, ticket='', term=''):92 """93 Process a search group request.94 Arguments:95 request (HTTP request istance): HTTP request send from client.96 ticket (string) : base 64 ticket.97 term (string) : search term98 Return:99 Successes - Json/xml/yaml format response100 Failure - 403 error101 """102 try:103 if request.GET.get('ticket'):104 client_address = request.META['REMOTE_ADDR']105 user, tkt64 = authenticate(ticket=request.GET['ticket'], cip=client_address)106 if user is not None:107 term = request.GET.get('term', '')108 groups = Group.objects.filter(name__icontains=term)109 return [{"groupname": g.name, "subscribers": len(g.user_set.all())} for g in groups]110 else:111 response = HttpResponse(status=403)112 response._is_string = True113 return response114 except Exception, e:115 from raven.contrib.django.raven_compat.models import client116 client.captureException()117 response = HttpResponse(status=500)118 response._is_string = True119 return response120def can_be_child(child, parent):121 if str(child.name).lower() == str(parent.name).lower():122 return False123 if parent.parent:124 return can_be_child(child, parent.parent.vphsharesmartgroup)125 return True126class create_group(BaseHandler):127 """128 REST service based on Django-Piston Library.\n129 """130 def read(self, request, ticket='', name='', parent=''):131 """132 Create a smart group133 Arguments:134 request (HTTP request istance): HTTP request send from client.135 ticket (string) : base 64 ticket.136 group (string) : the group name137 parent (string): the parent group name (optional)138 Return:139 Successes - Json/xml/yaml format response140 Failure - 403 error141 """142 try:143 if request.GET.get('ticket'):144 client_address = request.META['REMOTE_ADDR']145 user, tkt64 = authenticate(ticket=request.GET['ticket'], cip=client_address)146 if user is not None:147 name = request.GET.get('group')148 # check if a user with the group name exists149 try:150 User.objects.get(username__iexact=name) #select case-insensitive151 response = HttpResponse(status=500)152 response._is_string = True153 return response154 except ObjectDoesNotExist, e:155 pass156 try:157 Group.objects.get(name__iexact=name) #select case-insensitive158 response = HttpResponse(status=500)159 response._is_string = True160 return response161 except ObjectDoesNotExist, e:162 pass163 parent = request.GET.get('parent', '')164 group = VPHShareSmartGroup.objects.create(name=name)165 group.managers.add(user)166 group.user_set.add(user)167 add_local_role(group, user, group_manager)168 if parent:169 try:170 group.parent = Group.objects.get(name=parent)171 except ObjectDoesNotExist, e:172 pass173 group.save()174 response = HttpResponse(status=200)175 response._is_string = True176 response.write("OK")177 return response178 else:179 response = HttpResponse(status=403)180 response._is_string = True181 return response182 except Exception, e:183 from raven.contrib.django.raven_compat.models import client184 client.captureException()185 response = HttpResponse(status=500)186 response._is_string = True187 return response188class delete_group(BaseHandler):189 """190 REST service based on Django-Piston Library.\n191 """192 def read(self, request, ticket='', name=''):193 """194 Delete a smart group195 Arguments:196 request (HTTP request istance): HTTP request send from client.197 ticket (string) : base 64 ticket.198 group (string) : the group name199 Return:200 Successes - Json/xml/yaml format response201 Failure - 403 error202 """203 try:204 if request.GET.get('ticket'):205 client_address = request.META['REMOTE_ADDR']206 user, tkt64 = authenticate(ticket=request.GET['ticket'], cip=client_address)207 if user is not None:208 name = request.GET.get('group')209 group = VPHShareSmartGroup.objects.get(name=name)210 if not user in group.managers.all():211 response = HttpResponse(status=403)212 response._is_string = True213 return response214 group.active = False215 group.remove_users()216 # remove this group from children parent reference217 for child in VPHShareSmartGroup.objects.filter(parent=group):218 child.parent = None219 child.save()220 group.parent = None221 group.save()222 response = HttpResponse(status=200)223 response._is_string = True224 response.write("OK")225 return response226 else:227 response = HttpResponse(status=403)228 response._is_string = True229 return response230 except Exception, e:231 from raven.contrib.django.raven_compat.models import client232 client.captureException()233 response = HttpResponse(status=500)234 response._is_string = True235 return response236def add_user_to_group(user, group):237 group.user_set.add(user)238 for child in VPHShareSmartGroup.objects.filter(parent=group):239 add_user_to_group(user, child)240class add_to_group(BaseHandler):241 """242 REST service based on Django-Piston Library.\n243 """244 def read(self, request, ticket='', group='', name=''):245 """246 Add a user to a smart group247 Arguments:248 request (HTTP request istance): HTTP request send from client.249 ticket (string) : base 64 ticket.250 group (string) : the group name251 name (string) : the username or the group name to add252 Return:253 Successes - Json/xml/yaml format response254 Failure - 403 error255 """256 try:257 if request.GET.get('ticket'):258 client_address = request.META['REMOTE_ADDR']259 user, tkt64 = authenticate(ticket=request.GET['ticket'], cip=client_address)260 if user is not None:261 group = VPHShareSmartGroup.objects.get(name=request.GET.get('group'))262 if not group.is_manager(user):263 response = HttpResponse(status=403)264 response._is_string = True265 return response266 try:267 user_to_add = User.objects.get(username=request.GET.get('name'))268 # add user to all children groups269 if request.GET.get('recursive', False):270 add_user_to_group(user_to_add, group)271 else:272 group.user_set.add(user_to_add)273 except ObjectDoesNotExist, e:274 try:275 group_to_add = VPHShareSmartGroup.objects.get(name=request.GET.get('name'))276 if not can_be_child(group_to_add, group):277 response = HttpResponse(status=500, content="constraint violation circularity")278 response._is_string = True279 return response280 group_to_add.parent = group281 group_to_add.save()282 except ObjectDoesNotExist, e:283 response = HttpResponse(status=403)284 response._is_string = True285 return response286 response = HttpResponse(status=200)287 response._is_string = True288 response.write("OK")289 return response290 else:291 response = HttpResponse(status=403)292 response._is_string = True293 return response294 except Exception, e:295 from raven.contrib.django.raven_compat.models import client296 client.captureException()297 response = HttpResponse(status=500)298 response._is_string = True299 return response300class remove_user_from_group(BaseHandler):301 """302 REST service based on Django-Piston Library.\n303 """304 def read(self, request, ticket='', group='', username='', recursive=False):305 """306 Remove a user from a smart group307 Arguments:308 request (HTTP request istance): HTTP request send from client.309 ticket (string) : base 64 ticket.310 group (string) : the group name311 username (string) : the username312 recursive (string) : if present the user will be removed from all the tree of group313 Return:314 Successes - Json/xml/yaml format response315 Failure - 403 error316 """317 try:318 if request.GET.get('ticket'):319 client_address = request.META['REMOTE_ADDR']320 user, tkt64 = authenticate(ticket=request.GET['ticket'], cip=client_address)321 if user is not None:322 group = VPHShareSmartGroup.objects.get(name=request.GET.get('group'))323 user_to_remove = User.objects.get(username=request.GET.get('username'))324 if not group.is_manager(user):325 response = HttpResponse(status=403)326 response._is_string = True327 return response328 if request.GET.get('recursive', False):329 # remove user from all sub groups330 while group is not None:331 group.user_set.remove(user_to_remove)332 try:333 group = VPHShareSmartGroup.objects.get(parent=group)334 except ObjectDoesNotExist, e:335 group = None336 else:337 # remove only from this group338 group.user_set.remove(user_to_remove)339 response = HttpResponse(status=200)340 response._is_string = True341 response.write("OK")342 return response343 else:344 response = HttpResponse(status=403)345 response._is_string = True346 return response347 except Exception, e:348 from raven.contrib.django.raven_compat.models import client349 client.captureException()350 response = HttpResponse(status=500)351 response._is_string = True352 return response353class group_members(BaseHandler):354 """355 REST service based on Django-Piston Library.\n356 """357 def read(self, request, ticket='', group=''):358 """359 Given a group name, return the list of subscribers360 Arguments:361 request (HTTP request istance): HTTP request send from client.362 ticket (string) : base 64 ticket.363 group (string) : the group name364 Return:365 Successes - Json/xml/yaml format response366 Failure - 403 error367 """368 try:369 if request.GET.get('ticket'):370 client_address = request.META['REMOTE_ADDR']371 user, tkt64 = authenticate(ticket=request.GET['ticket'], cip=client_address)372 if user is not None:373 try:374 group = VPHShareSmartGroup.objects.get(name=request.GET.get('group'))375 except ObjectDoesNotExist, e:376 response = HttpResponse(status=404)377 response._is_string = True378 return response379 return {380 "users": [{"username": user.username, "fullname": "%s %s" % (user.first_name, user.last_name),381 "email": user.email} for user in group.user_set.all()],382 "groups": [{"groupname": g.name, "subscribers": len(g.user_set.all())} for g in383 VPHShareSmartGroup.objects.filter(parent=group)]384 }385 else:386 response = HttpResponse(status=403)387 response._is_string = True388 return response389 except Exception, e:390 from raven.contrib.django.raven_compat.models import client391 client.captureException()392 response = HttpResponse(status=500)393 response._is_string = True394 return response395class user_groups(BaseHandler):396 """397 REST service based on Django-Piston Library.\n398 """399 def read(self, request, ticket='', username=''):400 """401 Given a username, return the list of groups he is part of402 Arguments:403 request (HTTP request istance): HTTP request send from client.404 ticket (string) : base 64 ticket.405 username(string) : the username you want to know the groups406 Return:407 Successes - Json/xml/yaml format response408 Failure - 403 error409 """410 try:411 if request.GET.get('ticket'):412 client_address = request.META['REMOTE_ADDR']413 user, tkt64 = authenticate(ticket=request.GET['ticket'], cip=client_address)414 if user is not None:415 try:416 target_user = User.objects.get(username=request.GET.get('username'))417 except ObjectDoesNotExist, e:418 response = HttpResponse(status=404)419 response._is_string = True420 return response421 if request.GET.get('institution', None) is None:422 res = [{"groupname": g.name, "subscribers": len(g.user_set.all())} for g in423 target_user.groups.all()]424 else:425 res = [{"groupname": g.institution.name, "subscribers": len(g.institution.user_set.all())} for g in426 InstitutionPortal.objects.all() if target_user in g.institution.user_set.all()]427 return res428 else:429 response = HttpResponse(status=403)430 response._is_string = True431 return response432 except Exception, e:433 from raven.contrib.django.raven_compat.models import client434 client.captureException()435 response = HttpResponse(status=500)436 response._is_string = True437 return response438class promote_user(BaseHandler):439 """440 REST service based on Django-Piston Library.\n441 """442 def read(self, request, ticket='', group='', username=''):443 """444 Promote a user as manager of a group445 Arguments:446 request (HTTP request istance): HTTP request send from client.447 ticket (string) : base 64 ticket.448 group (string) : the group name449 username (string) : the username450 Return:451 Successes - Json/xml/yaml format response452 Failure - 403 error453 """454 try:455 if request.GET.get('ticket'):456 client_address = request.META['REMOTE_ADDR']457 user, tkt64 = authenticate(ticket=request.GET['ticket'], cip=client_address)458 if user is not None:459 group = VPHShareSmartGroup.objects.get(name=request.GET.get('group'))460 user_to_promote = User.objects.get(username=request.GET.get('username'))461 if not group.is_manager(user):462 response = HttpResponse(status=403)463 response._is_string = True464 return response465 # add user to the managers466 group.managers.add(user_to_promote)467 # add user to the group and all sub groups468 while group is not None:469 group.user_set.add(user_to_promote)470 try:471 group = VPHShareSmartGroup.objects.get(parent=group)472 except ObjectDoesNotExist, e:473 group = None474 response = HttpResponse(status=200)475 response._is_string = True476 response.write("OK")477 return response478 else:479 response = HttpResponse(status=403)480 response._is_string = True481 return response482 except Exception, e:483 from raven.contrib.django.raven_compat.models import client484 client.captureException()485 response = HttpResponse(status=500)486 response._is_string = True487 return response488class downgrade_user(BaseHandler):489 """490 REST service based on Django-Piston Library.\n491 """492 def read(self, request, ticket='', group='', username=''):493 """494 Promote a user as manager of a group495 Arguments:496 request (HTTP request istance): HTTP request send from client.497 ticket (string) : base 64 ticket.498 group (string) : the group name499 username (string) : the username500 Return:501 Successes - Json/xml/yaml format response502 Failure - 403 error503 """504 try:505 if request.GET.get('ticket'):506 client_address = request.META['REMOTE_ADDR']507 user, tkt64 = authenticate(ticket=request.GET['ticket'], cip=client_address)508 if user is not None:509 group = VPHShareSmartGroup.objects.get(name=request.GET.get('group'))510 user_to_downgrade = User.objects.get(username=request.GET.get('username'))511 if not group.is_manager(user):512 response = HttpResponse(status=403)513 response._is_string = True514 return response515 # remove user from the group managers and all sub groups516 while group is not None:517 # group.user_set.remove(user_to_downgrade)518 group.managers.remove(user_to_downgrade)519 try:520 group = VPHShareSmartGroup.objects.get(parent=group)521 except ObjectDoesNotExist, e:522 group = None523 response = HttpResponse(status=200)524 response._is_string = True525 response.write("OK")526 return response527 else:528 response = HttpResponse(status=403)529 response._is_string = True530 return response531 except Exception, e:532 from raven.contrib.django.raven_compat.models import client533 client.captureException()534 response = HttpResponse(status=500)535 response._is_string = True...
__init__.py
Source:__init__.py
1from ffindex.content import FFIndexContent2import mmap3try:4 isinstance("", basestring)5 def _is_string(s):6 return isinstance(s, basestring)7except NameError:8 def _is_string(s):9 return isinstance(s, str)10def _to_file(fn, mode="rb"):11 if _is_string(fn):12 return open(fn, mode)13 else:14 return fn15def read(ffindex_data, ffindex_db=None, encoding=None):16 """Generator to parse FFindex entries"""17 if ffindex_db is None:18 if _is_string(ffindex_data):19 ffindex_db = ffindex_data + ".index"20 else:21 raise Exception("When ffindex_data is passed as a file-like object, ffindex_db is required")22 f_db = _to_file(ffindex_db, "r")23 f_data = _to_file(ffindex_data, "r+b")24 m_data = mmap.mmap(f_data.fileno(), 0)25 for l_db in f_db:26 filename, start, length = l_db.strip().split("\t")27 yield FFIndexContent(m_data, int(start), int(length) - 1, filename, encoding)28 m_data.close()29 if _is_string(ffindex_db):30 f_db.close()31 if _is_string(ffindex_data):...
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!