def setUp(self):
        db.drop_all()
        db.create_all()
        self.client = app.test_client()
        user_1 = User.signup("user1",'*****@*****.**','password')
        user_2 = User.signup("user2",'*****@*****.**','password')
        user_3 = User.signup("user3",'*****@*****.**','password')

        db.session.add_all([user_1,user_2,user_3])
        db.session.commit()
        self.user_1 = user_1
        self.user_2 = user_2
        self.user_3 = user_3

        area_1 = Area(city="Irvine", state="CA")
        self.user_2.areas.append(area_1)
        db.session.commit()
        self.area_1 = area_1

        area_2 = Area(city="Irvine", state="CA")
        self.user_3.areas.append(area_2)
        db.session.commit()
        self.area_2 = area_2

        d = {"googlePlaceId":"ChIJ9f9zhYDb3IARfXSrxrDSdq4","name":"Lazy Dog Restaurant & Bar","address":"address"}
        rest_1 = Restaurant(name=d['name'],address=d['address'], google_place_id=d['googlePlaceId'],user_id=self.user_3.id, area_id=self.area_2.id)
        db.session.add(rest_1)
        db.session.commit()
        self.rest_1 = rest_1
        like = Likes(user_id=user_3.id, restaurant_id=rest_1.id)
        db.session.add(like)
        db.session.commit()
Exemple #2
0
def load_data_to_db(row):
    province_id = int(row['CH_ID'])
    province = Area.objects(aid=province_id).first()
    if not province:
        try:
            province = Area(level='ch',
                            th_name=row['CHANGWAT_T'].split()[-1],
                            en_name=row['CHANGWAT_E'],
                            aid=province_id)
            province.save()
        except ValidationError as e:
            print(row['CHANGWAT_T'], row['CHANGWAT_E'])

    amphoe_id = int(row['AM_ID'])
    amphoe = Area.objects(aid=amphoe_id).first()
    if not amphoe:
        try:
            amphoe = Area(level='am',
                          th_name=row['AMPHOE_T'].split()[1],
                          en_name=row['AMPHOE_E'],
                          aid=amphoe_id,
                          parent=province)
            amphoe.save()
        except ValidationError as e:
            print(row['AMPHOE_E'], row['AMPHOE_T'])

    tambon_id = int(row['TA_ID'])
    tambon = Area.objects(aid=tambon_id).first()
    if not tambon:
        try:
            tambon = Area(
                level='ta',
                th_name=row['TAMBON_T'].split()[1],
                aid=tambon_id,
                parent=amphoe,
                latlng=[float(row['LONG']),
                        float(row['LAT'])],
            )
            tambon.save()
        except ValidationError as e:
            print(row['TAMBON_E'], row['TAMBON_T'])
            sys.exit(1)
    else:
        # the tambon exists, do nothing.
        '''
        print('{}, {}, {} already in the database'.format(
            tambon.th_name.encode('utf8'),
            amphoe.th_name.encode('utf8'),
            province.th_name.encode('utf8')
        ))
        '''
        return

    amphoe.childs.append(tambon)
    amphoe.save()

    province.childs.append(amphoe)
    province.save()
def show_areas():
    '''Route to show a user's areas '''
    if not g.user:
        return redirect("/")

    user_areas = Area.query.filter(UserAreas.user_id == g.user.id).all()
    user = User.query.get_or_404(g.user.id)
    form = SearchForm()
    user_cities = [area.serialize() for area in user_areas]

    if form.validate_on_submit():
        city = form.city.data
        state = form.state.data
        formatted_city = city.title()

        for area in user_cities:
            if area['city'] == formatted_city and area['state'] == state:
                area_id = area['id']
                flash('You already added this area!', 'success')
                return redirect(f'/discover/restaurants/{area_id}')

        area = Area(city=formatted_city, state=state)
        g.user.areas.append(area)
        db.session.commit()
        return redirect(f'/discover/restaurants/{area.id}')
    return render_template('/areas/areas.html', form=form)
Exemple #4
0
def generate_random_data():
    from models import Area, User, Ticket, Note, TicketCloseReason
    import random
    import loremipsum

    db.drop_all()
    db.create_all()

    areas = [
        Area(name=u'CTO'),
        Area(name=u'Network'),
        Area(name=u'Infrastructure'),
        Area(name=u'Devops'),
        Area(name=u'Helpdesk'),
    ]
    db.session.add_all(areas)
    db.session.commit()

    users = [
        User(user='******', name=u'Bruno Bonagura', areas=areas, access_admin=True, access_reports=False),
    ]
    users[0].set_password('ax886dds')
    db.session.add_all(users)
    
    reasons = [
        TicketCloseReason(reason=u'Solved'),
        TicketCloseReason(reason=u'False Alarm'),
        TicketCloseReason(reason=u'Network failure'),
        TicketCloseReason(reason=u'Misconfiguration'),
        TicketCloseReason(reason=u'Remission')
    ]
    db.session.add_all(reasons)
    db.session.commit()

    random.seed('oi')
    for i in range(1, 100):
        t = Ticket(
            title = unicode(loremipsum.get_sentence()),
            text = unicode(loremipsum.get_paragraph()),
            current_area = random.choice(areas),
            created_at = datetime.now() - timedelta(random.randint(1,100)),
            created_by = random.choice(users),
        )
        t.add_note(random.choice(users), unicode(loremipsum.get_sentence()))
        db.session.add(t)
    db.session.commit()
