def insert_test_data():
    all_objects = []
    with open('test_data/volunteers.json', encoding='utf8') as volunteers_file:
        volunteers_data = json.load(volunteers_file)
        volunteers = [
            Volunteer(id=int(id_), name=vol['name'], userpic=vol['userpic'], phone=vol['phone'])
            for id_, vol in volunteers_data.items()
        ]
    all_objects.extend(volunteers)

    with open('test_data/streets.json', encoding='utf8') as streets_file:
        streets_data = json.load(streets_file)
        streets = [
            Street(id=int(id_), title=st['title'], volunteers=list(filter(lambda x: x.id in st['volunteer'], volunteers)))
            for id_, st in streets_data.items()
        ]
    all_objects.extend(streets)

    with open('test_data/districts.json', encoding='utf8') as districts_file:
        districts_data = json.load(districts_file)
        districts = [
            District(id=int(id_), title=ds['title'], streets=list(filter(lambda x: x.id in ds['streets'], streets)))
            for id_, ds in districts_data.items()
        ]
    all_objects.extend(districts)

    db.session.add_all(all_objects)
    db.session.commit()
	def POST(self):

		web.header('Access-Control-Allow-Origin',      '*')
		web.header('Access-Control-Allow-Credentials', 'true')

		volunteerItem = simplejson.loads(web.data())

		existingVolunteer = Volunteer.GetByEmail(volunteerItem['volunteer_email'])

		if (existingVolunteer):
			return "{ status: 'Error - Volunteer Exists'}"

		else:              # not existing, create new database record
			newVolunteer = Volunteer( 
					volunteer_name = volunteerItem['volunteer_name'],
					volunteer_email = volunteerItem['volunteer_email'],
					volunteer_phone = volunteerItem['volunteer_phone'],
					address_street = volunteerItem['address_street'],
					address_street2 = volunteerItem['address_street2'],
					address_city = volunteerItem['address_city'],
					address_state = volunteerItem['address_state'],
					address_zipcode = volunteerItem['address_zipcode']
   								)	
			newVolunteer.put()

		return "{ status: 'Success'}"
Пример #3
0
 def post(self, post_code):
     v = simple_validate({'post_code': post_code})
     if v['valid']:
         f = VolunteerForm(self.request.POST)
         if f.validate():
             new_v = Volunteer(
                 first_name=f.first_name.data,
                 last_name=f.last_name.data,
                 phone=f.phone.data,
                 email=f.email.data,
                 project=f.project.data,
                 sitelocation=f.sitelocation.data,
                 notes=f.notes.data,
                 cos=f.cos.data,
                 trainee_input="",
             )
             new_v.put()
             new_kit = MedKit(
                 date_issued=datetime.now(),
                 in_use=True,
                 delivery_events=[],
                 volunteer=new_v,
                 post_default=v["post_default"],
             )
             new_kit.put()
             v['Volunteer'] = new_v
             v['MedKit'] = new_kit
             html = render.page(self,
                                "templates/postadmin/confirmation.html", v)
             self.response.out.write(html)
         else:
             self.response.out.write(
                 "invalid entry for one of the form items")
     else:
         render.not_found(self)
Пример #4
0
    def add_volunteer_submission():
        # adds a new volunteer with data from volunteer_form and redirects to
        # the dashboard
        form = VolunteerForm()
        if not form.validate_on_submit():
            # if the form has errors, display error messages and resend the
            # current page
            flash('Task could not be created because one or more data fields'
                  ' were invalid:')
            for field, message in form.errors.items():
                flash(message[0])
            return render_template('volunteer_form.html',
                                   form=form,
                                   title="Add a New Volunteer")

        # the form is valid
        name = request.form['name']
        address = request.form['address']
        city = request.form['city']
        state = request.form['state']
        zip_code = request.form['zip_code']
        phone_number = request.form['phone_number']

        new_volunteer = Volunteer(name, address, city, state, zip_code,
                                  phone_number)
        try:
            new_volunteer.insert()
            flash('Volunteer ' + name + ' was successfully added')
        except Exception as e:
            flash('An error occurred.  The Volunteer could not be added')
            abort(422)

        return redirect('/dashboard')
Пример #5
0
    def create_volunteer():
        # creates a new volunteer and returns it to the api
        body = request.get_json()
        if not body:
            abort(400)

        name = body.get('name', None)
        address = body.get('address', None)
        city = body.get('city', None)
        state = body.get('state', None)
        zip_code = body.get('zip_code', None)
        phone_number = body.get('phone_number', None)

        # all fields are required
        if name and address and city and state and zip_code and phone_number:
            try:
                new_volunteer = Volunteer(name, address, city, state, zip_code,
                                          phone_number)
                new_volunteer.insert()
                return {'success': True, 'volunteer': new_volunteer.format()}
            except Exception:
                abort(422)
        else:
            # request did not contain one or more required fields
            abort(400)
Пример #6
0
def add_volunteer():
    email = request.form.get('email')
    volunteer = Volunteer(email)
    DB.session.add(volunteer)
    DB.session.commit()

    flash('Successfully added volunteer', 'success')
    return redirect(url_for('volunteer-list'))
Пример #7
0
def create_volunteer(userN,passW,zip,types,phoneN,address_):
	try:
		user = Volunteer(username=userN,password=passW,zipCode=zip,phone_number=phoneN,typesPref=types,address=address_)
		db.session.add(user)
		db.session.commit()
		db.session.remove()
		return {"Success":"Signup was Successful"}
	except:
		return {"Failure": "Signup Failed"}
