Beispiel #1
0
def plan(request, location):
    context_dict ={}
     # A HTTP POST?
    if request.method == 'POST':
        form = MyForm(request.POST)
        planner = Planner.objects.get(user=request.user)
        tripForm = CreateTrip(request.POST)

        # Have we been provided with a valid form?
        if form.is_valid() and tripForm.is_valid():
            # Save the new category to the database.
            trip = tripForm.save(commit=False)
            trip.planner=planner #Planner will be sent automatically eventually
            trip.save()
            data = form.cleaned_data['places']
            for place in data:
                visit = Visit(trip=trip, place=place)
                visit.save()
            # The user will be shown the summary page.
            return redirect(reverse('tripSummary', args=[trip.id] ))
        else:
            # The supplied form contained errors - just print them to the terminal.
            print form.errors
            context_dict['errors'] = form.errors
    else:
        places = get_places(location)
        form = CreateTrip()
        # If the request was not a POST, display the form to enter details.
        context_dict['places'] = places
        context_dict['tripForm'] = form

    return render(request, 'plan.html', context_dict)
Beispiel #2
0
    def get(self, request, ip, *args, **kw):
        print "Requested IP: {}".format(ip)
        details_request = IPDetails(ip, *args, **kw)

        # Track API usage
        alien_vault_id = request.COOKIES.get(COOKIE_NAME, None)
        if alien_vault_id is None:
            user = User()
        else:
            try:
                user = User.objects.get(alien_vault_id=alien_vault_id)
            except User.DoesNotExist:
                user = User()
        user.save()

        visit = Visit(
            user=user,
            address=request.META.get('REMOTE_ADDR'),  # TODO: Handle X-Forwarded-For
            endpoint='api/threat/ip/{}'.format(ip)
        )
        visit.save()

        result = DetailsSerializer(details_request)
        response = Response(result.data, status=status.HTTP_200_OK)

        response.set_cookie(
            COOKIE_NAME,
            user.alien_vault_id,
            max_age=COOKIE_MAX_AGE
        )

        return response
Beispiel #3
0
def production_seen(request, play_id, play, production_id, type):
    production = check_parameters(play_id, play, production_id)
    if type == 'add':
        alert = Visit(user=request.user, production=production)
        try:
            alert.save()
        except IntegrityError, e:
            if e.args[0] != 1062: # Duplicate
                raise
        messages.success(request, u"Your visit has been recorded.")
Beispiel #4
0
def visit(db):
    authorize()

    customer_id = post_get('customer_id')
    visit = Visit()
    visit.setStatus(status='checkin', family_id=customer_id)
    db.add(visit)
    db.commit()

    checkout_url = get_redirect_url('checkin')
    return bottle.redirect(checkout_url)
Beispiel #5
0
def visit(db):
    authorize()

    customer_id = post_get('customer_id')
    visit = Visit()
    visit.setStatus(status='checkin', family_id=customer_id)
    db.add(visit)
    db.commit()

    checkout_url = get_redirect_url('checkin')
    return bottle.redirect(checkout_url)
Beispiel #6
0
    def get_visits(self, uid=None, page_size=100, offset=0):
        params = {'offset': offset, 'limit': page_size}
        visits = Visit.select().paginate((offset % page_size) + 1, page_size)

        if uid:
            params.update({'uid': uid})
            visits = (Visit.select(Visit, User.nickname).where(
                Visit.uid == uid).join(User).group_by(Visit).paginate(
                    (offset % page_size) + 1, page_size))
        else:
            visits = (Visit.select(
                Visit, User.nickname).join(User).group_by(Visit).paginate(
                    (offset % page_size) + 1, page_size))

        raise gen.Return(visits)
Beispiel #7
0
def logbud():
    form = VisitorSignInForm()

    # TODO:
    # implement
    if request.method == 'POST':
        if form.validate_on_submit():
            firstname = form.firstname.data.lower()
            lastname = form.lastname.data.lower()
            visiting = form.visiting.data.lower()
            purpose = form.purpose.data.lower()

            # Check if visitor is new
            returning_visitor = Visitor.query.filter_by(
                firstname=firstname, lastname=lastname).first()
            if not returning_visitor:
                new_visitor = Visitor(firstname=firstname, lastname=lastname)
                db.session.add(new_visitor)
                db.session.commit()

                new_visitor = Visitor.query.filter_by(
                    firstname=firstname, lastname=lastname).first()

                new_visit = Visit(visitor_id=new_visitor.id,
                                  visiting=visiting,
                                  purpose=purpose)
                db.session.add(new_visit)
                db.session.commit()

                return redirect('/log')

            # Returning visitor should not have active visit
            for visit in returning_visitor.visits:
                if visit.is_active():
                    flash('Visitor is already logged in!')
                    return redirect('/log/' + str(returning_visitor.id))

            # Log visitor
            new_visit = Visit(visitor_id=returning_visitor.id,
                              visiting=visiting,
                              purpose=purpose)
            db.session.add(new_visit)
            db.session.commit()
            return redirect('/log')

        flash("Form errors!")

    return render_template('logbud.html', form=form)