Exemple #5
0
def area_create():
    if not flask_login.current_user.is_admin:
        abort(403)

    obj = Area()
    for k, v in request.json.iteritems():
        setattr(obj, k, v)

    db.session.add(obj)
    db.session.commit()

    return jsonify({'id': obj.id})
def venues():
  unique_locations = []
  areas = []

  for venue in Venue.query.all():
    if [venue.city, venue.state] not in unique_locations:
      unique_locations.append([venue.city, venue.state])
      venuesInLoc = Venue.query.filter_by(city=venue.city).filter_by(state=venue.state)
      vnShort = []
      for vn in venuesInLoc:
        vnShort.append(InfoShort(vn.id, vn.name, vn.upcoming_shows_count))
      areas.append(Area(venue.city, venue.state, vnShort))

  return render_template('pages/venues.html', areas=areas)
    def setUp(self):
        db.drop_all()
        db.create_all()
        self.client = app.test_client()
        user_1 = User.signup("user1", '*****@*****.**', 'password')
        user_2 = User.signup("user2", '*****@*****.**', 'password')
        user_3 = User.signup("user3", '*****@*****.**', 'password')

        db.session.add_all([user_1, user_2, user_3])
        db.session.commit()
        self.user_1 = user_1
        self.user_2 = user_2
        self.user_3 = user_3

        area_test = Area(city="Irvine", state="CA")
        self.user_1.areas.append(area_test)
        db.session.commit()
        self.area_test = area_test
Exemple #8
0
def get_area_id(city, state):
    """Gets the area id of an area from a city and state.

    Args:
        city: A str representing the city of an area object
        state: A str representing the state of an area object

    Returns:
        area_id: An int representing the id of the area object cooresponding
            to a city and state
    """
    area = Area.query.filter(Area.city == city, Area.state == state).first()

    if not area:
        area = Area(city=city, state=state)
        db.session.add(area)
        db.session.flush()

    return area.id
Exemple #9
0
def getcoords(deviceName):
    if not session.get('loggedIn'):
        return redirect(url_for('login'))
    else:
        currentUser = User.query.get(session['currentUserId'])
        devices = currentUser.device
        content = request.form
        coordinatesString = ''
        for items in content:
            coordinatesString = items
        for device in devices:
            if device.name == deviceName:
                newArea = Area(coordinatesString)
                try:
                    db.session.add(newArea)
                    userDevice = Device.query.filter_by(
                        name=deviceName).first()
                    userDevice.area.append(newArea)
                    db.session.commit()
                except:
                    db.session.rollback()
                    flash(u'Błąd bazy danych!')
        flash(u'Ustawiono nowy obszar dla urzadzenia ' + deviceName)
        return 'OK'
