def post(self): uid, role = get_auth(request) try: data = request.get_json() except BadRequest: raise ZoeRestAPIException('Error decoding JSON data') if 'what' not in data: raise ZoeRestAPIException('"what" is required in query object') what = data['what'] if 'filters' not in data: filters = {} else: filters = data['filters'] if not isinstance(filters, dict): raise ZoeRestAPIException('query filters should be a dictionary of {attribute: requested_value} entries') if what == 'stats_scheduler': # TODO ret = None elif what == 'execution': if role != 'admin': filters['user_id'] = uid execs = self.api_endpoint.execution_list(uid, role, **filters) return [x.serialize() for x in execs] else: raise ZoeRestAPIException('unknown query {}'.format(what)) return ret
def post(self): try: asset = Asset(**request.get_json()) asset.save() except Exception as e: return {"error": e.message}, 422 return asset.to_export(), 201
def put(self): from flask_restful import request try: data = request.get_json(force=True) if "newpassword" not in data: return self.send_errors( "Error", "Invalid request, this operation cannot be completed", code=hcodes.HTTP_BAD_REQUEST ) user = self.get_current_user() pwd = BaseAuthentication.hash_password(data["newpassword"]) user.password = pwd user.save() auth = self.global_get('custom_auth') tokens = auth.get_tokens(user=auth._user) for token in tokens: auth.invalidate_token(token=token["token"]) auth.invalidate_all_tokens() except: return self.send_errors( "Error", "Unknown error, please contact system administrators", code=hcodes.HTTP_BAD_REQUEST ) return self.empty_response()
def delete(self): try: if parsers.RequestQueryParser.query(): # Parse query from request. These entities will be deleted. entries = self._retrieve() else: # No query was passed. Search for identities in the body. entries, _ = commons.CollectionHelper.transform(request.get_json()) if not entries: raise errors.BadRequestError('DATA_CANNOT_BE_EMPTY') identities = self._identify(entries) del entries self.event_manager().trigger('before_delete', identities=identities) entries = self.repository.delete(identities) entries, fields = self.serializer.project(entries) self.event_manager().trigger('after_delete', entries=entries) return self.response({'deleted': entries}, projection=fields, wrap=False) except errors.GrapherError as e: return self.response(status=e.status_code, errors=e.as_api_response())
def post(self): """ Starts an execution, given an application_id. Takes a JSON object like this: { "application_id": 4 } :return: the new execution_id """ start_time = time.time() calling_user = authenticate(request, self.state) try: data = request.get_json() except BadRequest: raise ZoeRestAPIException('Error decoding JSON data') execution = Execution(self.state) try: execution.from_dict(data, checkpoint=False) except ZoeException as e: raise ZoeRestAPIException(e.value) # if not zoe_sched_singleton.validate(execution.application): # return error('admission control refused this application description') is_authorized(calling_user, execution, 'create') check_quota(calling_user, self.state) execution.id = self.state.gen_id() self.state.new('execution', execution) self.platform.execution_submitted(execution) self.state.state_updated() singletons['metric'].metric_api_call(start_time, 'execution', 'start', calling_user) return {'execution_id': execution.id}, 201
def get_input(self, forcing=True, single_parameter=None): """ Recover parameters from current requests. Note that we talk about JSON only when having a PUT method, while there is URL encoding for GET, DELETE and Headers encoding with POST. Non-JSON Parameters are already parsed at this point, while JSON parameters may be already saved from another previous call """ if len(self._json_args) < 1: try: self._json_args = request.get_json(force=forcing) for key, value in self._json_args.items(): if value is None: continue # if isinstance(value, str) and value == 'None': # continue if key in self._args and self._args[key] is not None: # print("Key", key, "Value", value, self._args[key]) key += '_json' self._args[key] = value except Exception: # as e: # logger.critical("Cannot get JSON for req: '%s'" % e) pass if single_parameter is not None: return self._args.get(single_parameter) if len(self._args) > 0: logger.info("Parameters %s" % self._args) return self._args
def put(self, id): data = request.get_json(force=True) item = Item.get_by_id(id) item.value = data['value'] item.put() return item, 200
def post(self): data = request.get_json(force=True) item = Item() item.value = data['value'] item.put() return item, 201
def post(self, asset_title): asset = Asset.objects.get_or_404(title=asset_title) credit = Credit(**request.get_json()) asset.credits.append(credit) try: asset.save() except Exception as e: return {"error": e.message}, 422 return credit.to_export(), 201
def post(self): json_data = request.get_json() if not json_data: return jsonify({'message': 'No input data provided'}), 400 data,errors = self.ns.load(json_data) mockecr_id = str(uuid.uuid4()) mockecr[mockecr_id] = data mockecr[mockecr_id]["id"] = mockecr_id return mockecr[mockecr_id], 201
def put(self, mockecr_id): self.abort_if_mockecr_doesnt_exist(mockecr_id) json_data = request.get_json() if not json_data: return jsonify({'message': 'No input data provided'}), 400 data,errors = self.ns.load(json_data) mockecr[mockecr_id] = data mockecr[mockecr_id]["id"] = mockecr_id return mockecr[mockecr_id], 201
def put(self): """ Place an order and make a payment. --- tags: - orders consumes: - application/json parameters: - in: body name: body required: true description: Json object for an order schema: type: object properties: customerEmailAddress: type: string default: [email protected] orderItems: type: array items: type: object properties: description: type: string default: Test Item price: type: float default: 10.00 totalPriceBeforeVat: type: float default: 10.00 totalVat: type: float default: 2.10 totalPrice: type: float default: 12.10 """ try: order = Order(request.get_json()) order.validate() except DataError as e: return {'Error': str(e)}, 400 # Process order try: order_service = OrdersService() order = order_service.create_order(order) return {'orderId': order.order_id, 'orderStatus': order.order_status}, 201 except OrderError: return {'Order Failed Reason': 'Error saving order'}, 500 except Exception as e: app.logger.error('Unhandled error: {0}'.format(str(e))) return {'Order Failed Reason': 'Unhandled exception'}, 500
def post(self): json_data = request.get_json() if not json_data: return jsonify({'message': 'No input data provided'}), 400 data,errors = self.ts.load(json_data) ticket_id = str(uuid.uuid4()) tickets[ticket_id] = data tickets[ticket_id]["id"] = ticket_id tickets[ticket_id]["self"] = self.api.url_for(Ticket, ticket_id = ticket_id, _external=True) return tickets[ticket_id], 201
def put(self, title): asset = Asset.objects.get_or_404(title=title) data = request.get_json() try: for field_name, field_value in data.items(): setattr(asset, field_name, field_value) asset.save() except Exception as e: return {"error": e.message}, 422 return asset.to_export(), 200
def put(self): try: entries, _ = commons.CollectionHelper.transform(request.get_json()) # Makes sure every entry has an identity. self._identify(entries) return self._update(entries) except errors.GrapherError as e: return self.response(status=e.status_code, errors=e.as_api_response(), wrap=False)
def post(self): json_data = request.get_json() if not json_data: return jsonify({'message': 'No input data provided'}), 400 use_id = str(uuid.uuid4()) data,errors = self.us.load(json_data) uses[use_id] = data uses[use_id]["id"] = use_id uses[use_id]["self"] = self.api.url_for(Use, use_id = use_id, _external=True) return uses[use_id], 201
def put(self, use_id): self.abort_if_use_doesnt_exist(use_id) json_data = request.get_json() if not json_data: return jsonify({'message': 'No input data provided'}), 400 data,errors = self.us.load(json_data) uses[use_id] = data uses[use_id]["id"] = use_id # Just to make sure uses[use_id]["self"] = self.api.url_for(Use, use_id = use_id, _external=True) return uses[use_id], 201
def post(self): json_data = request.get_json() if not json_data: return jsonify({'message': 'No input data provided'}), 400 data,errors = self.ns.load(json_data) nexus_id = str(uuid.uuid4()) nexus[nexus_id] = data nexus[nexus_id]["id"] = nexus_id nexus[nexus_id]["self"] = self.api.url_for(Nexus, nexus_id = nexus_id, _external=True) return nexus[nexus_id], 201
def put(self, nexus_id): self.abort_if_nexus_doesnt_exist(nexus_id) json_data = request.get_json() if not json_data: return jsonify({'message': 'No input data provided'}), 400 data,errors = self.ns.load(json_data) nexus[nexus_id] = data nexus[nexus_id]["id"] = nexus_id nexus[nexus_id]["self"] = self.api.url_for(Nexus, nexus_id = nexus_id, _external=True) return nexus[nexus_id], 201
def post(self): rq_json = request.get_json() hours = rq_json['hours'] minutes = rq_json['minutes'] comment = rq_json['comment'] user_id = rq_json['user_id'] project_id = rq_json['project_id'] created_time_entry = self.project_service.report_user_time( project_id, user_id, get_float_duration(hours, minutes), comment, datetime.date.now()) return created_time_entry, 201, {'x-created-id': created_time_entry.time_entry_id}
def post(self): """Add the new doctor""" doctorInput = request.get_json(force=True) doc_first_name=doctorInput['doc_first_name'] doc_last_name = doctorInput['doc_last_name'] doc_ph_no = doctorInput['doc_ph_no'] doc_address = doctorInput['doc_address'] doctorInput['doc_id']=conn.execute('''INSERT INTO doctor(doc_first_name,doc_last_name,doc_ph_no,doc_address) VALUES(?,?,?,?)''', (doc_first_name, doc_last_name,doc_ph_no,doc_address)).lastrowid conn.commit() return doctorInput
def post(self): """api to add the patient in the database""" patientInput = request.get_json(force=True) pat_first_name=patientInput['pat_first_name'] pat_last_name = patientInput['pat_last_name'] pat_insurance_no = patientInput['pat_insurance_no'] pat_ph_no = patientInput['pat_ph_no'] pat_address = patientInput['pat_address'] patientInput['pat_id']=conn.execute('''INSERT INTO patient(pat_first_name,pat_last_name,pat_insurance_no,pat_ph_no,pat_address) VALUES(?,?,?,?,?)''', (pat_first_name, pat_last_name, pat_insurance_no,pat_ph_no,pat_address)).lastrowid conn.commit() return patientInput
def put(self,id): """api to update the patient by it id""" patientInput = request.get_json(force=True) pat_first_name = patientInput['pat_first_name'] pat_last_name = patientInput['pat_last_name'] pat_insurance_no = patientInput['pat_insurance_no'] pat_ph_no = patientInput['pat_ph_no'] pat_address = patientInput['pat_address'] conn.execute("UPDATE patient SET pat_first_name=?,pat_last_name=?,pat_insurance_no=?,pat_ph_no=?,pat_address=? WHERE pat_id=?", (pat_first_name, pat_last_name, pat_insurance_no,pat_ph_no,pat_address,id)) conn.commit() return patientInput
def put(self, asset_title, role): asset = Asset.objects.get_or_404(title=asset_title) credit = asset.credits.filter(role=role)[0] if not credit: return {"error": "Credit not found"}, 404 data = request.get_json() try: for field_name, field_value in data.items(): setattr(credit, field_name, field_value) asset.save() except Exception as e: return {"error": e.message}, 422 return credit.to_export(), 200
def put(self,id): """Update the doctor by its id""" doctorInput = request.get_json(force=True) doc_first_name=doctorInput['doc_first_name'] doc_last_name = doctorInput['doc_last_name'] doc_ph_no = doctorInput['doc_ph_no'] doc_address = doctorInput['doc_address'] conn.execute( "UPDATE doctor SET doc_first_name=?,doc_last_name=?,doc_ph_no=?,doc_address=? WHERE doc_id=?", (doc_first_name, doc_last_name, doc_ph_no, doc_address, id)) conn.commit() return doctorInput
def post(self): signup_obj = request.get_json() user = User(signup_obj['username']) if not user.verify_password(signup_obj['password']): return_code = 401 message = { 'status': 'failure', 'message': 'username doesn\'t exist or password incorrect.' } else: user.login() login_user(user, remember=True) return_code = 200 message = { 'status': 'success', 'message': 'Successful login!'} return message, return_code
def post(self): signup_obj = request.get_json() signup_status = User(signup_obj['username']).register(signup_obj['password'] ,signup_obj['email'] ,signup_obj['first_name'] ,signup_obj['last_name']) if signup_status == True: return_code = 200 message = { 'status': 'success', 'message': 'User created successfully!'} else: return_code = 409 message = { 'status': 'failure', 'message': 'username or email already exists.' } return message, return_code
def post(self): my_username = session['user_id'] review_obj = request.get_json() rtn = RankUtils().add_review(my_username ,review_obj['item_id'] ,review_obj['review_text'] ,review_obj['rank']) if rtn: message = { 'status': 'success', 'message': 'Review added'} else: message = { 'status': 'failure', 'message': 'Review not added'} return message
def patch(self): try: r, _ = commons.CollectionHelper.transform(request.get_json()) # We need all the entities' data to run meaningful validations. identities = self._identify(r) entries = self.repository.find(identities) # Patches the request data onto the database data. for i in range(len(r)): entries[i].update(r[i]) del r return self._update(entries) except errors.GrapherError as e: return self.response(status=e.status_code, errors=e.as_api_response())
def put(self): """ Create a customer --- tags: - customers produces: - application/json parameters: - in: body name: body required: true description: Json request for creating a customer schema: type: object properties: firstName: type: string default: Test surname: type: string default: McTest emailAddress: type: string default: [email protected] responses: 201: description: Customer Created 400: description: Invalid Request 500: description: Server Error """ # Validate request, return 400 if invalid try: customer = Customer(request.get_json()) customer.validate() except DataError as e: return {'Error': str(e)}, 400 try: customer_service = CustomerService() customer_service.create_or_get_customer(customer) return {'Status': 'SUCCESS'}, 201 except CustomerServiceError: return {'Status': 'ERROR'}, 500
def delete(self): """ Delete specified messages for logged in user --- tags: - notifications produces: - application/json parameters: - in: header name: Authorization description: Base64 encoded session token required: true type: string default: Token sessionTokenHere== - in: body name: body required: true description: JSON object containing message ids to delete schema: properties: messageIds: type: array items: integer required: true responses: 200: description: Messages deleted 500: description: Internal Server Error """ try: message_ids = request.get_json()["messageIds"] if message_ids: MessageService.delete_multiple_messages( message_ids, token_auth.current_user()) return {"Success": "Messages deleted"}, 200 except Exception as e: error_msg = f"DeleteMultipleMessages - unhandled error: {str(e)}" current_app.logger.critical(error_msg) return {"Error": "Unable to delete messages"}, 500
def post(cls): """POST method that handles the creation of a cinema. path : /api/cinema/register Description ----------- This will create a new entry in the cinema, location, user and account table. """ is_logged_in = get_jwt_identity() if is_logged_in: return {"message": INVALID_ALREADY_LOGIN_400}, 400 user_data = request.get_json() try: user_data = cls.user_schema.load(user_data) except ValidationError as err: return {"message": err.messages} if AccountModel.find_by_email(email=user_data["account"]["email"]): return {"message": ACCOUNT_EXISTS_MESSAGE_400}, 400 new_account = AccountModel(**user_data["account"]) new_location = LocationModel( barangay_id=user_data["location"]["barangay"]["id"], longitude=user_data["location"]["longitude"], latitude=user_data["location"]["latitude"] ) new_cinema = CinemaModel(**user_data["cinema"]) new_cinema_user = UserModel( first_name=user_data["first_name"], last_name=user_data["last_name"], contact_no=user_data["contact_no"], location=new_location, account=new_account, cinema=new_cinema ) try: new_cinema_user.save_to_db() except Exception as e: print(e) db.session.rollback() db.session.flush() return ({"message": UNKNOWN_ERROR_MESSAGE_500}, 500) return ({"message": ACCOUNT_CREATED_MESSAGE_201}, 201)
def post(self): data = request.get_json() exam_id = data["id"] exam_name = data["exam_name"] exam_date = data["exam_date"] exam_start_time = data["exam_start_time"] exam_end_time = data["exam_end_time"] exam_centre_addr = data["exam_centre_addr"] exam_city = data["exam_city"] exam_area_pincode = data["exam_area_pincode"] skills_preference = data["skills_preference"] gender_preference = data["gender_preference"] language_preference = data["language_preference"] disabled_id = data["disabled_id"] volunteer_id = data["volunteer_id"] if (exam_id > 0 and len(volunteer_id) > 0): examToUpdate = Exam.query.filter_by(id=int(exam_id)) examToUpdate.volunteer_id = volunteer_id examToUpdate.exam_request_status = "closed" #db.session.merge(examToUpdate) db.session.commit() return "Exam assigned successfully" else: volunteer_id = None status = "open" exam = Exam(exam_name=exam_name, exam_date=exam_date, exam_start_time=exam_start_time, exam_end_time=exam_end_time, exam_centre_addr=exam_centre_addr, exam_city=exam_city, exam_area_pincode=exam_area_pincode, skills_preference=skills_preference, gender_preference=gender_preference, language_preference=language_preference, disabled_id=disabled_id, volunteer_id=volunteer_id, exam_request_status=status) db.session.add(exam) db.session.commit() return exam.json()
def put(self, city, zone, rule): rule_q = CityModel.query(CityModel.name == city, CityModel.zone == zone, CityModel.rule == rule).get() if not rule_q: return {'Error 404:': 'Rule does not exist.'}, 404 body = request.get_json() if not body: return {'Error:': 'Invalid inputs'}, 400 try: time = body['time'] intensity = int(body['intensity']) rule_q.time = time rule_q.intensity = intensity except KeyError: return {'Error:': 'Invalid inputs'}, 400 except BadValueError: return {'Error:': 'Invalid inputs'}, 400 rule_q.put() return {'Success': 'Rule modified'}
def post(self): claims = get_jwt() data = request.get_json() if not data.get("list_title"): return { "description": "The list can not be created without list title", "error": "missing_info", }, 400 return { "message": "The list created successfully", "list": TasksListModelService.json( TasksListModelService.create( dict( list_title=data.get("list_title"), user_id=claims.get("user_id") ), self.app, db, ) ), }, 201
def post(self): data = {} error = False message = "" try: params = request.get_json(force=True) data = DB.TagAttribute.create(params).json() except Exception as e: DB.session.rollback() message = str(e) error = True finally: return ResponseAPI('TagAttribute', 'post', data=data, message=message, error=error).json()
def post(self, group=None): obj_group = request.get_json() employees = obj_group[ParamConstants.PARAM_EMPLOYEES] if ParamConstants.PARAM_EMPLOYEES in obj_group else [] for employee in employees: employee[ParamConstants.PARAM_CAPACITY] = Converter.convert( employee[ParamConstants.PARAM_CAPACITY], Types.TYPE_INT) match_params = { ParamConstants.PARAM_GROUP: group if group else obj_group[ParamConstants.PARAM_GROUP] } return Accessor.factory(DbConstants.CFG_DB_SCRUM_API).upsert({ AccessParams.KEY_COLLECTION: DbConstants.PROJECT_TEAM, AccessParams.KEY_TYPE: AccessParams.TYPE_SINGLE, AccessParams.KEY_OBJECT: obj_group, AccessParams.KEY_MATCH_PARAMS: match_params }), 201
def post(self): """api to add the patient in the database""" patientInput = request.get_json(force=True) pat_first_name = patientInput['pat_first_name'] pat_last_name = patientInput['pat_last_name'] age = patientInput['age'] sex = patientInput['sex'] pat_ph_no = patientInput['pat_ph_no'] pat_address = patientInput['pat_address'] bed_id = patientInput['bed_id'] patientInput['pat_id'] = conn.execute( '''INSERT INTO patient(pat_first_name, pat_last_name, age,sex,pat_ph_no, pat_address, bed_id) VALUES(?,?,?,?,?,?,?)''', (pat_first_name, pat_last_name, age, sex, pat_ph_no, pat_address, bed_id)).lastrowid conn.execute("UPDATE bed SET pat_id=? WHERE bed_id=?", (patientInput['pat_id'], bed_id)) conn.commit() return patientInput
def post(self): claims = get_jwt() if not claims.get("is_admin"): return { "description": "You need admin privileges", "error": "invalid_credentials", }, 401 color_data = request.get_json() if not color_data["color_value"]: return { "description": "The color needs a color hex value", "error": "missing_info", }, 400 color_attrs: ColorInterface = dict( color_value=color_data["color_value"]) color: ColorModel = ColorService.create(color_attrs, self.app, db) return { "message": "Color created successfully", "color": ColorService.json(color), }, 201
def post(self): req_json = json.dumps(request.get_json()) load_data, errors = BasicSchema().loads(req_json) if errors: return RetStatus(False, "parse request data failed.").dumps_json() ret = Admin.find_by_username(load_data['username']) if ret.check() is False: return RetStatus(False, "check user's availability failed.").dumps_json() elif ret.data is None: return RetStatus(False, "username had be used.").dumps_json() user = Admin(uuid=uuid.uuid1(), username=load_data['username'], password=load_data['password'], login_type=load_data['login_type']) add_ret = Admin.ADD(user) if add_ret.check() is False: return add_ret.dumps_json() return RetStatus(True, "register success.", data=user.uuid).dumps_json()
def put(cls, user_id: int): user = UserModel.find_by_id(user_id) if not user: raise ResourceNotFound requester_id = get_jwt_identity() print(user_id != 1) if requester_id != user_id and requester_id != 1: raise NotAuthorized fields_json = request.get_json() supported_fields = ['first_name', 'last_name', 'role', 'active'] update_fields = { k: v for k, v in fields_json.items() if k in supported_fields } user.update(update_fields) return {"success": True, "data": user_schema.dump(user)}, 200
def put(self, id): """api to update the patient by it id""" try: if session['role_id'] == Roles.ADMIN.val(): patientInput = request.get_json(force=True) pat_first_name = patientInput['pat_first_name'] pat_last_name = patientInput['pat_last_name'] pat_insurance_no = patientInput['pat_insurance_no'] pat_ph_no = patientInput['pat_ph_no'] pat_address = patientInput['pat_address'] conn.execute( "UPDATE patient SET pat_first_name=?,pat_last_name=?,pat_insurance_no=?,pat_ph_no=?,pat_address=? WHERE pat_id=?", (pat_first_name, pat_last_name, pat_insurance_no, pat_ph_no, pat_address, id)) conn.commit() return patientInput else: return {'status': 401, 'msg': 'Not authorized'} except KeyError as no_key: return {'status': 403, 'msg': 'Forbidden'}
def post(self): current_user = get_jwt_identity() data = request.get_json() if not data: return invalid_data, 400 name = data["name"] desc = data["description"] location = data["location"] date = data["event_date"] event = Events.query.filter_by(name=name, user_id=current_user).first() if event: return {"error": "event exists"}, 409 post_event = Events(name=name, desc=desc, location=location, event_date=date, owner=current_user) db.session.add(post_event) db.session.commit() return {"message": "{} has been added".format(name)}, 201
def post(self): data = request.get_json() args = _email_enquiry_schema.load(data) args['phone'] = '0{}'.format(int(args['phone'])) try: MailSmtp.send_email([os.getenv('EMAIL_ENQUIRY')], 'Email Enquiry', 'email/EmailEnquiry.html', **args) # subscribe property with current_app.test_client() as client: client.post('/subscribe', json={ 'email': args['sender_email'], 'subscribe_type': 'property', 'subscribe_from': 'enquiry' }) except MailSmtpException as err: return {"error": str(err)}, 500 return {"message": "Email enquiry has send"}, 200
def post(self): data = request.get_json() user = user_schema.load(data) current_user = User.find_by_username(data['username']) if not current_user: return { 'message': 'User {} doesn\'t exist.'.format(data['username']) } if User.verify_hash(data['password'], current_user.password): try: access_token = create_access_token(identity=data['username']) return { 'message': 'Logged in as {}'.format(current_user.username), 'access_token': access_token } except: return {'message': 'Something went wrong.'}, 500 else: return {'message': 'Wrong password.'}
def post(self, id): data = request.get_json() pengguna_id = data[0]['value'] pengguna_nama = data[1]['value'] pengguna_posisi = data[2]['value'] pengguna_status = data[3]['value'] sql = "INSERT INTO `pengguna` SET " sql += "`pengguna_id` = '{}',".format(pengguna_id) sql += "`pengguna_nama` = '{}',".format(pengguna_nama.upper()) sql += "`pengguna_posisi` = '{}',".format(pengguna_posisi) sql += "`pengguna_status` = '{}' ".format(pengguna_status) sql += "ON DUPLICATE KEY UPDATE " sql += "`pengguna_nama` = '{}',".format(pengguna_nama.upper()) sql += "`pengguna_posisi` = '{}',".format(pengguna_posisi) sql += "`pengguna_status` = '{}' ".format(pengguna_status) execs = connExecute(sql) return execs
def post(self, name): if self.find_by_name(name): return { 'message': " an item with name '{}' already exists.".format(name) } data = request.get_json() item = {'name': name, 'price': data['price']} connection = sqlite3.connect('data.db') cursor = connection.cursor() query = "INSERT INTO items VALUES (?, ?)" cursor.execute(query, (item['name'], item['price'])) connection.commit() connection.close() return item
def updateWord(): try: corpusName = request.args.get('corpusName') word = request.get_json(force=True) myCorpusManager = corpusManager() myCorpusManager.update(corpusName=corpusName, wordObject=word) response_body = { "Flag": "Sucess", "Result": "the corpus " + corpusName + " has been updated" } return make_response(jsonify(response_body), 200) except Exception as e: print("file does not exist !.") return make_response( jsonify({ "Flag": "Fail", "Message": "An error has occured" + "\n \t" + str(e) }), 400) print(e.strerror)
def post(self): """ Insert multi-instances """ jsondata = request.get_json() if not jsondata or jsondata['username'] is None: return pretty_response(40001) if UsersModel.query.filter_by(username=jsondata['username']).first(): return pretty_response(40002) try: users_instance = UsersSchema().load(jsondata) users_instance = UsersModel( jsondata['username'], jsondata['password']) users_instance.add(users_instance) users_dump = UsersSchema().dump(users_instance) return pretty_response(200, users_dump) except ValidationError as e: current_app.logger.error(e.messages) return pretty_response(40003) except SQLAlchemyError as e: current_app.logger.error(e) return pretty_response(50001)
def post(self): reply_info = request.get_json() pic = PictureModule(id=reply_info["pic_id"]) pic_data = pic.find_by_id() print(reply_info) reply_channel = "reply-channel_%s" % (reply_info["commenter_id"]) print(reply_channel) reply_status = ReplyModule.create_reply(reply_info) notification = { "pic_id":reply_info["pic_id"], "pic_title": pic_data["title"], "created_at": reply_info["created_at"], "commenter_username": reply_info["username"], "pic_category": pic_data["category"] } NotificationModule.save_notification_to_db(notification) pusher.trigger(reply_channel,'reply', json_util.dumps(notification)) return make_response(json_util.dumps(reply_info, ensure_ascii=False).encode('utf8'), 200) if reply_status else None
def post(cls): user_json = request.get_json() user = user_schema.load(user_json) print(user) if UserModel.find_by_email(user.email): raise ResourceAlreadyExists( "error", {"email": ["Ya existe un recurso con este campo"]}) if UserModel.find_by_username(user.username): raise ResourceAlreadyExists( "error", {"username": ["Ya existe un recurso con este campo"]}) if UserModel.find_by_document(user.document): raise ResourceAlreadyExists( "error", {"document": ["Ya existe un recurso con este campo"]}) user.password = generate_password_hash(user.password, method='sha256') user.save_to_db() return {"success": True, "data": user_schema.dump(user)}, 201
def post(self): """ Insert multi-instances """ if current_identity.roles not in ['super']: return pretty_response(403) jsondata = request.get_json() if not jsondata or 'title' not in jsondata: return pretty_response(40001) if ManualsModel.query.filter_by(title=jsondata['title']).first(): return pretty_response(40002) try: manuals_instance = ManualsSchema().load(jsondata) manuals_instance.add(manuals_instance) manuals_dump = ManualsSchema().dump(manuals_instance) return pretty_response(200, manuals_dump) except ValidationError as e: current_app.logger.error(e.messages) return pretty_response(40003) except SQLAlchemyError as e: current_app.logger.error(e) return pretty_response(50001)
def post(self): data = request.get_json() print("post data", data) data["post_id"] = GenerateId() post_rec = db.session.query(Post).filter(Post.post_id == data["post_id"]).first() if post_rec: data["post_id"] = GenerateId() rec = Post( post_id = data["post_id"], user_id = data["user_id"], description = data["description"], ingrident = data["ingrident"], procedure = data["procedure"], file_name = data["file_name"], created_date=datetime.datetime.now()) db.session.add(rec) db.session.commit() #-------- return { "message": "User Successfully Posted!!", "code": 200}
def put(self, uuid): """ Update specific instance """ if current_identity.roles not in ['super']: return pretty_response(403) manuals_instance = ManualsModel.query.get_or_404(uuid) try: jsondata = request.get_json() ManualsSchema().load(jsondata) for key, val in jsondata.items(): setattr(manuals_instance, key, val) manuals_instance.updatetime = datetime.now() manuals_instance.update() manuals_dump = ManualsSchema().dump(manuals_instance) return pretty_response(200, manuals_dump) except ValidationError as e: current_app.logger.error(e.messages) return pretty_response(40003) except SQLAlchemyError as e: current_app.logger.error(e) return pretty_response(50001)
def post(self): """ Insert multi-instances """ if current_identity.roles not in ['super']: return pretty_response(403) jsondata = request.get_json() if not jsondata or 'opt_key' not in jsondata: return pretty_response(400) if OptionsModel.query.filter_by(opt_key=jsondata['opt_key']).first(): return pretty_response(400) try: options_instance, errors = OptionsSchema().load(jsondata) if errors: current_app.logger.error(errors) return pretty_response(400) options_instance.add(options_instance) options_dump, errors = OptionsSchema().dump(options_instance) return pretty_response(200, options_dump) except SQLAlchemyError as e: current_app.logger.error(e) return pretty_response(500)
def post(self): print("inside post") content = request.get_json() pk = content['PK'] value = {"sk": []} resp = table.query(KeyConditionExpression=Key('PK').eq(pk)) for i in range(len(resp['Items'])): print("inside for") try: if resp['Items'][i]['state'] == 'active': getTags = resp['Items'][i]['SK'] value['sk'].append(getTags) else: print("data not exist") except: print("key does not exist") return value
def post(): """ Add new user to the database :return: Access token """ data = request.get_json() try: Registration.schema.load(data) except ValidationError as err: raise BadRequest(err.messages) user = UserModel(**data) try: user.save_to_db() except Exception: raise ServerProblem() token = jwt.encode({'id': user.id}, config.SECRET_KEY) return jsonify({'access_token': token.decode('utf-8')})
def post(self): print("inside post") content = request.get_json() pk = content['PK'] createdBy = content['createdBy'] value = {"tagBySpecificUser": []} resp = table.query(KeyConditionExpression=Key('PK').eq(pk)) for i in range(len(resp['Items'])): try: if resp['Items'][i]['createdBy'] == createdBy: getTags = resp['Items'][i]['SK'] value['tagBySpecificUser'].append(getTags) else: print("data not exist") except: print("key does not exist") return value
def put(self, id): """ 更新一条记录 :return: """ params = request.get_json() name = params.get("name") age = params.get("age") # 查询数据是否存在 foo = db.session.query(Foo).get(id) if foo: if name: foo.name = name if age: foo.age = age db.session.commit() return success("更新成功!") else: return params_error("更新失败!不存在这条记录!")
def post(self): """ Starts an execution, given an application description. Takes a JSON object. :return: the new execution_id """ uid, role = get_auth(request) try: data = request.get_json() except BadRequest: raise zoe_api.exceptions.ZoeRestAPIException( 'Error decoding JSON data') application_description = data['application'] exec_name = data['name'] new_id = self.api_endpoint.execution_start(uid, role, exec_name, application_description) return {'execution_id': new_id}, 201