Beispiel #8
0
def update_stalls_from_raw():
    required = ['raw_data']
    if not request.json:
        abort(400, 'request must be in application/json format')
    if any(x not in request.json for x in required):
        abort(400, 'request must contain %s' % (', '.join(required),))
    message_str = base64.b64decode(request.json['raw_data'])
    message_bytes = bytearray()
    message_bytes.extend(message_str)
    sender, status = sender_and_status(message_bytes)
    address = struct.unpack('>I', sender[4:])[0]
    # We're using pull up resistors on the XBee's
    status = not status

    session = db.session()
    stall = session.query(Stall).filter_by(address=address).first()
    if not stall:
        abort(400, 'no stall found')
    if stall.status and not status:
        stall.status = False
        visit = stall.visits.order_by(Visit.id.desc()).first()
        visit.exited_at = datetime.datetime.now()
        session.commit()
    elif not stall.status and status:
        session.add(Visit(stall_id=stall.id))
        stall.status = True
        session.commit()
    return jsonify({'success': True}), 201
Beispiel #9
0
def signup_visit():
    request_body = request.get_json()
    print(request_body)

    visit1 = Visit(
        temperature=request_body["temperature"],
        business_id=get_jwt_identity(),
        visitor_id=request_body["visitor_id"],
        entry_date=datetime.strptime(request_body["entry_date"],
                                     "%a, %d %b %Y %H:%M:%S %Z"),
        has_fever=request_body["has_fever"],
        has_covid=request_body["has_covid"],
    )
    db.session.add(visit1)
    db.session.commit()
    return jsonify(visit1.serialize()), 200
Beispiel #10
0
    def get(self, request, *args, **kwargs):
        ip = kwargs['ip']

        # User's source address
        x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR')
        if x_forwarded_for:
            user_addr = x_forwarded_for.split(',')[0]
        else:
            user_addr = request.META.get('REMOTE_ADDR')

        # Generate IPDetails object for serialization
        details_request = IPDetails(ip, *args, **kwargs)

        # Serialize object
        result = DetailsSerializer(details_request)

        response = Response(result.data, status=status.HTTP_200_OK)

        # Set UTC time
        current_datetime = datetime.utcnow()
        epoch = int((current_datetime - datetime(1970, 1, 1)).total_seconds())
        expires = addYear(current_datetime, 1)

        # Handle Cookies
        if 'alienvaultid' in request.COOKIES:
            avid = request.COOKIES['alienvaultid']

            response.set_cookie('last_visit', epoch, expires=expires)

        else:
            # Didn't find cookie, set one.
            avid = ''.join(
                ["%s" % random.randint(0, 9) for num in range(0, 11)])
            response.set_cookie('alienvaultid', avid, expires=expires)
            response.set_cookie('last_visit', epoch, expires=expires)

        user = User(alienvaultid=avid)
        user.save()

        visit = Visit(user=user,
                      address=user_addr,
                      timestamp=epoch,
                      endpoint=kwargs['endpoint'] + ip)
        visit.save()

        return response