def add_entry():
    connect(host='mongodb://*****:*****@ds255539.mlab.com:55539/9321test')
    parser = reqparse.RequestParser()
    parser.add_argument('name', type=str, help='LGA name input error')
    parser.add_argument('postcode', type=int, help='Postcode input error')
    args = parser.parse_args()
    postcode = args.get("postcode")#check postcode to find the LGA name
    ############################# postcode ######################################
    if postcode:
        name_list = []
        for k, v in postdic.items():
            for s in v:
                if s == postcode:
                    name_list.append(k) #regions founded

        if name_list == []: #check whether the input postcode in the postdic
            return jsonify(Input_postcode=False),404

        feed = AtomFeed(title='Multi-collections POST complete', feed_url=request.url)
        for a in Area.objects:
            for n in name_list:
                if a.name.lower().replace(' ', '') == n.lower().replace(' ', ''):
                    name_list.remove(n)
        for n in name_list:
            name = n
            url = 'http://127.0.0.1:5000' + url_for('show_entry', name=name)

            # download from the internet -- check 400 - if 2 not in 1 -- not up-to-date
            dld_url = 'http://www.bocsar.nsw.gov.au/Documents/RCS-Annual/'+name+'lga.xlsx'
            r = requests.get(dld_url)
            with open(name + 'lga.xlsx','wb') as f:
                f.write(r.content)

            excel_url = name + 'lga.xlsx'
            data = xlrd.open_workbook(excel_url).sheets()[0]
            id = 0  # initialisation id for embeded document
            p = []  # used to collect Offense()
            for row in range(7, 69):  # for further update
                id = id + 1
                offence_group = str(data.cell(row, 0).value)
                if offence_group != '':
                    backup = offence_group
                if offence_group == '':
                    offence_group = backup
                offence_type = str(data.cell(row, 1).value)
                incidents_2012 = str(data.cell(row, 2).value)
                rate_2012 = str(data.cell(row, 3).value)
                incidents_2013 = str(data.cell(row, 4).value)
                rate_2013 = str(data.cell(row, 5).value)
                incidents_2014 = str(data.cell(row, 6).value)
                rate_2014 = str(data.cell(row, 7).value)
                incidents_2015 = str(data.cell(row, 8).value)
                rate_2015 = str(data.cell(row, 9).value)
                incidents_2016 = str(data.cell(row, 10).value)
                rate_2016 = str(data.cell(row, 11).value)
                trend_24m = str(data.cell(row, 12).value)
                trend_60m = str(data.cell(row, 13).value)
                lga_rank = str(data.cell(row, 14).value)
                p.append(Offense(id, offence_group, offence_type, incidents_2012, rate_2012, incidents_2013, rate_2013, \
                                 incidents_2014, rate_2014, incidents_2015, rate_2015, incidents_2016, \
                                 rate_2016, trend_24m, trend_60m, lga_rank))
            t = Area(name, p)
            t.save()
            entry = FeedEntry(title=name, url=url, updated=datetime.datetime.utcnow(), author={'name': 'admin'})
            feed.add(entry)

        response = make_response(feed.to_string())
        response.mimetype = "application/atom+xml"

    ############################# name ######################################
    else: #if postcode not given, check the name field
        name = args.get("name").lower().replace(' ', '')
        if not name:
            return jsonify(Input=False), 404
        url = 'http://127.0.0.1:5000' + url_for('show_entry', name=name)

        #if LGA or postcode that already has been imported before
        for a in Area.objects:
            if a.name.lower().replace(' ', '') == name.lower().replace(' ', ''):
                feed = AtomFeed(title='Already existed', feed_url=url)
                entry = FeedEntry(title=name, url=url, updated=datetime.datetime.utcnow(),
                                author={'name': 'admin'})
                feed.add(entry)
                response = make_response(feed.to_string())
                response.mimetype = "application/atom+xml"
                return response, 200

        #download from the internet -- check 400 - if 2 not in 1 -- not up-to-date
        dld_url = 'http://www.bocsar.nsw.gov.au/Documents/RCS-Annual/'+name+'lga.xlsx'
        r = requests.get(dld_url)
        with open(name + 'lga.xlsx','wb') as f:
           f.write(r.content)

        excel_url = name + 'lga.xlsx'
        data = xlrd.open_workbook(excel_url).sheets()[0]
        id = 0 #initialisation id for embeded document
        p = [] #used to collect Offense()
        for row in range(7, 69): #for further update
            id = id+1
            offence_group = str(data.cell(row, 0).value)
            if offence_group != '':
                backup = offence_group
            if offence_group == '':
                offence_group = backup
            offence_type = str(data.cell(row, 1).value)
            incidents_2012 = str(data.cell(row, 2).value)
            rate_2012 = str(data.cell(row, 3).value)
            incidents_2013 = str(data.cell(row, 4).value)
            rate_2013 = str(data.cell(row, 5).value)
            incidents_2014 = str(data.cell(row, 6).value)
            rate_2014 = str(data.cell(row, 7).value)
            incidents_2015 = str(data.cell(row, 8).value)
            rate_2015 = str(data.cell(row, 9).value)
            incidents_2016 = str(data.cell(row, 10).value)
            rate_2016 = str(data.cell(row, 11).value)
            trend_24m = str(data.cell(row, 12).value)
            trend_60m = str(data.cell(row, 13).value)
            lga_rank = str(data.cell(row, 14).value)
            p.append(Offense(id, offence_group, offence_type, incidents_2012, rate_2012, incidents_2013, rate_2013, \
                            incidents_2014, rate_2014, incidents_2015, rate_2015, incidents_2016, \
                            rate_2016, trend_24m, trend_60m, lga_rank))
        t = Area(name,p)
        t.save()

        feed = AtomFeed(title='Sucess POST Activity', feed_url=url)
        entry = FeedEntry(title=name, url=url, updated=datetime.datetime.utcnow(), author={'name': 'admin'})
        feed.add(entry)
        response = make_response(feed.to_string())
        response.mimetype = "application/atom+xml"

    return response, 201
Exemple #11
0
def get_all_areas():
    return [Area(a) for a in backend.data.areas.find()]
 def test_area_model(self):
     area = Area(city="Los Angeles", state="CA")
     db.session.add(area)
     db.session.commit()
     check_area = Area.query.get(area.id)
     self.assertIsNotNone(check_area)
Exemple #13
0
async def addA():
    a1 = Area(name='电子科技大学(沙河校区)', parid='xxx')
    a2 = Area(name='电子科技大学(清水河校区)', parid='xxx')
    await a1.save()
    await a2.save()
    return a1, a2