How to use make_json_response method in localstack

Best Python code snippet using localstack_python

v1.py

Source:v1.py Github

copy

Full Screen

...67 return password_validator(password)68 if email_validator(email):69 return email_validator(email)70 if User.query.filter_by(email=email).first() is not None:71 return make_json_response(409, email, " Already Exists") # existing user72 user = User(email=email, username=username, password=password)73 save_user(user)74 return make_json_response(201, user.username, " Created Successfully")75@ns.route("/user")76class AppUser(Resource):77 @auth.login_required78 def get(self):79 """80 Get current user details81 """82 return marshal(g.user, user_model)83 @ns.expect(login_model, validate=True)84 @api.response(401, "Unknown User or Invalid Credentials")85 def post(self):86 """87 User Login88 Supply details user registered with.89 """90 args = master_parser.parse_args()91 email = args['email']92 password = args['password']93 user = User.query.filter_by(email=email).first()94 if user:95 # User Found Check Password96 if user.check_password(password):97 g.user = user98 token = g.user.generate_auth_token(configurations=configuration,99 expiration=3600)100 return jsonify({'token': token.decode('ascii'),101 'duration': 3600})102 else:103 return make_json_response(401, "Wrong Credentials ", " Provided")104 else:105 return make_json_response(401, "Wrong Credentials ",106 " Provided")107 @ns.expect(update_model, validate=True)108 @auth.login_required109 @api.response(200, "User Credentials Updated Successfully")110 def put(self):111 """112 edit Account credentials113 Only username and password can be changed.114 For Fields that the user does not intend to change, they should be left115 as 'None'116 """117 args = update_parser.parse_args()118 username = args['name']119 password = args['password']120 if username != '':121 invalid_name = name_validalidatior(username, "Users")122 if invalid_name:123 return invalid_name124 if len(username.strip()) == 0 and len(password.strip()) == 0:125 return {126 "message": "No Updates Were Made"127 }128 update_user(g.user, username=username, password=password)129 response = {130 "message": "User Updated successfully",131 "User": marshal(g.user, user_model)132 }133 return response134@ns.route("/shoppinglists")135class ShoppingLists(Resource):136 @api.response(404, "ShoppingList Does not Exist")137 @auth.login_required138 @ns.expect(paginate_query_parser, validate=True)139 def get(self):140 """141 gets all shopping lists of current user if a query is not provided.142 A specific shopping list will be returned if a query is provided.143 Note that an empty list will be returned in cases where there144 is no shopping list145 """146 args = paginate_query_parser.parse_args(request)147 search_query = args.get("q")148 page = args.get('page', 1)149 limit = args.get("limit", 10)150 if not isinstance(page, int):151 jsonify({"message": "Url not found"}), 404152 if search_query:153 """154 gets shopping_list(s) of current user specified by search_query155 """156 shopping_lists = ShoppingList.query. \157 filter(func.lower(ShoppingList.name).like("%" + func.lower(search_query) + "%")). \158 filter_by(owner_id=g.user.id).all()159 if len(shopping_lists) > 0:160 return marshal(shopping_lists, shopping_lists_with_items_model)161 else:162 return make_json_response(404, "Shopping Lists with '" + search_query,163 "' Does Not Exist")164 shopping_lists = ShoppingList.query.filter_by(owner_id=g.user.id). \165 paginate(page, limit, True).items166 if len(shopping_lists) == 0:167 return make_json_response(200, "You Currently",168 "Do Not Have Any Shopping List")169 return marshal(shopping_lists, shopping_lists_with_items_model)170 @api.response(201, "ShoppingList Added Successfully")171 @api.response(409, "ShoppingList Already Exist")172 @ns.expect(shopping_list_model, validate=True)173 @auth.login_required174 def post(self):175 """176 Add a ShoppingList.177 """178 args = shoppinglist_parser.parse_args()179 name = args['name']180 description = args['description']181 invalid_name = name_validalidatior(name, "Shopping List")182 if invalid_name:183 return invalid_name184 if add_shopping_list(g.user, name=name, description=description):185 shopping_lists = ShoppingList.query.filter_by(owner_id=g.user.id).all()186 return make_json_response(201, "Shopping list " + name,187 " Created Successfully", data=shopping_lists)188 else:189 return make_json_response(409, "Shopping list " + name,190 " Already Exists")191@ns.route("/shoppinglists/<id>")192class SingleShoppingList(Resource):193 @api.response(200, "ShoppingList Found")194 @api.response(404, "ShoppingList Does not Exist")195 @auth.login_required196 def get(self, id=None):197 """198 gets the shopping list with the supplied id199 """200 if validate_ints(id):201 shopping_list = ShoppingList.query.filter_by(id=id).first()202 if shopping_list is not None:203 if shopping_list.owner_id == g.user.id:204 return marshal(shopping_list, shopping_lists_with_items_model)205 else:206 return make_json_response(403, "You Are not Authorised to Access Shopping List '" + id,207 "'")208 else:209 return make_json_response(404, "Shopping List'" + id,210 "' Does Not Exist")211 else:212 return make_json_response(404, "Shopping list with ID " + id,213 " Does not exist. Expecting a digit id")214 @api.response(200, "ShoppingList Updated Successfully")215 @api.response(404, "ShoppingList Does not Exist")216 @ns.expect(update_shopping_list_model, validate=True)217 @auth.login_required218 def put(self, id):219 """220 Updates a shopping list221 Both the "new_name" and "description" fields can be added222 according to which the user wants to update223 """224 args = update_shoppinglist_parser.parse_args()225 new_name = args.get('new_name')226 description = args.get('description')227 if not validate_ints(id):228 return make_json_response(404, "Shopping list with ID " + id,229 " Does not exist. Expecting a digit id")230 # Get shopping list231 shopping_list = ShoppingList.query.filter_by(id=id).first()232 if shopping_list is not None:233 # We got the shopping list. Now Update it234 if new_name is not '' or description is not '':235 update_shopping_list(shopping_list, new_name, description)236 shopping_lists = ShoppingList.query.filter_by(owner_id=g.user.id).all()237 return make_json_response(200, "Shopping list " + shopping_list.name,238 " Updated Successfully", data=shopping_lists)239 else:240 return make_json_response(200, "Nothing was provided ", "to Updated")241 else:242 return make_json_response(404, "Shopping list With ID '" + id,243 "' Does not exist")244 @api.response(200, "ShoppingList Deleted Successfully")245 @api.response(404, "ShoppingList Does not Exist")246 @auth.login_required247 def delete(self, id=None):248 """249 Deletes a shopping list250 """251 if not validate_ints(id):252 return make_json_response(404, "Shopping list with ID " + id,253 " Does not exist. Expecting a digit id")254 # Get the shopping list specified and belonging to current user255 shopping_list = ShoppingList.query.filter_by(id=id) \256 .filter_by(owner_id=g.user.id).first()257 if shopping_list is not None:258 items = Item.query.filter_by(shoppinglist_id=shopping_list.id).all()259 delete_shoppinglist(shopping_list, items)260 shopping_lists = ShoppingList.query.filter_by(owner_id=g.user.id).all()261 return make_json_response(200, "Shopping list " + shopping_list.name,262 " Deleted Successfully", data=shopping_lists)263 else:264 return make_json_response(404, "Shopping list with ID " + id,265 " Does not exist")266@ns.route("/shoppinglists/share")267class ShareShoppingLists(Resource):268 @api.response(200, "Shopping list shared successfully")269 @api.response(404, "Shopping list or email to share with doesn't exist")270 @ns.expect(share_shoppinglist_model, validate=True)271 @auth.login_required272 def post(self):273 """274 Shares supplied shopping list with the email provided.275 """276 args = share_shoppinglist_parser.parse_args()277 shopping_list_id = args.get('id')278 email = args.get('email')279 invalid_id = numbers_validator(shopping_list_id)280 if invalid_id:281 return invalid_id282 # Find shopping list from db283 shopping_list = ShoppingList.query.filter_by(id=shopping_list_id). \284 filter_by(owner_id=g.user.id).first()285 if shopping_list:286 # shopping list exists just share it now287 share_with = User.query.filter_by(email=email).first()288 if share_with and email != g.user.email:289 # the person exists290 if add_shared_shopping_list(shopping_list, share_with):291 share(shopping_list, True, g.user.email)292 return make_json_response(200, "Shopping List " +293 '`'+shopping_list.name+'`',294 " Shared Successfully")295 else:296 return make_json_response(200, "Shopping List " +297 '`'+shopping_list.name+'`',298 " Not Shared. User Already has it.")299 else:300 # person don't exist or you are the person301 return make_json_response(404, "Email: " + email,302 " Does not exists or its your email")303 else:304 return make_json_response(404, "ShoppingList with ID " + shopping_list_id, "Does Not Exist")305@ns.route("/shoppinglist_items")306class Items(Resource):307 @api.response(201, "Item Added Successfully")308 @api.response(409, "Item Already Exist")309 @api.response(404, "ShoppingList Not Found")310 @ns.expect(item_model)311 @auth.login_required312 def post(self):313 """314 Add's a ShoppingList item315 "shopping_list_id" Is the id of the shopping_list to which the316 item will be added to.317 """318 args = item_parser.parse_args()319 name = args.get('name')320 price = args.get('price')321 quantity = args.get('quantity')322 shopping_list_id = args.get('shoppinglist_id')323 # get shoppinglist from db324 invalid = validate_values(name, price, quantity, shopping_list_id)325 if invalid:326 response = jsonify({'error': invalid})327 response.status_code = 400328 return response329 shopping_list = ShoppingList.query.filter_by(id=shopping_list_id) \330 .filter_by(owner_id=g.user.id).first()331 if shopping_list:332 # Eureka!!! we found the shopping list add the item now333 if add_item(shopping_list, name=name, price=price,334 quantity=quantity, owner_id=g.user.id):335 return make_json_response(201, "Item " + name, " Added Successfully")336 else:337 return make_json_response(409, "Item " + name, " Already exist")338 return make_json_response(404, "Shoppinglist with ID " + str(shopping_list_id),339 " Not Found")340 @api.response(200, "ShoppingList Item Updated Successfully")341 @api.response(404, "ShoppingList Item or Shopping List Does not Exist")342 @ns.expect(item_update_model)343 @auth.login_required344 def put(self):345 """346 Updates a shopping list Item347 For Fields that the user does not want to update they can be omitted348 """349 args = update_shoppinglist_item_parser.parse_args()350 item_id = args.get('id')351 new_name = args.get('new_name', "None")352 price = args.get('price')353 quantity = args.get('quantity')354 new_shopping_list_id = args.get('new_shopping_list_id')355 if new_name is '' and price is '' and quantity is '':356 return make_json_response(404, "Nothing Provided ",357 " For Updating")358 if not validate_ints(item_id):359 return make_json_response(404, "Shoppinglist Item ID " +360 "'" + str(item_id) + "'",361 " Is an Invalid Id")362 if new_name is not '' or price is not '' or quantity is not '':363 invalid_values = validate_values(new_name, price, quantity, new_shopping_list_id, update=True)364 print('Look also', invalid_values)365 if invalid_values:366 return invalid_values367 item = Item.query.filter_by(id=item_id).first()368 item2 = Item.query.filter_by(name=new_name).first()369 if item2 is not None:370 if item2.id != item.id:371 return make_json_response(409, "Item " + new_name, " Already exist")372 if item is not None and new_shopping_list_id is None:373 # Got The Item We supposed to Update374 item.update_item(name=new_name, price=price,375 quantity=quantity)376 items = ShoppingList.query.filter_by(id=item.shoppinglist_id).all()377 return make_json_response(200, "Item " + "'" + item.name + "'",378 " Successfully Updated", data=items)379 if item is None:380 return make_json_response(404, "Item with id " + "'" + str(item_id) + "'",381 "Does not Exist")382 # Check if user wants to update the items shopping list383 if new_shopping_list_id is not None and new_shopping_list_id != item.shoppinglist_id:384 # Look for the Shopping list to update to385 new_shopping_list = ShoppingList.query. \386 filter_by(id=new_shopping_list_id).filter_by(owner_id=g.user.id).first()387 if new_shopping_list is not None:388 # User has that Shopping List Now update the item389 item.update_item(name=new_name, price=price,390 quantity=quantity,391 shoppinglist=new_shopping_list)392 return make_json_response(200, "Item " + "'" + item.name + "'",393 " Successfully Updated")394 else:395 return make_json_response(404, "The new Shopping List with ID " +396 "'" +397 str(new_shopping_list_id) +398 "'",399 " Does not Exist")400 else:401 return make_json_response(200, "Item " + "'" + item.name + "'",402 " Belongs to Shopping list "403 + str(new_shopping_list_id) + " Already")404@ns.route("/shoppinglist_items/<id>")405class SingleItem(Resource):406 @api.response(200, "Item Found")407 @api.response(404, "Item Does Not Exist")408 @auth.login_required409 def get(self, id=None):410 """411 Returns a single Item with the supplied id412 """413 if validate_ints(id):414 item = Item.query.filter_by(id=id) \415 .filter_by(owner_id=g.user.id).first()416 if item is not None:417 return marshal(item, item_model)418 else:419 return make_json_response(404, "Item with ID " + id,420 " Does not exist")421 else:422 return make_json_response(404, "Item with ID " + id,423 " Does not exist. Expecting a digit id")424 @api.response(200, "ShoppingList Item Deleted Successfully")425 @api.response(404, "ShoppingList Item Does not Exist")426 @auth.login_required427 def delete(self, id=None):428 """429 Deletes a shopping list Item430 """431 if not validate_ints(id):432 return make_json_response(404, "Shopping list with ID " + id,433 " Does not exist. Expecting a digit id")434 # Check if That Item exist435 item = Item.query.filter_by(id=id).filter_by(owner_id=g.user.id).first()436 if item:437 delete_item(item)438 return make_json_response(200, "Item " + item.name,439 " Deleted Successfully")440 else:441 return make_json_response(404, "Item With id " + str(id),442 " Does Not Exist.")443def make_json_response(status_code, name_obj, message, data=None):444 if data is not None:445 response = jsonify({'message': name_obj + " " + message, 'data': marshal(data,446 shopping_lists_with_items_model)})447 else:448 response = jsonify({'message': name_obj + " " + message})449 response.status_code = status_code450 return response451@ns.route("/token")452class GetAuthToken(Resource):453 decorators = [auth.login_required]454 def get(self):455 """456 Generate authentication token for logged in user457 Use the generated Authentication Token for other...