Beispiel #11
0
    def get(self, request, *args, **kwargs):
        ip = kwargs['ip']

        # User's source address
        x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR')
        if x_forwarded_for:
            user_addr = x_forwarded_for.split(',')[0]
        else:
            user_addr = request.META.get('REMOTE_ADDR')

        # Generate IPDetails object for serialization
        details_request = IPDetails(ip, *args, **kwargs)

        # Serialize object
        result = DetailsSerializer(details_request)

        response = Response(result.data, status=status.HTTP_200_OK)

        # Set UTC time
        current_datetime = datetime.utcnow()
        epoch            = int((current_datetime - datetime(1970, 1, 1)).total_seconds())
        expires          = addYear(current_datetime, 1)

        # Handle Cookies
        if 'alienvaultid' in request.COOKIES:
            avid = request.COOKIES['alienvaultid']

            response.set_cookie('last_visit', epoch, expires=expires)

        else:
            # Didn't find cookie, set one.
            avid = ''.join(["%s" % random.randint(0, 9)
                           for num in range(0, 11)])
            response.set_cookie('alienvaultid', avid, expires=expires)
            response.set_cookie('last_visit', epoch, expires=expires)

        user = User(alienvaultid=avid)
        user.save()

        visit = Visit(user=user,
                      address=user_addr,
                      timestamp=epoch,
                      endpoint=kwargs['endpoint'] + ip)
        visit.save()

        return response
Beispiel #12
0
    def create(self, request, **kwargs):
        serializer = RectSerializer(data=request.data, many=True)
        if serializer.is_valid():
            serializer.save()

            # We receive a list of Rects with the same picture, so we just
            # take the picture from the first Rect.
            picture_obj = serializer.validated_data[0]['picture']
            image = picture_obj.picture

            # Create the Recognizer and pass all available faces
            recognizer = VisitorRecognizer(VisitorFaceSample.objects.all())
            recognizer.train_model()

            # Build an URL where the clients can download the image
            picture_url = request.build_absolute_uri(image.url)
            response_dict = {"visitors": [], "people": 0, "picture_url": picture_url}

            # Create a new visit
            visit = Visit(picture=picture_obj)
            visit.save()

            # Try to recognize people in the incoming picture
            visitors, faces = recognizer.recognize_visitor(image)

            # Add the recognized visitors to the Visit and to the JSON response
            for visitor_id, confidence in visitors:
                visitor = Visitor.objects.get(pk=visitor_id)
                visit.visitors.add(visitor)

                visitor_dict = {"name": visitor.name, "confidence": confidence}
                response_dict["visitors"].append(visitor_dict)

            # Save and send the number of people in the visit
            response_dict["people"] = visit.people = faces
            visit.save()

            # Pack the data (url and visitor data) in json
            json_response = json.dumps(response_dict)

            # Send the data to the xmpp server where the devices are listening
            xmppconnector.connect_and_send(json_response)

        # Return an empty response since we don't need to inform anything
        return Response()
Beispiel #13
0
def follow(request, token):
  logger.debug('Follow: %s' % token)

  try:
    link = Link.objects.get(token=token)
  except Link.DoesNotExist:
    raise Http404()

  ip = request.META.get('REMOTE_ADDR')
  referer = request.META.get('HTTP_REFERER')

  visit = Visit(link=link, ip=ip, referer=referer)
  visit.save()

  link.visits = F('visits') + 1
  link.save()

  return HttpResponsePermanentRedirect(link.url)
Beispiel #14
0
def count():
    
    v = Visit.query.first()
    if not v:
        v = Visit()
        v.count += 1
        db.session.add(v)
    v.count +=1
    db.session.commit()
    return jsonify(counter=v.count)
Beispiel #15
0
def index():
    app.logger.info("Rendering homepage from flask server")
    counter = 0
    v = Visit.query.first()

    #If very first visist, create the first entry into DB,
    #which would be subsequently used by all clients
    if not v:
        v = Visit()
        db.session.add(v)
        db.session.commit()
    return render_template('index.html', counter=v.count)
Beispiel #16
0
def counter():
    visit = session.query(Visit).filter(Visit.visit_id == 1).with_for_update(
        nowait=False, of=Visit).first()
    if visit is None:
        visit = Visit(visit_id=1, counter=1)
        session.add(visit)
        session.commit()
        return str(visit.counter)
    else:
        visit.counter += 1
        session.commit()
        return str(visit.counter)
Beispiel #17
0
def append():
    try:
        payload = json.loads(request.data.decode('utf-8'))
    except json.JSONDecodeError:
        return abort(400)

    for v in payload:
        visit = Visit(url=v['url'],
                      time=datetime.strptime(v['timestamp'],
                                             "%Y-%m-%dT%H:%M:%S.%fZ"),
                      raw_dom=v['html'])
        db_session.add(visit)
    db_session.commit()
    print("Logged %i urls" % len(payload))
    return "OK"
