How to use server_error method in Kiwi

Best Python code snippet using Kiwi_python

views.py

Source:views.py Github

copy

Full Screen

...20import simplejson as json21logger = logging.getLogger(__name__)22def get_user(request):23 return get_default_user()24def server_error(msg):25 response_data = dict()26 response_data['success'] = False27 response_data['result'] = msg28 return HttpResponse(json.dumps(response_data), mimetype="application/json") 29def server_data(data):30 response_data = dict()31 response_data['success'] = True32 response_data['result'] = data33 return HttpResponse(json.dumps(response_data), mimetype="application/json") 34'''35Code to handle businesses36'''37def get_business(request,oid):38 try:39 user = authenticate_api_request(request)40 authorize_user(user, request, "get")41 bus = Business.objects.get(id=oid)42 except ReadJSONError as e:43 return server_error(e.value)44 except (AuthenticationFailed, AuthorizationError) as e:45 return server_error(e.value)46 except: 47 return server_error('Business with id '+str(oid)+'not found')48 bus_data = get_single_bus_data_ios(bus,user)49 return server_data(bus_data)50def rate_business(request,oid):51 try:52 user = authenticate_api_request(request)53 authorize_user(user, request, "rate")54 rating = get_json_get_or_error('rating', request)55 bus = Business.objects.get(id=oid)56 except ReadJSONError as e:57 return server_error(e.value)58 except (AuthenticationFailed, AuthorizationError) as e:59 return server_error(e.value)60 except: 61 return server_error('Business with id '+str(oid)+'not found') 62 63 if Rating.objects.filter(business=bus,user=user).count() > 0:64 Rating.objects.filter(business=bus,user=user).delete()65 Rating.objects.create(business=bus, rating=rating,user=user) 66 bus.dist = distance.distance(user.current_location,(bus.lat,bus.lon)).miles67 bus_data = get_single_bus_data_ios(bus,user)68 return server_data(bus_data)69 70def add_business(request):71 try:72 user = authenticate_api_request(request)73 authorize_user(user, request, "add")74 bus = Business()75 name=get_json_post_or_error('businessName', request)76 addr=get_json_post_or_error('streetAddr', request)77 city = get_json_post_or_error('businessCity', request)78 state = get_json_post_or_error('businessState', request)79 phone = get_json_post_or_error('businessPhone', request)80 81 #already exists82 if Business.objects.filter(name=name,address=addr,city=city,state=state).count() == 0:83 bus = Business(name=name,address=addr,city=city,state=state)84 bus.save()85 elif Business.objects.filter(name=name,address=addr,city=city,state=state).count() > 1: #too many86 Business.objects.filter(name=name,address=addr,city=city,state=state).delete()87 Business.objects.create(name=name,address=addr,city=city,state=state,phone=phone)88 else:89 bus = Business.objects.get(name=name,address=addr,city=city,state=state) 90 except ReadJSONError as e:91 return server_error(e.value)92 except (AuthenticationFailed, AuthorizationError) as e:93 return server_error(e.value) 94 bus.dist = distance.distance(user.current_location,(bus.lat,bus.lon)).miles95 bus_data = get_single_bus_data_ios(bus,user)96 return server_data(bus_data)97def edit_business(request,oid):98 try:99 user = authenticate_api_request(request)100 authorize_user(user, request, "edit")101 bus = Business.objects.get(id = oid)102 except ReadJSONError as e:103 return server_error(e.value)104 except (AuthenticationFailed, AuthorizationError) as e:105 return server_error(e.value) 106 except:107 return server_error("Getting business with id "+str(oid)+" failed")108 109 print(request.POST)110 if 'businessName' in request.POST:111 print('mod that stuff!')112 bus.name = request.POST['businessName']113 114 if 'streetAddr' in request.POST:115 bus.addr = request.POST['streetAddr']116 117 if 'businessCity' in request.POST:118 bus.city = request.POST['businessCity']119 if 'businessPhone' in request.POST:120 return server_error("Phone not implemented")121 122 if 'businessState' in request.POST:123 bus.state = request.POST['businessState']124 125 print(bus.name)126 bus.save()127 print(bus.name)128 bus.dist = distance.distance(user.current_location,(bus.lat,bus.lon)).miles129 bus_data = get_single_bus_data_ios(bus,user)130 return server_data(bus_data)131def remove_business(request,oid):132 try:133 user = authenticate_api_request(request)134 authorize_user(user, request, "remove")135 bus = Business.objects.get(id=oid)136 name = bus.name137 Business.objects.filter(id = oid).delete()138 except ReadJSONError as e:139 return server_error(e.value)140 except (AuthenticationFailed, AuthorizationError) as e:141 return server_error(e.value)142 except:143 return server_error("Deleting business with id "+str(oid)+" failed")144 return server_data("Deletion of business "+str(name)+ " was a success")145def query_businesses(request,oid):146 try:147 user = authenticate_api_request(request)148 authorize_user(user, request, "query")149 q = Query.objects.get(id=oid)150 except (AuthenticationFailed, AuthorizationError) as e:151 return server_error(e.value)152 except ReadJSONError as e:153 return server_error(e.value)154 except:155 return server_error("Couldn't get query with ID " + str(oid))156 data = perform_query_from_obj(user,user.current_location,q)157 return server_data(data) #server_data(top_businesses)158 159def get_businesses(request):160 try:161 user = authenticate_api_request(request)162 authorize_user(user, request, "get")163 except:164 return server_error('Failure to authenticate')165 weights = dict()166 #Weights for sorting. 167 #score weight168 if 'sw' in request.GET:169 weights['sw'] = request.GET['sw']170 else:171 weights['sw'] = 1172 173 #distance weight174 if 'dw' in request.GET:175 weights['sdw'] = request.GET['dw']176 else:177 weights['dw'] = 1178 179 #price weight180 if 'pw' in request.GET:181 weights['pw'] = request.GET['pw']182 else:183 weights['pw'] = 1184 185 #value weight186 if 'vw' in request.GET:187 weights['vw'] = request.GET['vw']188 else:189 weights['vw'] = 1190 #Tags to sort by191 if 'tags' in request.GET: 192 tags = request.get['tags']193 else:194 tags = None195 #Tags to sort by196 if 'text' in request.GET: 197 searchText = request.get['text']198 else:199 searchText = None200 if 'lat' in request.GET and 'lng' in request.GET:201 lat = request.GET['lat']202 lng = request.GET['lng']203 else:204 g = geocoders.Google()205 _, (lat, lng) = g.geocode("Princeton, NJ") 206 207 208 businesses = perform_query_from_param(user, (lat, lng),weights,tags,searchText)209 print('before serial')210 top_businesses = get_bus_data_ios(businesses ,user)211 print('after serial')212 return server_data(top_businesses)213'''214Code to handle business categories215'''216def get_business_categories(request,oid):217 try:218 user = authenticate_api_request(request)219 authorize_user(user, request, "get")220 bus = Business.objects.get(id=oid)221 except ReadJSONError as e:222 return server_error(e.value)223 except (AuthenticationFailed, AuthorizationError) as e:224 return server_error(e.value)225 except: 226 return server_error('Business with id '+str(oid)+'not found')227 228 categories = BusinessTag.objects.filter(business=bus)229 230 data = get_categories_data(categories,user)231 return server_data(data)232def get_business_category(request,oid):233 try:234 user = authenticate_api_request(request)235 authorize_user(user, request, "get")236 category = BusinessTag.objects.get(id=oid)237 except ReadJSONError as e:238 return server_error(e.value)239 except (AuthenticationFailed, AuthorizationError) as e:240 return server_error(e.value)241 except: 242 return server_error('Category with id '+str(oid)+'not found')243 244 data = get_category_data(category,user)245 return server_data(data)246def rate_business_category(request,oid):247 try:248 user = authenticate_api_request(request)249 authorize_user(user, request, "rate")250 rating = get_json_get_or_error('rating', request)251 category = BusinessTag.objects.get(id=oid)252 except ReadJSONError as e:253 return server_error(e.value)254 except (AuthenticationFailed, AuthorizationError) as e:255 return server_error(e.value)256 except: 257 return server_error('Category with id '+str(oid)+'not found')258 259 TagRating.objects.create(user=user,tag=category,rating=rating)260 261 data = get_category_data(category,user)262 return server_data(data)263def add_business_category(request,oid):264 try:265 user = authenticate_api_request(request)266 authorize_user(user, request, "add")267 tagid = get_json_get_or_error('tagID', request)268 bus = Business.objects.get(id=oid)269 tag = Tag.objects.get(id=tagid)270 except ReadJSONError as e:271 return server_error(e.value)272 except (AuthenticationFailed, AuthorizationError) as e:273 return server_error(e.value)274 except: 275 return server_error('Retrieving business and category failed (IDs: '+str(oid)+ ' and ' + str(tagid))276 277 if BusinessTag.objects.filter(business=bus,tag=tag).count() > 0:278 category = BusinessTag.objects.get(business=bus, tag=tag)279 else:280 category = BusinessTag.objects.create(business=bus,tag=tag,creator=user)281 data = get_category_data(category,user)282 return server_data(data)283def remove_business_category(request,oid):284 try:285 user = authenticate_api_request(request)286 authorize_user(user, request, "remove")287 BusinessTag.objects.filter(id=oid).delete()288 except ReadJSONError as e:289 return server_error(e.value)290 except (AuthenticationFailed, AuthorizationError) as e:291 return server_error(e.value)292 except:293 return server_error('Category with id '+str(oid)+'not found')294 return server_data("Deletion successful")295def get_tags(request):296 try:297 user = authenticate_api_request(request)298 except (AuthenticationFailed, AuthorizationError) as e:299 return server_error(e.value)300 data = get_tags_data(Tag.objects.all(),user)301 return server_data(data)302'''303Code to handle comments304'''305def get_comments(request):306 try:307 user = authenticate_api_request(request)308 authorize_user(user, request, "get")309 except ReadJSONError as e:310 return server_error(e.value)311 except (AuthenticationFailed, AuthorizationError) as e:312 return server_error(e.value)313 return server_error('unimplemented')314def get_comment(request,oid):315 try:316 user = authenticate_api_request(request)317 authorize_user(user, request, "get")318 comment = Discussion.objects.get(id=oid)319 except ReadJSONError as e:320 return server_error(e.value)321 except (AuthenticationFailed, AuthorizationError) as e:322 return server_error(e.value)323 324 data = get_comment_data(comment,user)325 return server_data(data)326def rate_comment(request,oid):327 try:328 user = authenticate_api_request(request)329 authorize_user(user, request, "rate")330 rating = get_json_get_or_error('rating', request)331 comment = Discussion.objects.get(id=oid)332 except ReadJSONError as e:333 return server_error(e.value)334 except (AuthenticationFailed, AuthorizationError) as e:335 return server_error(e.value)336 except: 337 return server_error('Comment with id '+str(oid)+'not found')338 CommentRating.objects.create(user=user,rating=rating,comment=comment)339 data = get_comment_data(comment,user)340 return server_data(data)341def add_comment(request):342 try: 343 user = authenticate_api_request(request)344 oid = get_json_get_or_error('commentBaseID', request) 345 commentType = get_json_get_or_error('type', request) 346 content = get_json_post_or_error('commentContent', request) 347 except ReadJSONError as e:348 return server_error(e.value)349 except (AuthenticationFailed, AuthorizationError) as e:350 return server_error(e.value)351 try:352 if 'replyTo' in request.GET:353 replyToID = request.GET['replyTo']354 replyComment = Discussion.objects.get(id=replyToID)355 else:356 replyComment = None357 except:358 return server_error("No comment found with id "+str(replyToID))359 360 if commentType == 'business':361 try:362 bus = Business.objects.get(id=oid)363 except:364 return server_error("Business with ID "+str(oid)+ " does not exist")365 comment = BusinessDiscussion.objects.create(user=user,reply_to=replyComment,content=content,business=bus)366 elif commentType == 'category':367 try:368 btag = BusinessTag.objects.get(id=oid)369 except:370 return server_error("Category with ID "+str(oid)+ " does not exist")371 comment = CategoryDiscussion.objects.create(user=user,reply_to=replyComment,content=content,businesstag=btag)372 elif commentType == 'photo':373 try:374 photo = Photo.objects.get(id=oid)375 except:376 return server_error("Photo with ID "+str(oid)+ " does not exist")377 comment = PhotoDiscussion.objects.create(user=user,reply_to=replyComment,content=content,photo=photo) 378 else:379 return server_error("Invalid commentType "+str(commentType))380 data = get_comment_data(comment,user)381 return server_data(data)382def edit_comment(request,oid):383 try:384 user = authenticate_api_request(request)385 authorize_user(user, request, "edit")386 content = get_json_post_or_error('commentContent', request) 387 except ReadJSONError as e:388 return server_error(e.value)389 except (AuthenticationFailed, AuthorizationError) as e:390 return server_error(e.value)391 392 comment = CategoryDiscussion.objects.create(id=oid,content=content)393 data = get_comment_data(comment,user)394 return server_data(data)395 396def remove_comment(request,oid):397 try:398 user = authenticate_api_request(request)399 authorize_user(user, request, "user")400 except ReadJSONError as e:401 return server_error(e.value)402 except (AuthenticationFailed, AuthorizationError) as e:403 return server_error(e.value)404 405 try:406 Discussion.objects.filter(id=oid).delete()407 except: 408 return server_error('Comment with id '+str(oid)+' not found. Deletion failed')409 410 return server_data("Deletion successful")411'''412Code to handle photos413'''414def get_photos(request,oid):415 try:416 user = authenticate_api_request(request)417 authorize_user(user, request, "get")418 phototype = get_json_get_or_error('type', request) 419 order_by = get_json_get_or_error('order_by', request) 420 except ReadJSONError as e:421 return server_error(e.value)422 except (AuthenticationFailed, AuthorizationError) as e:423 return server_error(e.value)424 425 if phototype=="business":426 try:427 bus = Business.objects.get(id=oid)428 except:429 return server_error("No business with ID"+str(oid)+" found")430 allphotos= Photo.objects.filter(business=bus) 431 else:432 allphotos= Photo.objects.filter(user=user,business=None)433 434 data = get_photos_data(allphotos,user,order_by=order_by)435 return server_data(data)436def get_photo(request,oid):437 try:438 user = authenticate_api_request(request)439 authorize_user(user, request, "get")440 authorize_user(user,request,"get")441 photo = Photo.objects.get(id=oid)442 except ReadJSONError as e:443 return server_error(e.value)444 except (AuthenticationFailed, AuthorizationError) as e:445 return server_error(e.value) 446 except Photo.DoesNotExist: 447 return server_error('Photo with id '+str(oid)+' not found. Deletion failed')448 449 data = get_photo_data(photo,user)450 return server_data(data)451def rate_photo(request,oid):452 try:453 user = authenticate_api_request(request)454 authorize_user(user, request, "rate")455 rating = get_json_get_or_error('rating', request)456 except ReadJSONError as e:457 return server_error(e.value)458 except (AuthenticationFailed, AuthorizationError) as e:459 return server_error(e.value)460 photo = Photo.objects.get(id=oid) 461 PhotoRating.objects.create(rating = rating,user=user,photo=photo)462 data = get_photo_data(photo,user)463 return server_data(data)464 465 466def add_photo(request):467 try:468 user = authenticate_api_request(request)469 authorize_user(user, request, "add")470 caption = get_json_post_or_error('photoCaption', request)471 title = get_json_post_or_error('photoTitle', request)472 except ReadJSONError as e:473 return server_error(e.value)474 except (AuthenticationFailed, AuthorizationError) as e:475 return server_error(e.value)476 477 if 'businessID' not in request.GET:478 b = None479 defaultUserPhoto = True480 else:481 defaultUserPhoto = False482 bid = request.GET['businessID']483 try:484 b = Business.objects.get(id=bid)485 except:486 return server_error("Could not retrieve business with ID "+str(bid)+ " for add_photo")487 488 if 'image' in request.FILES:489 img = request.FILES['image']490 photo = add_photo_by_upload(img,b,request.user,defaultUserPhoto,caption,title)491 elif 'url' in request.POST:492 url = request.POST['url']493 if url != '':494 photo = add_photo_by_url(url, b, request.user, defaultUserPhoto,caption,title)495 else:496 return server_error("No photo specified in request.FILES or URL in request.POST")497 data = get_photo_data(photo,user)498 return server_data(data)499def remove_photo(request,oid):500 try:501 user = authenticate_api_request(request)502 authorize_user(user, request, "remove")503 Photo.objects.filter(id=oid).delete()504 except ReadJSONError as e:505 return server_error(e.value)506 except (AuthenticationFailed, AuthorizationError) as e:507 return server_error(e.value) 508 except Photo.DoesNotExist: 509 return server_error('Photo with id '+str(oid)+' not found. Deletion failed')510 return server_data("Deletion of photo id= " +str(oid)+ " successful")511'''512Code to handle queries513''' 514def get_queries(request):515 try:516 user = authenticate_api_request(request)517 authorize_user(user, request, "get")518 querytype = get_json_get_or_error('type', request)519 except ReadJSONError as e:520 return server_error(e.value)521 except (AuthenticationFailed, AuthorizationError) as e:522 return server_error(e.value)523 524 if querytype=='yours':525 queries = Query.objects.filter(creator=user)526 elif querytype=='popular': 527 queries = Query.objects.filter(is_default=True)528 else:529 queries = Query.objects.filter(creator=user)530 data = get_queries_data(queries,user)531 return server_data(data)532 533 534def get_query(request,oid):535 try:536 user = authenticate_api_request(request)537 authorize_user(user, request, "get")538 query = Query.objects.get(id=oid)539 except ReadJSONError as e:540 return server_error(e.value)541 except (AuthenticationFailed, AuthorizationError) as e:542 return server_error(e.value)543 except:544 return server_error("Query with ID "+str(oid)+" not found")545 data = get_query_data(query,user)546 return server_data(data)547 548 549def add_query(request):550 try:551 user = authenticate_api_request(request)552 authorize_user(user, request, "add")553 query = Query()554 query.name = get_json_post_or_error('queryName',request)555 query.creator = user#get_json_or_error('queryName',request)556 query.proximity = get_json_post_or_error('proximityWeight',request)557 query.price = get_json_post_or_error('priceWeight',request)558 query.value = get_json_post_or_error('valueWeight',request)559 query.score = get_json_post_or_error('scoreWeight',request)560 query.userHasVisited = get_json_post_or_error('userHasVisited',request)561 query.text = get_json_post_or_error('searchText',request)562 query.networked = get_json_post_or_error('networked',request)563 query.deal = get_json_post_or_error('deal',request)564 query.is_default = False# get_json_or_error('deal',request)565 query.save()566 if 'queryTags' not in request.POST:567 return server_error("Categories did not provide a list")568 categoryList = request.POST.getlist('queryCategories')569 for c in categoryList:570 if Tag.objects.filter(id=c).count() == 0:571 return server_error("Invalid Category provided")572 cat = Tag.objects.get(id=c)573 QueryTag.objects.create(query=query,tag=cat)574 except ReadJSONError as e:575 return server_error(e.value)576 except (AuthenticationFailed, AuthorizationError) as e:577 return server_error(e.value)578 except:579 return server_error("Could not save the object")580 data = get_query_data(query,user)581 return server_data(data)582def remove_query(request,oid):583 try:584 user = authenticate_api_request(request)585 authorize_user(user, request, "remove")586 Query.objects.filter(id=oid).delete()587 except ReadJSONError as e:588 return server_error(e.value)589 except (AuthenticationFailed, AuthorizationError) as e:590 return server_error(e.value)591 except:592 return server_error("Query with ID "+str(oid)+" not found. Deletion was not successful")593 return server_data("Deletion successful")594 595def edit_query(requst):596 return server_error("unimplemented")597 598 ...