Full Screen

Full Screen

app.py

Source:app.py Github

copy

Full Screen

...34 return render_template('custom_500.html')35@app.route('/', methods=['GET'])36def index():37 return render_template('home.html')38def make_json_response(data):39 response = make_response(json.dumps(data))40 response.headers['Content-Type'] = 'application/json'41 return response42@app.route('/call/', methods=['GET', 'POST'])43def call(number_call=None):44 number = number_call or request.args.get('number_call')45 if not number:46 response = make_json_response({'error':'No number'})47 return response48 call_params = {49 'to':number,50 'from':PLIVO_NUMBER,51 'ring_url':BASE_URL + 'response/call/ring/',52 'ring_method':'GET',53 'answer_url':BASE_URL + 'response/conf/music/',54 'answer_method':'GET', 55 }56 p = get_plivo_connection()57 status, response = p.make_call(call_params)58 if status == 201:59 response = make_json_response({'success': True})60 return response61 response = make_json_response({'error':'Call cannot be established, please verify your number'})62 return response63@app.route('/call/play/', methods=['GET', 'POST'])64def call_play():65 call_uuid = request.args.get('call_uuid');66 tts_msg = request.args.get('tts_msg');67 p = get_plivo_connection()68 p.speak({'call_uuid':call_uuid, 'text':tts_msg})69 return ''70@app.route('/response/call/ring/', methods=['GET', 'POST'])71def call_ring():72 call_uuid = request.args.get('CallUUID')73 number = request.args.get('To')74 rd = get_redis_connection()75 rd.set(number, call_uuid)76 number_call_uuid = {number:call_uuid}77 pr = get_pusher_connection()78 pr['pycon.plivo'].trigger('in_call', json.dumps(number_call_uuid))79@app.route('/conference/', methods=['GET', 'POST'])80def conference(number=None):81 number = number or request.args.get('number')82 if not number:83 response = make_json_response({'error':'No number'})84 return response85 members = get_conference_members(CONFERENCE_NAME)86 for member in members:87 if number == member['to']:88 response = make_json_response({'error':'Already in conference'})89 return response90 call_params = {91 'to':number,92 'from':PLIVO_NUMBER,93 'answer_url':BASE_URL + 'response/conf/',94 'answer_method':'GET', 95 }96 p = get_plivo_connection()97 status, response = p.make_call(call_params)98 if status == 201:99 response = make_json_response({'success': True})100 return response101 response = make_json_response({'error':'Call cannot be established, please verify your number'})102 return response103@app.route('/response/conf/', methods=['GET', 'POST'])104def conference_response():105 r = plivo.Response()106 r.addSpeak('Welcome to the world of top class conferencing! You are being placed into a conference.', voice='WOMAN')107 conference_params = {108 'enterSound':'beep:1',109 'waitSound':BASE_URL + 'response/conf/music/',110 'timeLimit':'8400',111 'callbackUrl':BASE_URL + 'response/conf/callback/',112 'callbackMethod':'GET',113 }114 r.addConference(CONFERENCE_NAME, **conference_params)115 response = make_response(r.to_xml())116 response.headers['Content-Type'] = 'text/xml'117 return response118@app.route('/response/conf/callback/', methods=['GET', 'POST'])119def conference_callback():120 """121 Refresh the list of member on receiving any callback122 """123 event = request.args.get('Event') or None124 pr = get_pusher_connection()125 members = get_conference_members(CONFERENCE_NAME)126 pr['pycon.plivo'].trigger('show_members', json.dumps(members))127 response = make_json_response({'success': True})128 return response129@app.route('/response/conf/music/', methods=['GET', 'POST'])130def conference_music():131 r = plivo.Response()132 play_parameters = {133 'loop':'50',134 }135 r.addPlay(PLIVO_MUSIC, **play_parameters)136 response = make_response(r.to_xml())137 response.headers['Content-Type'] = 'text/xml'138 return response139@app.route('/conference/members/', methods=['GET', 'POST'])140def conference_members():141 pr = get_pusher_connection()142 members = get_conference_members(CONFERENCE_NAME)143 response = make_json_response(json.dumps(members))144 return response145@app.route('/conference/kick/', methods=['GET', 'POST'])146def conference_kick():147 member_id = request.args.get('member_id')148 p = get_plivo_connection()149 member_params = {150 'member_id': member_id,151 'conference_name': CONFERENCE_NAME,152 'callback_url':BASE_URL + 'response/conf/callback/',153 'callback_method':'GET',154 }155 p.kick_member(member_params)156 return 'Done'157@app.route('/conference/mute/', methods=['GET', 'POST'])...

