Best Python code snippet using localstack_python
app.py
Source:app.py
...44}45@app.route("/")46def index():47 return "HungryOsori TestServer"48def make_error_response(error_code, message):49 result = {}50 result['error'] = error_code51 result['message'] = message52 return json.dumps(result)53def make_success_result(**args):54 result = {}55 result['error'] = 056 result['message'] = 'Success'57 for key, value in args.items():58 result[key] = value59 return json.dumps(result)60def refresh_user_key():61 r_uuid = base64.urlsafe_b64encode(uuid.uuid4().bytes)62 return r_uuid.replace('=', '')63def verify_user():64 user_id = None65 user_key = None66 try:67 user_id = request.form['user_id']68 user_key = request.form['user_key']69 except Exception as e:70 return False, -1, -1, "no have form data 'user_id' or 'user_key"71 try:72 if str(session['user_id']) != user_id or str(session['user_key']) != user_key:73 return False, -1, -1, "invalid session"74 except Exception as e:75 return False, -1, -1, "no have key in session"76 return True, user_id, user_key77def is_vaild_id(id):78 if bool(re.match(r"(^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$)", id)) is False:79 return False80 return True81def make_temp_password():82 return refresh_user_key()83def make_token_for_reset_password():84 return refresh_user_key()85@app.route('/req_signup', methods=["POST"])86def req_signup():87 try:88 user_id = request.form['user_id']89 password = request.form['password']90 except Exception as e:91 return make_error_response(-1, "invalid form data")92 if is_vaild_id(user_id) is False:93 return make_error_response(-200, "invalid id(must email)")94 if user_id not in users:95 users[user_id] = User()96 users[user_id].id = user_id97 users[user_id].password = password98 users[user_id].subscriptions = []99 users[user_id].token = None100 else:101 return make_error_response(-100, "alreay exist user_id")102 return make_success_result()103@app.route('/req_login', methods=["POST"])104def req_login():105 try:106 user_id = request.form['user_id']107 except Exception as e:108 return make_error_response(-1, "invalid form data")109 if user_id not in users:110 return make_error_response(-100, "not exist user")111 user = users[user_id]112 try:113 user_key = request.form['user_key']114 except:115 user_key = refresh_user_key()116 try:117 user.token = request.form['token']118 except Exception as e:119 push_token = None120 try:121 password = request.form['password']122 if user.password != password:123 return make_error_response(-200, "invalid password")124 else:125 session['user_id'] = user_id126 session['user_key'] = user_key127 except Exception as e:128 if 'user_id' in session:129 if str(session['user_id']) == user_id and \130 str(session['user_key']) != user_key:131 return make_error_response(-1, "invalid session, retry to login")132 else:133 session['user_id'] = user_id134 session['user_key'] = user_key135 if hasattr(user, 'reset_pw_token'):136 del user.reset_pw_token137 return make_success_result(user_key=user_key)138@app.route('/req_change_password', methods=["POST"])139def req_change_password():140 try:141 user_id = request.form['user_id']142 password = request.form['password']143 new_password = request.form['new_password']144 except Exception as e:145 return make_error_response(-1, "invalid form data")146 if user_id not in users:147 return make_error_response(-100, "not exist user")148 user = users[user_id]149 if user.password != password:150 return make_error_response(-200, "invalid password")151 user.password = new_password152 return make_success_result()153@app.route('/req_find_password', methods=["POST"])154def req_find_password():155 try:156 user_id = request.form['user_id']157 except Exception as e:158 return make_error_response(-1, "invalid form data")159 if user_id not in users:160 return make_error_response(-100, "not exist user")161 user = users[user_id]162 user.password = make_temp_password()163 user.reset_pw_token = make_token_for_reset_password()164 pw_reset_url = url_for('find_password', pw_reset_token = user.reset_pw_token)165 return make_success_result(new_password=user.password, pw_reset_url=pw_reset_url)166@app.route('/find_password/<pw_reset_token>', methods=["POST"])167def find_password(pw_reset_token=None):168 if pw_reset_token is None:169 return make_error_response(-1, "invalid route")170 new_password = None171 for user in users.values():172 if hasattr(user, 'reset_pw_token'):173 if user.reset_pw_token == pw_reset_token:174 del user.reset_pw_token175 new_password = make_temp_password()176 user.password = new_password177 break178 if new_password is None:179 return make_error_response(-100, "invalid token")180 return make_success_result(new_password=new_password)181@app.route("/req_subscription_list", methods=["GET", "POST"])182def req_subscription_list():183 if request.method == "GET":184 return make_error_response(-1, "need to change request method(get -> post)")185 user_verified_info = verify_user()186 if not user_verified_info[0]:187 return make_error_response(-1, "invalid user id-key")188 user_id = user_verified_info[1]189 try:190 if users.has_key(user_id) is True:191 subscription_list = users[user_id].subscriptions192 except:193 return make_error_response(-1, "collection error")194 return make_success_result(subscriptions=subscription_list)195@app.route("/req_entire_list", methods=["POST"])196def req_entire_list():197 user_info = verify_user()198 if not user_info[0]:199 return make_error_response(-1, "invalid user id-key")200 return make_success_result(crawlers=[item for item in crawlers.itervalues()])201@app.route("/req_subscribe_crawler", methods=["POST"])202def req_subscribe_crawler():203 user_info = verify_user()204 if not user_info[0]:205 return make_error_response(-1, "invalid user id-key")206 user_id = user_info[1]207 try:208 crawler_id = request.form['crawler_id']209 except Exception as e:210 return make_error_response(-1, "no have crawler_id")211 try:212 if crawler_id in users[user_id].subscriptions:213 return make_error_response(-1, "already registered")214 except:215 return make_error_response(-1, "collection error")216 users[user_id].subscriptions.append(crawler_id)217 return make_success_result()218@app.route("/req_unsubscribe_crawler", methods=["POST"])219def req_unsubscribe_crawler():220 user_info = verify_user()221 if not user_info[0]:222 return make_error_response(-1, "invalid user id-key")223 user_id = user_info[1]224 try:225 crawler_id = request.form['crawler_id']226 except Exception as e:227 return make_error_response(-1, "no have crawler_id")228 try:229 if crawler_id not in users[user_id].subscriptions:230 return make_error_response(-1, "not registered")231 except:232 return make_error_response(-1, "collection error")233 users[user_id].subscriptions.remove(crawler_id)234 return make_success_result()235@app.route("/register_push_token", methods=["POST"])236def req_register_push_token():237 user_info = verify_user()238 if not user_info[0]:239 return make_error_response(-1, "invalid user id-key")240 try:241 token = request.form['token']242 except Exception as e:243 return make_error_response(-1, "no have apple push token")244 user_id = user_info[1]245 users[user_id].token = token246 return make_success_result()247@app.route('/req_push', methods=["POST"])248def req_push():249 try:250 title = request.form['title']251 message = request.form['message']252 except Exception as e:253 return make_error_response(-1, "invalid data")254 tokens = []255 for user in users.values():256 if hasattr(user, 'token') is True:257 tokens.append(user.token)258 try:259 result = push_service.notify_multiple_devices(registration_ids=tokens, message_title=title,260 message_body=message)261 except Exception as e:262 print e263 print result264 return str(result)265if __name__ == '__main__':...
json_rpc.py
Source:json_rpc.py
...57 "params": notification.params,58 }59def make_success_response(response):60 return {"jsonrpc": "2.0", "result": response.result, "id": response.id}61def make_error_response(response):62 return {63 "jsonrpc": "2.0",64 "error": {65 "code": response.code,66 "message": response.message,67 "data": response.data,68 },69 "id": response.id,70 }71class Dispatcher(object):72 def __init__(self):73 self._handlers = dict()74 def __call__(self, data):75 try:76 json = parse_json(data)77 except JsonParseError as e:78 response = ErrorResponse(-32700, "Parse error", str(e), None)79 return serialize_to_json(make_error_response(response))80 else:81 response = self._handle(json)82 if response:83 return serialize_to_json(response)84 return None85 def add_method(self, param_parser=Any()):86 def decorator(handler):87 self._handlers[handler.__name__] = (handler, param_parser)88 return handler89 return decorator90 def _handle(self, json):91 if isinstance(json, list):92 return self._handle_batch(json)93 else:94 return self._handle_single(json)95 def _handle_batch(self, batch):96 responses = [self._handle_single(single) for single in batch]97 filtered = [response for response in responses if response is not None]98 if len(filtered) > 0:99 return filtered100 return None101 def _handle_single(self, single):102 try:103 request = parse(request_parser, single)104 except ParserError as e:105 return make_error_response(106 ErrorResponse(-32600, "Invalid Request", str(e), None)107 )108 else:109 if isinstance(request, Request):110 return self._handle_request(request.method, request.params, request.id)111 else:112 self._handle_request(request.method, request.params, None)113 return None114 def _handle_request(self, method, params, request_id):115 try:116 handler, param_parser = self._handlers[method]117 except KeyError:118 return make_error_response(119 ErrorResponse(-32601, "Method not found", None, request_id)120 )121 try:122 params = parse(param_parser, params)123 except ParserError as e:124 return make_error_response(125 ErrorResponse(-32602, "Invalid params", str(e), request_id)126 )127 try:128 return make_success_response(SuccessResponse(handler(params), request_id))129 except Exception:130 LOG_CURRENT_EXCEPTION()131 return make_error_response(132 ErrorResponse(-32603, "Internal error", None, request_id)...
views.py
Source:views.py
1from django.shortcuts import render2from django.http import JsonResponse, response3from browser.models import Terminal, State4def make_error_response(message, errors=None):5 partial_response = {6 'success': False,7 'message': message,8 'errors': errors9 }10 return JsonResponse(partial_response)11def make_success_response(message, data=None):12 partial_response = {13 'success': True,14 'message': message,15 'data': data16 }17 return JsonResponse(partial_response)18def query(request):19 if not request.GET:20 response = make_error_response(21 "You need to provide from_state and dest_state URL parameters"22 )23 return response24 25 from_state_id = request.GET.get('from_state')26 dest_state_id = request.GET.get('dest_state')27 try:28 from_state = State.objects.get(state_id=from_state_id)29 if from_state.terminal_set.count() == 0:30 # state does not have any terminal31 response = make_error_response(32 f'We do not, currently, know of any terminal in {from_state.name}'33 )34 return response35 except State.DoesNotExist:36 response = make_error_response(f'"from" state with id "{from_state_id}" does not exist')37 return response38 39 try:40 dest_state = State.objects.get(state_id=dest_state_id)41 if dest_state.terminal_set.count() == 0:42 # state also does not have any connecting terminal43 response = make_error_response(44 f'We do not, currently, know of any terminal in {dest_state.name}'45 )46 return response47 except State.DoesNotExist:48 response = make_error_response(f'"dest" state with id "{dest_state_id}" does not exist')49 return response50 51 connected_terminals = {}52 for terminal in from_state.terminal_set.all():53 for dest_terminal in terminal.dest_terminals.all():54 if dest_terminal.state.state_id == dest_state_id:55 connected_terminals.setdefault(terminal, []).append(dest_terminal)56 57 if len(connected_terminals) > 0:58 response = make_success_response(59 f'These terminals in {from_state.name} travel to {dest_state.name}',60 data = [61 {62 'terminal': terminal.name,...
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!!