Beispiel #18
0
def profile(username):
    profile_user = User.get_user(username)

    if not profile_user:
        abort(404)

    if g.user and g.user.username != profile_user.username:
        visit = Visit(profile_user.id, g.user.id)
        db.session.merge(visit)
        db.session.commit()

    return render_template('profile.html',
                           profile_user=profile_user,
                           questions=QUESTIONS,
                           comment_form=CommentForm())
Beispiel #19
0
def new_journal_from_search(username, park_code):
    """Show form for adding a new journal with park already chosen (GET) or add journal to db and go to user page (POST)"""
    # Check if logged in user is this user
    if is_correct_user(username):
        form = NewJournalForm()

        # Get park_code and name from db table for select field in form
        park = Park.query.get_or_404(park_code)
        form.park_name.choices = [(park_code, park.park_name)]

        if form.validate_on_submit():
            date_added = datetime.now()
            date_of_visit = form.date_of_visit.data
            user_id = user_id
            title = form.title.data
            text = form.text.data
            park_code = form.park_name.data
            title_img_url = form.title_img_url.data

            journal = Journal(date_added=date_added,
                              date_of_visit=date_of_visit,
                              user_id=user_id,
                              title=title,
                              text=text,
                              park_code=park_code,
                              title_img_url=title_img_url)

            db.session.add(journal)
            db.session.commit()

            visit = Visit(date_of_visit=date_of_visit,
                          user_id=user_id,
                          park_code=park_code,
                          journal_id=journal.id)
            db.session.add(visit)
            db.session.commit()

            flash("Journal successfully created")
            # on successful creation, redirect to users page
            return redirect(f"/users/{ user.username }")

        return render_template("new_journal.html", form=form)

    flash("Not your dashboard")
    return redirect("/")
Beispiel #20
0
    def create(self, request, **kwargs):
        serializer = RectSerializer(data=request.data, many=True)
        if serializer.is_valid():
            serializer.save()

            # We receive a list of Rects with the same picture, so we just
            # take the picture from the first Rect.
            picture_obj = serializer.validated_data[0]['picture']
            image = picture_obj.picture

            # Create the Recognizer and pass all available faces
            recognizer = VisitorRecognizer(VisitorFaceSample.objects.all())
            recognizer.train_model()

            # Build an URL where the clients can download the image
            picture_url = request.build_absolute_uri(image.url)
            response_dict = {
                "visitors": [],
                "people": 0,
                "picture_url": picture_url
            }

            # Create a new visit
            visit = Visit(picture=picture_obj)
            visit.save()

            # Try to recognize people in the incoming picture
            visitors, faces = recognizer.recognize_visitor(image)

            # Add the recognized visitors to the Visit and to the JSON response
            for visitor_id, confidence in visitors:
                visitor = Visitor.objects.get(pk=visitor_id)
                visit.visitors.add(visitor)

                visitor_dict = {"name": visitor.name, "confidence": confidence}
                response_dict["visitors"].append(visitor_dict)

            # Save and send the number of people in the visit
            response_dict["people"] = visit.people = faces
            visit.save()

            # Pack the data (url and visitor data) in json
            json_response = json.dumps(response_dict)

            # Send the data to the xmpp server where the devices are listening
            xmppconnector.connect_and_send(json_response)

        # Return an empty response since we don't need to inform anything
        return Response()
Beispiel #21
0
def update_stalls():
    data = request.get_data(as_text=True)
    required = ['secret', 'stall_id', 'status']
    if not request.json:
        abort(400, 'request must be in application/json format')
    if any(x not in request.json for x in required):
        abort(400, 'request must contain %s' % (', '.join(required),))
    if request.json['secret'] != SECRET:
        abort(400, 'secret is incorrect')

    session = db.session()
    stall = session.query(Stall).get(request.json['stall_id'])
    if not stall:
        abort(400, 'no stall found')
    if stall.status and not request.json['status']:
        stall.visits.order_by(Visit.id.desc()).first().exited_at = datetime.datetime.now()
        stall.status = request.json['status']
        session.commit()
    elif not stall.status and request.json['status']:
        session.add(Visit(stall_id=stall.id))
        stall.status = request.json['status']
        session.commit()
    return jsonify({'success': True}), 201
Beispiel #22
0
 def get_visits_total(self, uid=None):
     if uid:
         results_count = Visit.select().where(Visit.uid == uid).count()
     else:
         results_count = Visit.select().count()
     raise gen.Return(results_count)