Full Screen

Full Screen

users.py

Source:users.py Github

copy

Full Screen

1from flask_restplus import Namespace, Resource, fields, reqparse2from models import db, User, Company, Stock, NetWorthLeaderboard3import models4from validator import validate, user_rank, username_validator, users_validator, net_worth_rank_validator, current_balance_rank_validator5from util import rank_types6usersApi = Namespace('users', description="User operations")7# ----------------------------------- Response Model Registration ------------------------------------------------------8user_model = usersApi.model('user', {9 'server_error': fields.String(default = "no"),10 'id': fields.Integer,11 'username': fields.String,12 'email': fields.String,13 'country': fields.String,14 'current_balance': fields.Integer,15 'user_type': fields.Integer,16 'current_net_worth': fields.Integer17})18rank_model = usersApi.model('rank', {19 'server_error': fields.String(default = "no"),20 'rank': fields.Integer21})22# --------------------------------------------------- all users ---------------------------------------------23users_parser = reqparse.RequestParser()24users_parser.add_argument('amount', type=int)25users_parser.add_argument('rank_area', type=str) # 'top', 'bottom', or 'around' given user26users_parser.add_argument('username', type=str)27@usersApi.route('/')28@usersApi.response(522, 'Server broke :(')29@usersApi.response(222, 'success')30class users(Resource):31 def get(self):32 try:33 return {'server_error': 'TODO: setup respone which returns users around, top, bottom, etc'}, 32234 args = users_parser.parse_args()35 # ^^^^^^^^^^^ ERROR CHECK ^^^^^^^^^^^^^^^^^^^^^^^36 if (not validate(args, users_validator)):37 return {'server_error': 'one or more parameters not valid'}, 42238 if (not validate(args['username'], username_validator)):39 error_str = username+' does not exist.'40 return {'server_error': error_str}, 42241 # vvvvvvvvvvv ERROR CHECK END vvvvvvvvvvvvvvvvv42 43 return {'user': 'get users ordered by rank'}, 22244 except Exception as e:45 return {'server_error': str(e)}, 52246# --------------------------------------------------- single user ---------------------------------------------47@usersApi.route('/<string:username>')48class user(Resource):49 @usersApi.marshal_with(user_model)50 def get(self, username):51 try:52 # ^^^^^^^^^^^ ERROR CHECK ^^^^^^^^^^^^^^^^^^^^^^^53 if (not validate(username, username_validator)):54 error_str = username+' does not exist.'55 return {'server_error': error_str}, 24256 # vvvvvvvvvvv ERROR CHECK END vvvvvvvvvvvvvvvvv57 user1 = User.query.filter_by(username=username).first()58 return user1, 22259 except Exception as e:60 return {'server_error': str(e)}, 52261# --------------------------------------------------- General Rank ---------------------------------------------62@usersApi.route('/rank/')63class rank(Resource):64 def post(self):65 try:66 return {'message': 'TODO: here is where you add the user after making him'}, 32267 except Exception as e:68 return {'server_error': str(e)}, 52269 def put(self):70 try:71 update_rank_query = "UPDATE net_worth_leaderboard SET rank = new_t.rank FROM net_worth_leaderboard AS nwlb INNER JOIN (SELECT username, id, RANK() OVER(ORDER BY current_net_worth DESC) AS rank FROM users) AS new_t ON nwlb.user_id = new_t.id WHERE net_worth_leaderboard.user_id = new_t.id" 72 result = db.engine.execute(update_rank_query)73 return {'result': 'success!'}, 22274 except Exception as e:75 return {'server_error': str(e)}, 52276# --------------------------------------------------- given rank gets user ---------------------------------------------77rank_parser1 = reqparse.RequestParser()78rank_parser1.add_argument('rank_type')79@usersApi.route('/rank/<int:number>')80@usersApi.param('rank_type', 'specify a rank type')81class user_from_rank(Resource):82 @usersApi.marshal_with(user_model)83 def get(self, number):84 try:85 args = rank_parser1.parse_args()86 rank_type = args['rank_type']87 if rank_type == 'net_worth':88 # ^^^^^^^^^^^ ERROR CHECK ^^^^^^^^^^^^^^^^^^^^^89 if (not validate(number, net_worth_rank_validator)):90 return {'server_error': 'invalid rank number given'}, 42291 # vvvvvvvvvvv ERROR CHECK END vvvvvvvvvvvvvvvvv92 rank_user = NetWorthLeaderboard.query.filter_by(rank=number).first()93 user_username = rank_user.username94 user1 = User.query.filter_by(username=user_username).first()95 return user1, 22296 elif rank_type == 'current_balance':97 # ^^^^^^^^^^^ ERROR CHECK ^^^^^^^^^^^^^^^^^^^^^98 if (not validate(number, current_balance_rank_validator)):99 {'server_error': 'invalid rank number given'}, 422100 # vvvvvvvvvvv ERROR CHECK END vvvvvvvvvvvvvvvvv101 return {'server_error': 'TODO: return current balance rank of given user'}, 322102 return {'server_error': 'invalid rank type'}, 422103 except Exception as e:104 {'server_error': str(e)}, 522105# --------------------------------------------------- given username gets rank ---------------------------------------------106# get rank of a given user107rank_parser2 = reqparse.RequestParser()108rank_parser2.add_argument('rank_type')109# ROUTE110@usersApi.route('/<string:username>/rank/') 111# PARAMETERS112@usersApi.param('username', 'specify a user')113@usersApi.param('rank_type', 'specify a rank_type')114class rank_from_user(Resource):115 @usersApi.marshal_with(rank_model)116 def get(self, username):117 try:118 args = rank_parser2.parse_args()119 # ^^^^^^^^^^^ ERROR CHECK ^^^^^^^^^^^^^^^^^^^^^^^120 if (not validate(args, user_rank)):121 return {'server_error': 'one or more parameters not valid'}, 422122 if (not validate(username, username_validator)):123 error_str = username+' does not exist.'124 return {'server_error': error_str}, 422125 # vvvvvvvvvvv ERROR CHECK END vvvvvvvvvvvvvvvvv126 rank_type = args['rank_type']127 if rank_type == 'net_worth':128 rankUser = NetWorthLeaderboard.query.filter_by(username=username).first()129 rank = rankUser.rank130 return {'rank': rank}, 222131 elif rank_type == 'current_balance':132 # TODO: return global rank of the user133 return {'server_error': 'TODO: get rank by current balance'}, 322134 except Exception as e:135 return {'server_error': str(e)}, 522136# --------------------------------------------------- Registration ---------------------------------------------137registeringParser = reqparse.RequestParser()138registeringParser.add_argument('username', type=str)139registeringParser.add_argument('email', type=str)140registeringParser.add_argument('country', type=str)141registeringParser.add_argument('user_type', type=int)142register_fields = usersApi.model('Registration', {143 'username': fields.String,144 'email': fields.String,145 'country': fields.String, 146 'user_type': fields.Integer147 })148@usersApi.route('/register/')149@usersApi.response(522, 'Server broke :(')150@usersApi.response(222, 'success!')151class register(Resource):152 153 def get(self):154 try:155 return 'this is the registering page', 222156 except Exception as e:157 return {'message': str(e)}, 522158 @usersApi.expect(register_fields)159 def post(self):160 try:161 args = registeringParser.parse_args()162 db.session.add(User(username=args['username'], 163 email=args['email'],164 country=args['country'], 165 current_balance=100, 166 user_type=args['user_type'], 167 current_net_worth=100))168 db.session.commit()169 user1 = User.query.filter_by(username=args['username']).first()170 db.session.add(NetWorthLeaderboard(-1, user1.id, args['username']))171 db.session.commit()172 return {'message': 'success'}, 222173 except Exception as e:174 {'message': str(e)}, 522...

Full Screen

Full Screen

Automation Testing Tutorials

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.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run Kiwi automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful