def post_detail(post_id): post = Post.query.get_or_404(post_id) schema = PostSchema() result = schema.dump(post) pprint(result.data) pprint(result.errors) return render_template('Post.html', title='Post', post=post)
def add_shipment(): ''' Add a new shipment to DB.\n Creates a new Vizion subscription reference for tracking. ''' schema = ShipmentSchema() data = request.get_json() scac = data.get('scac') bol_number = data.get('bill_of_lading') container_id = data.get('container_id') # Determine whether this shipment is a BL or container # Identifier for subscription creation is set based on this value is_bol = bol_number != None identifier = bol_number if is_bol else container_id # Create Vizion reference subscription and return ref ID vizion_ref_id = create_subscription(identifier, scac, is_bol) # Create shipment record and return shipment = Shipment(carrier_scac=scac, bill_of_lading=bol_number, container_id=container_id, vizion_reference_id=vizion_ref_id) db.session.add(shipment) db.session.commit() res = schema.dump(shipment) print('Created new shipment.') pprint(res) return res, 201
def put(self, id): print(f'PUT - for ID: {id}') req_data = None temp_schema = TempSchema() user = User.select().where(User.key == id) if user.exists(): try: reqjson = request.get_json(force=True) req_data = temp_schema.load(reqjson) except ValidationError as err: pprint(err) return {'error': err.messages}, 422 print('REQUEST DATA:', req_data) if 'date' not in req_data: req_data['date'] = dt.datetime.now() sensor_data = SensorData(temp=req_data['temp'], humi=req_data['humi'], date=req_data['date'], fkey=id) if sensor_data.save(): return {'success': 'Data saved.'} else: return {'failed': 'Data was not saved.'} else: return {'error': 'User not exists.'}
def show_index(): predicts = Prediction.query.first() serial = PredictionSerializer(predicts) pprint(serial.data) return render_template('index.html', metypes = MeType.query.all() )
async def test_get(request): emoji_1 = emoji.emojize('Python is :thumbs_up_sign:') emoji_2 = emoji.emojize('Python is :thumbsup:', use_aliases=True) job = dict(company='摩尔妈妈', start_date=datetime.datetime(2018, 3, 1)) baby_1 = dict(name='zhaohao', age=31) baby_2 = dict(name='古瑞替', age=10) user = dict(name='刘大力', mobile='13311234567', email='*****@*****.**', job=job, babies=[baby_1, baby_2], married=False, money=decimal.Decimal(321.1235678), status=-1, skills=['吐槽', '使劲吐槽', ''], emoji=[emoji_1, emoji_2]) schema = UserSchema() result = schema.dump(user) marshmallow.pprint(result, indent=4) return json(result)
def generate_transaction_for_user(user_email, amount): '''Generate transaction for given user''' amount = int(amount) user = mongo.db.users.find_one({'email': user_email}) if not user: raise BadParameter(f'User with email {user_email} not found') fake_transactions = [] for ind in range(amount): airports = fake.random_sample(AIRPORTS_CODES, 2) fake_transaction = { 'transactions_id': fake.numerify('########'), 'bonus_card_id': user['bonus_card_id'], 'bonus_miles': fake.pyint(min_value=0, max_value=100), 'flight_from': airports[0], 'flight_to': airports[1], 'flight_date': ma.utils.to_iso_date( fake.date_between(start_date='-10y', end_date='today')) } fake_transactions.append(fake_transaction) result = mongo.db.transactions.insert_many(fake_transactions, ordered=True) for ind, inserted_id in enumerate(result.inserted_ids): fake_transactions[ind]['_id'] = inserted_id ma.pprint(fake_transactions, indent=4)
def update(deploymentId, deployment): """ This function updates an existing deployment in the deployment list :param deploymentId: deploymentId of the deployment to update in the deployment list :param deployment: deployment to update :return: updated deployment """ pprint(deployment) # Does the deployment exist in deployments? existing_deployment = Deployments.query.filter( Deployments.deploymentId == deploymentId ).one_or_none() # Does deployment exist? if existing_deployment is not None: schema = DeploymentsSchema() update_deployment = schema.load(deployment, session=db.session) update_deployment.deploymentId = existing_deployment.deploymentId db.session.merge(update_deployment) db.session.commit() # return the updted deployment in the response data = schema.dump(update_deployment) return data, 200 # otherwise, nope, deployment doesn't exist, so that's an error else: abort(404, f"Deployment not found")
def post(self, id, accion): n = NotificacionTemplateModel.find_by_id(id) if not n: return {"message": "No se encontro la notificación"}, 404 response_envio = NotificacionTemplateModel.send_to_participantes(n) if response_envio["status"] == 404: return {"message": "No se pudo crear o enviar la notificacion."}, 404 if accion == 'ninguna': return {"message": "Notificacion reenviada con éxito.", "Número de destinatarios:": response_envio["total"]} elif accion == 'premio': p = PremioModel.find_by_id(n.link) if not p: return {"message": "No se encontro el premio"}, 404 response_envio = PremioModel.send_to_participantes(n) if response_envio["status"] == 404: return {"message": "No se pudo crear o enviar la notificacion."}, 404 return {"message": "Notificacion reenviada con éxito.", "Número de destinatarios:": response_envio["total"]} elif accion == 'encuesta': n = NotificacionTemplateModel.find_by_id(id) pprint(n) if not n: return {"message": "No se encontro la notificacion"}, 404 en = EncuestaModel.find_by_id(n.link) if not en: return {"message": "No se encontro la encuesta"}, 404 response_envio = EncuestaModel.send_to_participantes(n) if response_envio["status"] == 404: return {"message": "No se pudo crear o enviar la notificacion."}, 404 return {"message": "Notificacion reenviada con éxito.", "Número de destinatarios:": response_envio["total"]}
def patch(self, id): bir = BirthdayModel.find_by_id(id) pprint(bir) if not bir: return {"message": "No se encontró el premio de cumpleaños"}, 404 item_json = request.get_json() item = BirthdaySchema().load(item_json) try: if "id_notificacion" in item: bir.id_notificacion = item["id_notificacion"] if "id_promocion" in item: bir.id_promocion = item["id_promocion"] if "trigger" in item: bir.trigger = item["trigger"] if "antiguedad" in item: bir.antiguedad = item["antiguedad"] if "vigencia" in item: bir.vigencia = item["vigencia"] bir.fecha_creacion = item["fecha_creacion"] bir.save() except ValidationError as exc: print(exc.message) return { "message": "Error: No se pudo actualizar el premio de cumpleños" } return {'message': "Elemento actualizado", '_id': str(bir._id)}, 200
def test_dump(): try: schema = UserSchema() result = schema.dump(input_user_data) marshmallow.pprint(result) except marshmallow.ValidationError as err: marshmallow.pprint({'errors': err.messages})
def reinit_db(): print("Reinitializing database...") with db.app.app_context(): db_name = db.app.config["MONGODB_DB"] db.connection.drop_database(db_name) try: for schema, data_file in INIT_DATA: print(f"Parsing {data_file}") with open(path.join(BASE_DIR_DATA, data_file), "r", encoding="utf8") as file: docs = schema.loads(file.read(), many=True) for doc in docs: try: mod = schema.__model__(**doc) except Exception as e: print(f"Cannot instanciate {schema.__model__.__name__} from \n{schema.dumps(doc, indent=2)}\n") raise e if isinstance(schema, UserSchema): mod.set_password(mod.password) # hashing password mod.save() except HTTPException as e: print(e) pprint(e.data, indent=2) exit()
def test_portfolio_image_schema(): """ GIVEN a PostArgs Schema WHEN the Schema deserializes data THEN check that all fields are properly validated and data is deserialized as expected """ schema = PostArgs() data = { "title": "Generic Event 2020", "category": "portrait", "preview": {"uri": "data:image/jpeg;base64,iusertiusnritnseirtniudenrzidtnznerditznirdtnz", "alt": "Img Alt"}, "content": [ { "uri": "data:image/jpeg;base64,iusertiusnritnseirtniudenrzidtnznerditznirdtnz", "alt": "Interesting Preview" } ], "year": 2020, "client": "Pre Malone", "description": "Some random event info could be written here." } try: pprint(schema.load(data)) except ValidationError as err: pytest.fail(err.messages)
def test_load(): try: data = UserSchema().load(input_user_data) marshmallow.pprint(data) except marshmallow.ValidationError as err: marshmallow.pprint({'errors': err.messages}) return data
def GetBooking(request): print(current_user.get_id()) bookingdetails = Booking.query.filter_by(id=current_user.get_id()).first() schema = BookingSchema() pprint(schema.dump(bookingdetails).data) booking_details = schema.dump(bookingdetails).data if request == None: return booking_details return jsonify(booking_details)
def GetUser(request): print(current_user.get_id()) userdetails = User.query.filter_by(id=current_user.get_id()).first() schema = UserSchema() pprint(schema.dump(userdetails).data) user_details = schema.dump(userdetails).data if request == None: return user_details return jsonify(user_details)
def api_group(group_id): if request.method == 'GET': group = Group.query.get(group_id) return group_schema.dumps(group) elif request.method == 'PUT': group = group_schema.load(request.data) pprint(group) return "Sorry, this endpoint isn't finished yet"
def read_xml(): cool_xml = None with open("cool.xml", "r") as f: cool_xml = f.read() my_cool_dict = xmltodict.parse(cool_xml) marshmallow.pprint(my_cool_dict)
def api_user(user_id): if request.method == 'GET': user = User.query.get(user_id) return user_schema.dumps(user) elif request.method == 'PUT': user = user_schema.load(request.data) pprint(user) return "Sorry, this endpoint isn't finished yet"
def test_json(app, base_json, base_nresult): print("\n\n\n\n\n") print("START") print(app) print(current_jsonschemas.list_schemas()) base_json.update(base_nresult) pprint(base_json) _records_state.validate( base_json, "https://nusl.cz/schemas/nr_nresults/nr-nresults-v1.0.0.json")
def run_demo(): # OUTPUT SHOULD BE AS FOLLOWS: # { 'artist': {'name': 'David Bowie'}, # 'release_date': '1971-12-17', # 'title': 'Hunky Dory'} bowie = dict(name='David Bowie') album = dict(artist=bowie, title='Hunky Dory', release_date=date(1971, 12, 17)) schema = AlbumSchema() result = schema.dump(album) pprint(result.data, indent=2)
def post_delete(post_id): post = Post.query.get_or_404(post_id) if post.author != current_user: abort(404) db.session.delete(post) db.session.commit() schema = PostSchema() result = schema.dump(post) pprint({'Delete Success': result.data}) flash('Delete Successfully', 'success') return redirect(url_for('main.home'))
def deleteMenu(pk): menu=Menusection.query.filter_by(id=pk).first() pprint(menu) if menu is None: return {"message":"No record related to ID"} else: db.session.delete(menu) db.session.commit() return jsonify({'success':True})
def new_post(): form = NewPostForm() if form.validate_on_submit(): post = Post(title=form.title.data, content=form.content.data, author=current_user) db.session.add(post) db.session.commit() sechma = PostSchema() result = sechma.dump(post) pprint(result.data) return redirect(url_for('main.home')) return render_template('NewPost.html', title='New Post', form=form, legend='New Post')
def create_user(): data = request.json row = user(data[0], data[0], data[1], data[3], data[2]) db.session.add(row) try: db.session.commit() except IntegrityError: pprint("Error: Duplication of Primary Key") return "created"
def post(self): notificacion_json = request.get_json() # print(notificacion_json) n = not_schema_template.load(notificacion_json) pprint(n) # print("loaded") try: template = NotificacionTemplateModel() if "titulo" in n: template.titulo=n["titulo"] if "mensaje" in n: template.mensaje=n["mensaje"] if "imagenIcon" in n: template.imagenIcon=n["imagenIcon"] if "imagenDisplay" in n: template.imagenDisplay=n["imagenDisplay"] if "ImagenDisplay" in n: template.ImagenDisplay=n["ImagenDisplay"] if "bar_text" in n: template.bar_text=n["bar_text"] if "fecha" in n: template.fecha=n["fecha"] else: template.fecha=dt.datetime.now() if "tipo_notificacion" in n: template.tipo_notificacion=n["tipo_notificacion"] if "link" in n: template.link=n["link"] if "filtros" in n: template.filtros = n["filtros"] else: template.filtros = [] template.save() if "filtros" in n and n["filtros"] != []: filtersObids=[] for fil in n["filtros"]: filtersObids.append(ObjectId(fil)) # Enviar a todos los participantes for p in ParticipanteModel.objects.raw({"_id": { "$in": filtersObids}}): # part_id = ObjectId(id) notif = NotificacionModel( id_participante=p._id, id_notificacion=template._id, estado=0, # Estado puede servir para actualizar tambien OJO! ahora esta fijo, pero podrías ser variable ).save() # PYMODM no tiene soporte transaccional, en un futuro migrar a PYMONGO, que sí tiene soporte # return {"message": "Notificacion guardada con éxito."} except ValidationError as exc: print(exc.message) return {"message": "No se pudo crear o enviar la notificacion."}, 404 return {"message": "Notificacion guardada con éxito.", "id_notificacion": str(template._id), "Número de destinatarios:": len(template.filtros)}
def create_user(): data = request.json row = user(data[0],data[0],data[1],data[3],data[2]) db.session.add(row) try: db.session.commit() except IntegrityError: pprint("Error: Duplication of Primary Key") return "created"
def GetRestaurant(request): print(current_user.get_id()) restaurantdetails = Restaurant.query.filter_by( id=current_user.get_id()).first() schema = RestaurantSchema() pprint(schema.dump(restaurantdetails).data) restaurant_details = schema.dump(restaurantdetails).data if request == None: return restaurant_details return jsonify(restaurant_details)
def addNewMenu(): json_data= request.get_json(force=True) pprint(json_data) if not json_data: return {"message':'No input data provided"},400 menuSection_schema=MenusectionSchema() data= menuSection_schema.load(json_data).data if data['name'] is None: return {"message':'Needs menuSection name"},422 name=data['name'] menu=Menusection.query.filter_by(name=name).first() if menu is None: if data.get('Items') is None: menu=Menusection(name=name) db.session.add(menu) else: menu=Menusection(name=name) db.session.add(menu) for key in data['Items']: item=Sectionitems(name=key['name'],price=key['price']) if data['Items']['Options'] is None: db.session.add(item) menu.Items.append(item) else: db.session.add(item) menu.Items.append(item) for key in data['Items']['Options']: option=Itemoptions(name=key['name'],price=key['price']) if data['Items']['Options']['Choices'] is None: db.session.add(option) item.Options.append(option) else: db.session.add(option) item.Options.append(option) for key in data['Items']['Options']['Choices']: choice=Itemchoices(name=key['name'],price=key['price']) db.session.add(choice) option.Choices.append(choice) else: for key in data.get('Items'): item=Sectionitems(name=key['name'],price=key['price'],m_id=menu.id) db.session.add(item) db.session.commit() result=menuSection_schema.dump(Menusection.query.get(menu.id)) return jsonify({'success':True,'menusection':result})
def post(self, event_id): json_data = request.get_json() data = event_guest_schema.load(json_data) pprint(data) event_guest = EventGuest(event_id=event_id, **data.data) db.session.add(event_guest) try: db.session.commit() except: db.session.rollback() raise return event_guest_schema.dump(event_guest).data, 201
def delete(self, id, accion): if accion == 'ninguna': n = NotificacionTemplateModel.find_by_id(id) if not n: return {"message": "No se encontro la notificación"}, 404 try: for p in NotificacionModel.objects.raw({"id_notificacion": n._id}): p.delete() n.delete() except: return {"message": "No se pudo efectuar esta operación"},404 return {"message": "Notificacion eliminada"}, 200 elif accion == 'premio': n = NotificacionTemplateModel.find_by_id(id) pprint(n) if not n: return {"message": "No se encontro la notificacion"}, 404 if n.link != "null" and n.link: p = PremioModel.find_by_id(n.link) if not p: return {"message": "No se encontro el premio"}, 404 else: p = None try: for np in NotificacionModel.objects.raw({"id_notificacion": n._id}): np.delete() if n.link != "null" and n.link: for pp in PremioParticipanteModel.objects.raw({"id_premio": p._id}): pp.delete() p.delete() n.delete() except: return {"message": "No se pudo efectuar esta operación"},404 return {"message": "Notificación y premio eliminados"}, 200 elif accion == 'encuesta': n = NotificacionTemplateModel.find_by_id(id) pprint(n) if not n: return {"message": "No se encontro la notificacion"}, 404 en = EncuestaModel.find_by_id(n.link) if not en: return {"message": "No se encontro la encuesta"}, 404 try: for np in NotificacionModel.objects.raw({"id_notificacion": n._id}): np.delete() for ep in ParticipantesEncuestaModel.objects.raw({"id_encuesta": en._id}): ep.delete() n.delete() en.delete() except: return {"message": "No se pudo efectuar esta operación"},404 return {"message": "Notificación y encuesta eliminados"}, 200
def get_test_info(testid): conn = sqlite3.connect('cmpe273.db') c = conn.cursor() t = (testid, ) c.execute("SELECT * FROM tests WHERE id=?", t) test = c.fetchone() test_id = test[0] test_name = test[1] keys_str = test[2] # "A,B,C,D,E" test_ans_keys_json = dict(enumerate(keys_str.split(","), 1)) # res = getres(keys_str, test_id) cursor = c.execute( "SELECT scantron_id, scantron_url, student_name,subject,score,ques_answers FROM submissions WHERE test_id=?", t) names = list(map(lambda x: x[0], cursor.description)) # row = c.fetchone() # col = row.keys() rows = c.fetchall() submissions = [] print(names) print(rows) for x in range(len(rows)): temp = {} for y in range(len(rows[0])): if y == 5: print("I am here") temp["result"] = getres( dict(enumerate((rows[x][y].split(",")))), keys_str.split(",")) else: temp[names[y]] = rows[x][y] submissions.append(temp) pprint(submissions) conn.commit() conn.close() return { "test_id": test_id, "subject": test_name, "answer_keys": test_ans_keys_json, "submissions": submissions }, 200
def validate_payload(payload): global count db = client.expenses_db try: schema = ExpenseSchema() schema.load(payload) payload["is_validated"] = True db.expenses.insert_one(payload) count = count + 1 print("Total documents inserted: ", count) except ValidationError as ve: payload["errors"] = ve.messages pprint(ve) db.expenses_errors.insert_one(payload)
def post(self): json_data = request.get_json() data = user_schema.load(json_data) pprint(data) user = User(**data.data) user.password = bcrypt.hashpw(data.data['password'].encode('utf-8'), bcrypt.gensalt()) db.session.add(user) try: db.session.commit() except: db.session.rollback() raise return user_schema.dump(user).data, 201
from user import User from schema import UserSchema from marshmallow import pprint user = User(name='M K', email='*****@*****.**') schema = UserSchema() result = schema.dump(user) pprint(result.data) json_result = schema.dumps(user) pprint(json_result.data)
def pprint(self, obj, *args, **kwargs): """Pretty-printing helper that can handle `OrderedDict`s.""" ma.pprint(obj, *args, **kwargs)
self.name = name self.email = email self.created_at = dt.datetime.now() def __repr__(self): return '<User(name={self.name!r})>'.format(self=self) class UserSchema(Schema): name = fields.Str() email = fields.Email() created_at = fields.DateTime() if __name__ == '__main__': user = User(name='Kasheem', email='*****@*****.**') schema = UserSchema() # USAGE OF ONLY PARAMETER # summary_schema = UserSchema(only=('name', 'email')) result = schema.dump(user) pprint(result.data) # pprint(json_result.data) #COLLECTIONS user1 = User(name='Mick', email='*****@*****.**') user2 = User(name='Keith', email='*****@*****.**') users = [user1, user2] schema = UserSchema(many=True) result = schema.dump(users) pprint(result.data)
from datetime import date import pickle import sys from marshmallow import Schema, fields, pprint class ArtistSchema(Schema): name = fields.Str() release_date = fields.Date() number_of_times_sold = fields.Number() if __name__ == '__main__': schema = ArtistSchema() data = {'name': 'this is an artist', 'release_date': date(1970, 4, 2), 'number_of_times_sold': 4929492} data_str = str(data) result = schema.dump(data) pck_data = pickle.dumps(result.data) pprint(result.data, indent=2) print 'size of original data as dict: %s' % sys.getsizeof(data) print 'size of original data as string: %s' % sys.getsizeof(data_str) print 'size of data after marshalling: %s' % sys.getsizeof(result.data) print 'size of data after pickling: %s' % sys.getsizeof(pck_data) print 'size of entire marshalling result: %s' % sys.getsizeof(result) print '[x]: marshalled data:' print result.data print '[x]: pickled data:' print pck_data print '[x]: marshalled result:' print result
def test_nested_meta_many(self): serialized_blog = BlogUserMetaSerializer(self.blog) assert_equal(len(serialized_blog.data['collaborators']), 2) pprint(serialized_blog.data['collaborators'][0]) assert_equal(serialized_blog.data['collaborators'], [UserMetaSerializer(col).data for col in self.blog.collaborators])