Full Screen

Full Screen

views.py

Source:views.py Github

copy

Full Screen

...5from parsing.sentence_parser import parse_sentence6from scrap.scrap_manager import scrap_manager7from tagging.tagging import tag_tokens8from tokenization.tokenize import tokenize_text9def make_json_response(data: Any) -> HttpResponse:10 return HttpResponse(json.dumps(data))11def tokenize(request: HttpRequest) -> HttpResponse:12 text = request.GET.get('text')13 if not text:14 return HttpResponseBadRequest('No text')15 return make_json_response(tokenize_text(text))16def tag(request: HttpRequest) -> HttpResponse:17 text = request.GET.get('text')18 if not text:19 return HttpResponseBadRequest('No text')20 return make_json_response(tag_tokens(tokenize_text(text)))21def parse(request: HttpRequest) -> HttpResponse:22 text = request.GET.get('text')23 if not text:24 return HttpResponseBadRequest('No text')25 openie = request.GET.get('openie', 'false') == 'true'26 return make_json_response(parse_sentence(text, use_openie=openie).serialize())27def parse_wiki_how(request: HttpRequest) -> HttpResponse:28 text = request.GET.get('text')29 if not text:30 return HttpResponseBadRequest('No text')31 article = scrap_manager.scrap_page('https://www.wikihow.com/wikiHowTo?search=' + text)32 if article is None:33 return HttpResponseBadRequest('Please use another search term')34 openie = request.GET.get('openie', 'false') == 'true'35 return make_json_response(parse_article(article, use_openie=openie).serialize())36def test(request: HttpRequest) -> HttpResponse:...

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 localstack 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