Beispiel #23
0
def customer(db, customer_id=None):
    authorize()

    bottle.BaseTemplate.defaults['page'] = '/customer'

    postData = bottle.request.POST
    form = CustomerForm(postData)
    post_url = get_redirect_url()
    visit_url_root = get_redirect_url('checkout')
    volunteer_url_root = get_redirect_url('volunteer_visit')
    checkin_url = get_redirect_url('checkin')
    visits = None
    volunteerVisits = None
    failedValidation = False

    if bottle.request.method == 'POST':
        family = None
        try:
            if form.validate():
                family = CustomerFamily()
                family.fromForm(customer_id, form)
                family = db.merge(family)

                db.flush()

                activeVisits = family.visits.filter(Visit.checkout == None)  # noqa
                hasNoActiveVisit = len(activeVisits.all()) == 0
                shouldCreateVisit = postData["checkinCust"] == "true"
                shouldCheckinVolunteer = postData["checkinVolunteer"] == "true"
                isCustomer = "isCustomer" in postData
                isVolunteer = "isVolunteer" in postData

                if hasNoActiveVisit and shouldCreateVisit and isCustomer:
                    visit = Visit()
                    visit.setStatus(status='checkin', family_id=family.id)
                    db.add(visit)
                next_url = get_redirect_url('checkin')

                db.commit()

                if shouldCheckinVolunteer:
                    next_url = get_redirect_url('volunteer_visit?family_id='+str(family.id))
                elif isVolunteer:
                    next_url = get_redirect_url('customer/'+str(family.id))
                return bottle.redirect(next_url)
            else:
                failedValidation = True
        except HTTPError as herr:
            raise herr
        except HTTPResponse as hres:
            raise hres
        except Exception as ex:
            log.debug(ex)
            db.rollback()
            visits = family.visits
            volunteerVisits = family.volunteerVisits

    if customer_id is not None and \
       (failedValidation or bottle.request.method == 'GET'):
        customerQuery = db.query(CustomerFamily)
        fams = customerQuery.filter(CustomerFamily.id == customer_id)

        famCount = len(fams.all())
        if famCount == 0:
            return "No customers were found with this id"
        elif famCount > 1:
            return "There were multiple customers with the same id"

        if not failedValidation:
            form = CustomerForm(obj=fams[0])
        visits = fams[0].visits
        volunteerVisits = fams[0].volunteerVisits
    elif bottle.request.method == 'GET':
        # Mark one of the two dependents as primary
        form.dependents[0].isPrimary.data = True

    customerDict = {}
    customerDict['form'] = form
    customerDict['customer_id'] = customer_id
    customerDict['visits'] = visits
    customerDict['volunteers'] = volunteerVisits
    customerDict['post_url'] = post_url
    customerDict['checkin_url'] = checkin_url
    customerDict['visit_url_root'] = visit_url_root
    customerDict['volunteer_url_root'] = volunteer_url_root

    return template('customer', **customerDict)
Beispiel #24
0
 def logout_pred(self, **kwargs):
     self.users.logout()
     q = Visit.all()
     for r in q:
         r.delete()
     self.redirect('/')
Beispiel #25
0
 def g(*args, **kwargs):
     self = args[0]
     invalid_cookie = False
     self.request.charset = None
     if "sse_pos_session_key" not in self.request.cookies:
         curr_session = Visit(expired=False, session="{}")
         curr_session.expired = False
         curr_session.session = "{}"
         curr_session.put()
         invalid_cookie = True
     else:
         curr_session = Visit.get(Key(encoded=str(self.request.cookies["sse_pos_session_key"])))
         if not curr_session or curr_session.expired:
             curr_session = Visit(expired=False, session="{}")
             curr_session.expired = False
             curr_session.session = "{}"
             curr_session.put()
             invalid_cookie = True
     sess = eval(curr_session.session)
     self.session = sess
     self.real_session = curr_session
     ret_val = f(*args, **kwargs)
     curr_session.session = repr(sess)
     curr_session.put()
     if invalid_cookie:
         self.response.headers[
             "Set-Cookie"
         ] = "sse_pos_session_key=%s; expires=Thu, 22-May-2014 17:36:31 GMT; Path=/;" % str(curr_session.key())
     return ret_val