Пример #8
0
def post_volunteer(payload):
    try:
        body = request.get_json()
        name = body['name']
        email = body['email']
        phone = body['phone']
    except Exception as e:
        print(e)
        abort(400)

    try:
        volunteer = Volunteer(name=name, email=email, phone=phone)
        db.session.add(volunteer)
        db.session.commit()
        return jsonify({'success': True, 'volunteer': volunteer.format()})
    except Exception as e:
        db.session.rollback()
        abort(422)
    finally:
        db.session.close()
Пример #9
0
def register_volunteer():
    try:
        body = request.get_json()
        volunteer = Volunteer(name=body['name'],
                              age=util.compute_int(body['age']),
                              gender=body.get('gender', 'NA'),
                              email=body['email'],
                              image_link=body.get('image_link', ''),
                              profile_link=util.compute_profile_link(),
                              seeking_student=util.compute_boolean(
                                  body['seeking_student']),
                              seeking_description=body['seeking_description'])

        volunteer.insert()

        return jsonify({"success": True}), 200

    except GenericException as e:
        raise e

    except Exception:
        raise APIException("Bad Request", 400)
Пример #10
0
    def create_volunteer(*args, **kwargs):
        """Creates a Volunteer.

        Returns:
            response: json, status_code
        """
        try:
            body = request.get_json()
            volunteer = Volunteer(
                name=body.get('name'),
                phone_number=body.get('phone_number'),
                email=body.get('email'),
                event=body.get('event'),
            )
            volunteer.insert()
            return jsonify({
                'success': True,
                'volunteers': volunteer.format()
            }), 201
        except Exception as e:
            app.logger.error(e)
            abort(422)
def parseFile(json_url, begin, end, args):
    resp = requests.get(url=json_url)
    data = resp.json()

    cols = max([int(i['gs$cell']['col']) for i in data['feed']['entry']])
    rows = max([int(i['gs$cell']['row']) for i in data['feed']['entry']])
    df = [['' for i in range(cols)] for j in range(rows)]
    for i in data['feed']['entry']:
        col = int(i['gs$cell']['col'])
        row = int(i['gs$cell']['row'])
        #print(i['gs$cell'])
        df[row - 1][col - 1] = i['gs$cell']['inputValue']

    lb = [df[1][i] if df[0][i] == '' else df[0][i] for i in range(cols)]
    lb = [i[:15] for i in lb]

    rr = [{lb[i]: v for i, v in enumerate(j)} for j in df[2:]]
    ids = []
    begin = int(begin)
    end = int(end)
    for row in rr[begin:end]:  #add
        item = parseRow(row)
        #if args.get('legitimatie') is not None and item['received_contract']:
        item['is_active'] = True
        ob = Volunteer.objects(phone=item['phone']).first()
        if not ob:
            comment = Volunteer(**item)
            comment.save()
            ids.append(comment.clean_data()['_id'])
            #return jsonify(comment.clean_data()['_id'])
        elif 'latitude' in item:
            data = ob.clean_data()
            if 'latitude' not in data or data['latitude'] == '':
                ob.update(latitude=item['latitude'],
                          longitude=item['longitude'],
                          address=item['address'])

    return jsonify(ids)
def register_volunteer(request_json, created_by):
    """Creates and persists a new volunteer into database.

    Parameters
    ----------
    request_json : dict
        A dictionary representing the volunteer profile details.
    created_by : str
         A string representing either name of user who is going to create a new volunteer, or the token

    Returns
    -------
    200:
        If the volunteer was successful created and saved.
    400:
        If the volunteer wasn't created or saved, and there was raised some exception.
    """
    log.debug("Relay offer for req:%s from ", request_json) 
    try:
        if not vu.is_email(created_by):
            user = Operator.verify_auth_token(created_by)
            created_by = user.get().clean_data()['email']

        if created_by == os.getenv("COVID_BACKEND_USER"):
            vu.exists_by_telegram_chat_id(request_json["chat_id"])
            new_volunteer_data = process_volunteer_data_from_telegram(request_json)
        else:
            vu.exists_by_email(request_json["email"])
            new_volunteer_data = request_json

        new_volunteer_data["password"] = PassHash.hash(new_volunteer_data["password"])
        new_volunteer_data['created_by'] = created_by
        new_volunteer = Volunteer(**new_volunteer_data)
        new_volunteer.save()
        return jsonify({"response": "success", 'user': new_volunteer.clean_data()})
    except Exception as error:
        return jsonify({"error": str(error)}), 400
Пример #13
0
artist = Artist(name="Justin Beiberlake",
                phone_number='555-555-5556',
                email='*****@*****.**',
                event=1,
                website='https://www.youtube.com/watch?v=dQw4w9WgXcQ',
                instagram_link='https://www.facebook.com/joeexotic',
                image_link="https://images.unsplash.com/photo-14")

artist2 = Artist(name="Gnarfunkel",
                 phone_number='555-555-5557',
                 email='*****@*****.**',
                 event=1,
                 website='https://www.youtube.com/watch?v=dQw4w9WgXcQ',
                 instagram_link='https://www.facebook.com/joeexotic',
                 image_link="https://images.unsplash.com/photo-15")

volunteer = Volunteer(name="Tyler",
                      phone_number='555-555-5558',
                      email='*****@*****.**',
                      event=1)

volunteer2 = Volunteer(name="Annie",
                       phone_number='555-555-5559',
                       email='*****@*****.**',
                       event=1)

add_list = [volunteer, volunteer2, artist, artist2]
[db.session.add(item) for item in add_list]
db.session.commit()
db.session.close()