def add(): form = forms.FeatureForm() if form.validate_on_submit(): try: print(form.target_date.data) models.Feature.create( user = g.user._get_current_object(), title =form.title.data, description = form.description.data, client = form.client.data, client_priority= form.priority.data, target_date = form.target_date.data, ticket_url = form.ticket_url.data, product_area = form.product_area.data, percent_complete = form.percent_complete.data ) except IntegrityError: print('You are seeing an IntegrityError') #see if the prioirty is the problem num = int(form.priority.data) cust_name = form.client.data #get problem record records = models.Feature.select().where(models.Feature.client== cust_name) #need to update the records for priorities greater than number for record in records: print(record.client_priority, type(record.client_priority)) if record.client_priority >= num: with DATABASE.transaction(): record.client_priority += 1 record.save() print('record saved') print('The new priority is ', record.client_priority) with DATABASE.transaction(): models.Feature.create( user = g.user._get_current_object(), title =form.title.data, description = form.description.data, client = form.client.data, client_priority= str(num), target_date = form.target_date.data, ticket_url = form.ticket_url.data, product_area = form.product_area.data, percent_complete = form.percent_complete.data ) return render_template('add.html', form=form) return render_template('add.html', form=form)
def sync(self, client=conn, resource=s3, dist="", bucket=os.environ['BUCKET_NAME'], token=''): count = 0 existing_items = 0 new_items = 0 paginator = client.get_paginator('list_objects') for result in paginator.paginate(Bucket=bucket, PaginationConfig={ 'PageSize': 500, 'StartingToken': token }): keys = [] for s3_object in result.get('Contents'): count += 1 if count % 1000 == 0: print(count) s3_key = s3_object['Key'] keys.append(s3_key) with db.atomic(): (existing, new) = build_directory_tree(keys) existing_items += existing new_items += new self.update_state(state='PROGRESS', meta={ 'existingObjects': existing_items, 'newObjects': new_items, 'total': count }) self.update_state(state='SUCCESS', meta={ 'existingObjects': existing_items, 'newObjects': new_items, 'total': count })
def to_database(available_files): with DATABASE.atomic(): for idx in range(0, len(available_files), 100): try: GetStarted.insert_many(available_files[idx:idx+100]).execute() except IntegrityError: # print(available_files[idx]) pass
def register(): """User register route""" payload = request.get_json() print(payload) payload['email'] = payload['email'].lower() payload['username'] = payload['username'].lower() try: # encrypting password before creating it payload['password'] = generate_password_hash(payload['password']) with DATABASE.atomic(): # creating new user new_user = models.User.create(username=payload['username'], email=payload['email'], password=payload['password']) login_user(new_user) new_user_dict = model_to_dict(new_user) new_user_dict.pop('password') return jsonify( data=new_user_dict, message='Sucessfully created new user with username: {}'.format( new_user_dict['username']), status=200), 200 except IntegrityError as e: print('ERROR ARGUMENTS') print(e.args[0]) # using the peewee.integrity error to check if the email/username is taken if e.args[0] == 'UNIQUE constraint failed: user.email': return jsonify( data={}, message='There is already a user registered with that email.', status=401), 401 elif e.args[0] == 'UNIQUE constraint failed: user.username': return jsonify( data={}, message= 'There is already a user registered with that username.', status=401), 401 else: print('ERROR') return e
def image_markers(image_id, stack_id, project_id): with DATABASE.transaction(): project_stack = models.ProjectStack.get(models.ProjectStack.project == project_id, models.ProjectStack.stack == stack_id) stack_image = models.StackImage.get(models.StackImage.stack == stack_id, models.StackImage.image == image_id) user = models.AppUser.get(models.AppUser.id == g.user_id) markers = (Marker.select().where( Marker.app_user == g.user_id, Marker.stack_image == stack_image.id, Marker.project_stack == project_stack.id) ) return jsonify({ 'markers': [marker.serialized for marker in markers] })
def get(self): args = request.headers.get('userInfo') aws_keys = json.loads(args) instances = get_instances(aws_keys['aws_access_key_id'], aws_keys['aws_secret_access_key']) for i in instances: instance_id = i.get('instance_id') availability_zone = i.get('availability_zone') instance_state = i.get('instance_state') try: with DATABASE.atomic(): Instance.create(instance_id=instance_id) except IntegrityError: pass return jsonify({"data": instances})
def update_project(project_id): new_project = request.get_json() try: project = Project.get(Project.id == project_id) except models.DoesNotExist: return jsonify({ 'message': 'Project not found' }), 400 if new_project['id'] != project.id: return jsonify({ 'message': 'Cannot update project at this url' }), 400 try: if new_project['markerOptions']: marker_options = new_project['markerOptions'] for marker_name in marker_options: try: marker_option = MarkerOption.get(MarkerOption.name == marker_name) ProjectMarkerOption.get(ProjectMarkerOption.project == project.id, ProjectMarkerOption.marker_option == marker_option.id) except models.DoesNotExist: ProjectMarkerOption.create(project = project, marker_option = marker_option) if new_project['users']: users = new_project['users'] for user in users: try: project_user = ProjectUser.get(ProjectUser.app_user == user['id'], ProjectUser.project == project) except models.DoesNotExist: ProjectUser.create(app_user = user['id'], project = project) if new_project['stacks']: stacks = new_project['stacks'] with db.atomic(): for stack in stacks: try: project_stack = ProjectStack.get(ProjectStack.stack == stack['id'], ProjectStack.project == project) except models.DoesNotExist: project_stack = ProjectStack.create(project=project, stack = stack['id']) probe_setting = stack['probeSettings'] probe_position = json.loads(probe_setting['position']) ProbeSetting.create(x_offset=int(probe_position['xOffset']), y_offset=int(probe_position['yOffset']), project_stack=project_stack, label=probe_position['label'] ) message = "Project updated" except Exception as ex: print ex project = Project.get(Project.id == project_id) return jsonify({ 'message': 'Project updated', 'project': project.deep_serialized() }), 200
def setUp(self): """Define test variables and initialize app.""" self.app = create_app() self.client = self.app.test_client self.todo = {'name': 'Get a new haircut'} #import pdb; #pdb.set_trace() # binds the app to the current context with self.app.app_context(): # create all tables DATABASE.connect(reuse_if_open=True) DATABASE.create_tables([Todo], safe=True) DATABASE.close()
def after_request(response): DATABASE.close() return response
def before_request(): g.db = DATABASE.connect()
def save_image_markers(): try: with DATABASE.transaction(): request_obj = request.get_json() images = (request_obj['images']) stack_id = request_obj['stackId'] project_id = request_obj['projectId'] no_markers_placed = request_obj['noMarkersPlaced'] project_stack = models.ProjectStack.get( models.ProjectStack.project == project_id, models.ProjectStack.stack == stack_id ) saved_marker_count = 0 try: old_top_of_stack = ProjectStackDatum.get( ProjectStackDatum.data_type == "top image", ProjectStackDatum.user == g.user_id, ProjectStackDatum.project_stack == project_stack.id ) old_top_of_stack.delete_instance() except ProjectStackDatum.DoesNotExist: pass no_marker_stack_data = ProjectStackDatum.select().where( ProjectStackDatum.data_type == "project stack marker", ProjectStackDatum.value == "no markers placed", ProjectStackDatum.user == g.user_id, ProjectStackDatum.project_stack == project_stack.id ) for datum in no_marker_stack_data: datum.delete_instance() if no_markers_placed: try: ProjectStackDatum.create( data_type = "project stack marker", value = "no markers placed", user = g.user_id, project_stack = project_stack.id ) except Exception: return jsonify({ 'message': 'Saving markers failed' }), 500 for index, image in enumerate(images): stack_image = models.StackImage.get( models.StackImage.stack == stack_id, models.StackImage.image == image['id'] ) try: if image['isTopOfStack']: ProjectStackDatum.create( data_type = "top image", value = str(index), # "top image" property is zero-indexed user = g.user_id, project_stack = project_stack.id ) except KeyError: # this will hit if image is not top of probe, which is nbd pass except Exception: return jsonify({ 'message': 'Saving markers failed' }), 500 old_markers = (models.Marker.select().where( models.Marker.app_user == g.user_id, models.Marker.stack_image == stack_image.id, models.Marker.project_stack == project_stack.id) ) for marker in old_markers: marker.delete_instance() try: for marker in image['markers']: mark = models.Marker.create( image = image, app_user = g.user_id, stack_image = stack_image, project_stack = project_stack, marker_type = marker['markerType'], x_percent = marker['xPercent'], y_percent = marker['yPercent'] ) saved_marker_count += 1 if marker['markerType'] == 'neuron': mark.x_crosshair_percent = marker['xLengthPercent'] mark.y_crosshair_percent = marker['yHeightPercent'] mark.save() except KeyError: pass return jsonify({ 'message': '{0} markers saved'.format(saved_marker_count) }) except ValueError: return jsonify({ 'message': 'Saving markers failed.' })
def create_app(): #app.run(debug=config.DEBUG, host=config.HOST, port=config.PORT) DATABASE.connect(reuse_if_open=True) DATABASE.create_tables([Todo], safe=True) DATABASE.close() return app
def tearDown(self): """teardown all initialized variables.""" with self.app.app_context(): # drop all tables DATABASE.close()