Beispiel #26
0
def customer(db, customer_id=None):
    authorize()

    bottle.BaseTemplate.defaults['page'] = '/customer'
    
    relationshipOpts = [relationship.__dict__ for relationship in db.query(Relationship)
                        .order_by(Relationship.id).all()]

    postData = bottle.request.POST
    form = CustomerForm(postData)
    post_url = get_redirect_url()
    visit_url_root = get_redirect_url('checkout')
    volunteer_url_root = get_redirect_url('volunteer_visit')
    checkin_url = get_redirect_url('checkin')
    visits = None
    volunteerVisits = None
    failedValidation = False

    if bottle.request.method == 'POST':
        family = None
        try:
            if form.validate():
                family = CustomerFamily()
                family.fromForm(customer_id, form)
                family = db.merge(family)

                db.flush()

                activeVisits = family.visits.filter(Visit.checkout == None)  # noqa
                hasNoActiveVisit = len(activeVisits.all()) == 0
                shouldCreateVisit = postData["checkinCust"] == "true"
                shouldCheckinVolunteer = postData["checkinVolunteer"] == "true"
                isCustomer = "isCustomer" in postData
                isVolunteer = "isVolunteer" in postData

                if hasNoActiveVisit and shouldCreateVisit and isCustomer:
                    visit = Visit()
                    visit.setStatus(status='checkin', family_id=family.id)
                    db.add(visit)
                next_url = get_redirect_url('checkin')

                db.commit()

                if shouldCheckinVolunteer:
                    next_url = get_redirect_url('volunteer_visit?family_id='+str(family.id))
                elif isVolunteer:
                    next_url = get_redirect_url('customer/'+str(family.id))
                return bottle.redirect(next_url)
            else:
                failedValidation = True
        except HTTPError as herr:
            raise herr
        except HTTPResponse as hres:
            raise hres
        except Exception as ex:
            log.debug(ex)
            db.rollback()
            if family is not None:
                visits = family.visits
                volunteerVisits = family.volunteerVisits

    if customer_id is not None and \
       (failedValidation or bottle.request.method == 'GET'):
        customerQuery = db.query(CustomerFamily)
        fams = customerQuery.filter(CustomerFamily.id == customer_id)

        famCount = len(fams.all())
        if famCount == 0:
            return "No customers were found with this id"
        elif famCount > 1:
            return "There were multiple customers with the same id"

        if not failedValidation:
            form = CustomerForm(obj=fams[0])
        visits = fams[0].visits\
            .order_by(models.Visit.checkin)
        volunteerVisits = fams[0].volunteerVisits\
            .order_by(models.VolunteerVisit.checkin)
    elif bottle.request.method == 'GET':
        # Mark one of the two dependents as primary
        form.dependents[0].isPrimary.data = True

    customerDict = {}
    customerDict['form'] = form
    customerDict['customer_id'] = customer_id
    customerDict['visits'] = visits
    customerDict['volunteers'] = volunteerVisits
    customerDict['relationshipOpts'] = relationshipOpts
    customerDict['post_url'] = post_url
    customerDict['checkin_url'] = checkin_url
    customerDict['visit_url_root'] = visit_url_root
    customerDict['volunteer_url_root'] = volunteer_url_root

    return template('customer', **customerDict)
Beispiel #27
0
def screen():

    print("from screen")
    print(request.method)

    if request.method == 'POST':

        name_of_test = request.form['name_of_test']
        if name_of_test not in [
                'fsmc', 'hads', 'memory_test', 'sf-36', '25_foot', '9_hpt',
                'pasat_3', 'neurostatus_scoring'
        ]:
            print('error')

        print("Here")

        birth_day = int(request.form['birth_day'])
        birth_month = int(request.form['birth_month'])
        birth_year = int(request.form['birth_year'])

        birth_date = datetime(birth_year, birth_month, birth_day)
        print(birth_date)

        patient = Patient.query.filter_by(fname=request.form['fname'].lower(),
                                          sname=request.form['sname'].lower(),
                                          lname=request.form['lname'].lower(),
                                          birth_date=birth_date).first()

        if not patient:

            patient = Patient(
                fname=request.form['fname'].lower(),
                sname=request.form['sname'].lower(),
                lname=request.form['lname'].lower(),
                birth_date=birth_date,
                sex=True if request.form['sex'] == "male" else False,
            )

            db.session.add(patient)
            db.session.commit()
            print("Patient Created")
        else:
            print("Patient Existed")

        doctor = Doctor.query.filter_by(
            fname=request.form['spec_fname'].lower(),
            sname=request.form['spec_sname'].lower(),
            lname=request.form['spec_lname'].lower(),
            clinic=request.form['clinic'].lower()).first()

        if not doctor:

            doctor = Doctor(fname=request.form['spec_fname'].lower(),
                            sname=request.form['spec_sname'].lower(),
                            lname=request.form['spec_lname'].lower(),
                            clinic=request.form['clinic'].lower())

            db.session.add(doctor)
            db.session.commit()
            print("Doctor Created")
        else:
            print("Doctor Existed")

        visit_day = int(request.form['visit_day'])
        visit_month = int(request.form['visit_month'])
        visit_year = int(request.form['visit_year'])

        visit_date = datetime(visit_year, visit_month, visit_day)
        print(visit_date)

        visit = Visit.query.filter_by(patient_id=patient.id,
                                      doctor_id=doctor.id,
                                      visit_date=visit_date).first()

        if not visit:

            visit = Visit(patient_id=patient.id,
                          doctor_id=doctor.id,
                          visit_date=visit_date)

            db.session.add(visit)
            db.session.commit()
            print("Visit Created")
        else:
            print("Visit Existed")

        screen_name = '_'.join([str(visit.id), name_of_test]) + '.png'
        screen_name = os.path.join(UPLOAD_FOLDER, screen_name)

        screenshot = request.form['screen'].split(',')[1]
        screenshot = base64.b64decode(screenshot)

        with open(screen_name, 'wb') as file:
            file.write(screenshot)

        print(name_of_test)

        test_summary = None
        if name_of_test == 'neurostatus_scoring':

            test_summary = EDSS(
                visit_id=visit.id,
                screenshot_path=screen_name,
                visual=float(request.form['visual']),
                brainstem=float(request.form['brainstem']),
                pyramidal=float(request.form['pyramidal']),
                cerebellar=float(request.form['cerebellar']),
                sensory=float(request.form['sensory']),
                bowel_bladder=float(request.form['bowel_bladder']),
                cerebral=float(request.form['cerebral']),
                ambulation_score=float(request.form['ambulation_score']),
                edss_step=float(request.form['edss_step']),
            )

        if name_of_test == 'fsmc':

            test_summary = FSMC(visit_id=visit.id,
                                screenshot_path=screen_name,
                                kog=int(request.form['kog']),
                                mot=int(request.form['mot']),
                                total=int(request.form['total']))

        if name_of_test == '25_foot':

            test_summary = Foot25(
                visit_id=visit.id,
                screenshot_path=screen_name,
                foot25_try1=float(request.form['foot25_try1']),
                foot25_try2=float(request.form['foot25_try2']),
                foot25_tools=request.form['foot25_tools'],
                foot25_addition=request.form['foot25_addition'])

        if name_of_test == 'hads':

            test_summary = HADS(visit_id=visit.id,
                                screenshot_path=screen_name,
                                anxiety=int(request.form['hads_anx']),
                                depression=int(request.form['hads_dep']))

        if name_of_test == 'memory_test':

            test_summary = MemoryTest(
                visit_id=visit.id,
                screenshot_path=screen_name,
                memtest_all=int(request.form['memtest_all']),
                memtest_correct=int(request.form['memtest_correct']),
                memtest_wrong=int(request.form['memtest_wrong']))

        if name_of_test == 'sf-36':

            test_summary = SF36(visit_id=visit.id,
                                screenshot_path=screen_name,
                                PHC=float(request.form['PHC']),
                                MHC=float(request.form['MHC']))

        if name_of_test == 'pasat_3':

            test_summary = PASAT3(visit_id=visit.id,
                                  screenshot_path=screen_name,
                                  form_type=request.form['pasat_form_type'],
                                  correct=int(request.form['pasat_correct']),
                                  procent=float(request.form['pasat_procent']))

        if name_of_test == '9_hpt':

            test_summary = HPT9(
                visit_id=visit.id,
                screenshot_path=screen_name,
                main_hand=request.form['hpt9_hand'],
                attempt_main_hand_1=float(request.form['hpt9_main_hand_1']),
                attempt_main_hand_2=float(request.form['hpt9_main_hand_2']),
                note_main=request.form['hpt9_note_main'],
                attempt_sec_hand_1=float(request.form['hpt9_sec_hand_1']),
                attempt_sec_hand_2=float(request.form['hpt9_sec_hand_1']),
                note_sec=request.form['hpt9_note_sec'])

        try:
            assert test_summary
            db.session.add(test_summary)
            db.session.commit()
        except AssertionError:
            print('No information about test results')

        print(test_summary)

    return redirect(url_for('index'))