def process_record_locations(locData, recObj): locations = [] for loc in locData: if loc['id'] == -1: location = models.Location(name=loc['value']) db.session.add(location) db.session.commit() elif loc['id'] == 0: continue else: location = models.Location.query.get(loc['id']) locations.append(location) clny_state = models.LocationType.query.filter_by( name='Colony/State').first() city = models.LocationType.query.filter_by(name='City').first() locale = models.LocationType.query.filter_by(name='Locale').first() loc_types = [clny_state, city, locale] for loc in locations: rec_loc = models.ReferenceLocation() rec_loc.reference = recObj rec_loc.location = loc idx = locations.index(loc) rec_loc.location_rank = idx if idx < len(loc_types): rec_loc.location_type = loc_types[idx] db.session.add(rec_loc) db.session.commit() return recObj
def add_location(): """ Receive location name and description from form Add to database Redirect to location listings page :return: add locations page for GET requests """ form = AddForm() if request.method == "POST" and form.validate_on_submit(): location = models.Location(name=form.name.data, description=form.description.data) # Handle cases when a location's name already exists try: models.db.session.add(location) models.db.session.commit() flash("Location added successfully", "success") return redirect(url_for("locations")) except sa.exc.IntegrityError: flash("Location name exists", "danger") page_title = "DuFarms - Add Location" form_type = "Location" return render_template("add.html", page_title=page_title, form=form, form_type=form_type)
def save_location(user, latitude, longitude): """ 保存用户地理位置 """ location = models.Location(user=user, latitude=latitude, longitude=longitude) db.session.add(location) db.session.commit()
def setUp(self): app.config.from_object(config.TestConfig) self.app = app.test_client() with app.app_context(): models.db.init_app(app) models.db.create_all() location = models.Location(name="Abroad", description="Not a warehouse") models.db.session.add(location) models.db.session.commit()
def addLocation(name, address): newLocation = models.Location(name=name, address=address) db.session.add(newLocation) for location in models.Location.query.all(): if location.name == name and location.address == address: return False else: return True
def test_location(test_db, test_case): """ Have to use test_db here because the PostGIS.Geometry base coordinates property does not change from a text based representation to an actual PostGIS.Geometry until it is saved to a database. """ location = models.Location(coordinates=test_case['coordinates']) test_db.session.add(location) test_db.session.commit() assert location.latitude == test_case['latitude'] assert location.longitude == test_case['longitude'] assert str(location) == test_case['str_val']
def test_location(self): l = models.Location(city='New York City', region='New York State', country='United States') db.session.add(l) db.session.commit() locations = models.Location.query.all() self.assertEqual(len(locations), 1) self.assertEqual(locations[0].city, 'New York City') self.assertEqual(locations[0].region, 'New York State') self.assertEqual(locations[0].country, 'United States')
def set_up(): app.config.from_object(config.DevConfig) with app.app_context(): models.db.init_app(app) models.db.create_all() # Initialize the database with the location Abroad try: location = models.Location(name="Abroad", description="Not a warehouse") models.db.session.add(location) models.db.session.commit() except sa.exc.IntegrityError: pass app.run()
def load_location(): # open file as an object loc_file = open('data/location.txt') # split based on space or tab into a reader object containing lists of strings for each row loc_obj = csv.reader(loc_file, delimiter="|") # pull each row and assign and store based on data labels for row in loc_obj: store_content = models.Location(id=row[0], lat=row[1], lng=row[2], rad=row[3], n_hood=row[4]) # adds the content to the db db_session db.session.add(store_content)
def test_user(self): l = models.Location(city='New York City', region='New York State', country='United States') db.session.add(l) db.session.commit() u = models.User(username='******', password='******', location_id=l.id) db.session.add(u) db.session.commit() users = models.User.query.all() self.assertEqual(len(users), 1) self.assertEqual(users[0].username, 'test') self.assertEqual(users[0].location_id, l.id)
def create_locations(): locations = [] json = request.get_json() if json is None: return jsonify({ '404' : 'Unable to parse JSON. Did you specify a content type of \'application/json\'?' }) trip_id = None try: trip_id = json['trip_id'] except KeyError: return jsonify({ '404' : 'Must provide a Trip ID' }) trip = models.Trip.query.filter(models.Trip.trip_id == trip_id).first() if trip is None: return jsonify({ '404' : 'Invalid Trip ID' }) locs = None try: locs = json['locations'] except KeyError: return jsonify({ '404' : 'Must provide locations' }) grouping_id = str(uuid.uuid4()) for loc in locs: try: stamp = None try: stamp = datetime.strptime(loc['timestamp'], '%b %d %Y %I:%M:%S%p') except ValueError: return jsonify({ '404' : 'Invalid time format' }) l = models.Location(x = loc['x'], y = loc['y'], timestamp = stamp, grouping_id = grouping_id, location_technology = loc['location_technology'], trip = trip, route = trip.route) db.session.add(l) locations.append(l) except KeyError: return jsonify({ '404' : 'You must provide a timestamp and an x and y value for all locations' }) db.session.commit() for l in locations: l.location_id = str(l.id) # the object's ID isn't set until it is added to the DB db.session.add(l) db.session.commit() return jsonify({ 'locations' : [l.serialize() for l in locations] }), 200
def addLocation(): form = addLocationForm(request.form) if request.method == "POST" and form.validate_on_submit(): flash("Location added!") name = form.name.data addr = form.addr.data max_capacity = form.max_capacity.data longt = float(form.longt.data) latt = float(form.latt.data) l = models.Location(name=name, bike_amount=0, max_capacity=max_capacity, addr=addr, longt=longt, latt=latt) db.session.add(l) db.session.commit() return render_template('newLocation.html', form=form, topname=session["name"])
def signup(): form_sign_up = SignInForm() if current_user.is_authenticated: return redirect('/') if utils.find_user_by_username(form_sign_up.username.data): flash('That username is taken, please try again.') return render_template('signup.html', title='Sign Up', form=form_sign_up) if form_sign_up.password.data != form_sign_up.password2.data: flash("Your passwords didn't match, please try again.") return render_template('signup.html', title='Sign Up', form=form_sign_up) if form_sign_up.validate_on_submit( ) and form_sign_up.password.data == form_sign_up.password2.data: db.create_all() loc = models.Location.query.filter_by( city=form_sign_up.city.data, region=form_sign_up.region.data).first() if not loc: loc = models.Location(city=form_sign_up.city.data, region=form_sign_up.region.data, country='placeholder') db.session.add(loc) db.session.commit() user = models.User(username=form_sign_up.username.data, location_id=loc.id) user.set_password(form_sign_up.password.data) db.session.add(user) db.session.commit() return redirect('/login/') return render_template('signup.html', title='Sign Up', form=form_sign_up)
def test_friends(self): l = models.Location(city='New York City', region='New York State', country='United States') db.session.add(l) db.session.commit() u1 = models.User(username='******', password='******', location_id=l.id) db.session.add(u1) db.session.commit() u2 = models.User(username='******', password='******', location_id=l.id) db.session.add(u2) db.session.commit() friendship = models.Friends(friend1_id=u1.id, friend2_id=u2.id) db.session.add(friendship) db.session.commit() friendships = models.Friends.query.all() self.assertEqual(len(friendships), 1) self.assertEqual(friendships[0].friend1_id, u1.id) self.assertEqual(friendships[0].friend2_id, u2.id)
def test_user_restaurant(self): l = models.Location(city='New York City', region='New York State', country='United States') db.session.add(l) db.session.commit() u = models.User(username='******', password='******', location_id=l.id) db.session.add(u) db.session.commit() r = models.Restaurant(name='test') db.session.add(r) db.session.commit() user_restaurant = models.UserRestaurant(user_id=u.id, restaurant_id=r.id) db.session.add(user_restaurant) db.session.commit() user_restaurants = models.UserRestaurant.query.all() self.assertEqual(len(user_restaurants), 1) self.assertEqual(user_restaurants[0].user_id, u.id) self.assertEqual(user_restaurants[0].restaurant_id, r.id)
import os from app import db, models import datetime # Delete database file if it exists currently if os.path.exists('app.db'): os.remove('app.db') db.create_all() l1 = models.Location(name='University', address='Roger Stevens') b1 = models.Bike(current_location=1) l2 = models.Location(name='City', address='Headrow') b2 = models.Bike(current_location=2) l3 = models.Location(name='Headingley', address='Otley Road') b3 = models.Bike(current_location=3) b4 = models.Bike(current_location=1) b5 = models.Bike(current_location=1) b6 = models.Bike(current_location=2) b7 = models.Bike(current_location=2) b8 = models.Bike(current_location=3) b9 = models.Bike(current_location=3) # adminuser = models.Account(surname="adSur", username="******", firstname="adFir", password="******", account_type=1) # staffuser = models.Account(surname="staffSur", username="******", firstname="staffFir", password="******", account_type=2) db.session.add(l1) db.session.add(b1) db.session.add(l2) db.session.add(b2) db.session.add(l3)
def add_or_create_location(address): location = models.Location.query.filter_by(location=address).first() if not location: location = models.Location(location=address) return location
def post(model_id, model_name): file = request.files.get('file') current_app.logger.info(f'Files: {request.files}') if not file: msg = flask_babel.gettext('No file uploaded') return jsonify({'message': msg}), 400 try: upload = app.storage.upload( file, acl=None ) # ACL set to none to avoid libcloud bug in generating invalid signature except flask_cloudy.InvalidExtensionError as error: msg = flask_babel.gettext('Invalid file extension for upload') return jsonify({'message': msg}), 400 document_id = request.form.get('document_id') or None if document_id: document_id = document_id files = models.UploadedFile.query.filter_by( document_id=document_id).all() for f in files: remote_file = app.storage.get(f.remote_filename) remote_file.delete() app.db.session.delete(f) # TODO: get uploaded location details from form uploaded_location_latitude = helpers.get_gps_value( request.form, 'uploaded_location_latitude') uploaded_location_longitude = helpers.get_gps_value( request.form, 'uploaded_location_longitude') uploaded_location_position_accuracy = helpers.get_gps_value( request.form, 'uploaded_location_position_accuracy') uploaded_location_altitude = helpers.get_gps_value( request.form, 'uploaded_location_altitude') uploaded_location_altitude_accuracy = helpers.get_gps_value( request.form, 'uploaded_location_altitude_accuracy') uploaded_location_heading = helpers.get_gps_value( request.form, 'uploaded_location_heading') uploaded_location_speed = helpers.get_gps_value(request.form, 'uploaded_location_speed') got_uploaded_location_data = any([ uploaded_location_latitude is not None and uploaded_location_longitude is not None, uploaded_location_position_accuracy is not None, uploaded_location_altitude is not None, uploaded_location_altitude_accuracy is not None, uploaded_location_heading is not None, uploaded_location_speed is not None ]) if got_uploaded_location_data: coordinates = f"POINT({uploaded_location_longitude} {uploaded_location_latitude})" uploaded_location = models.Location( coordinates=coordinates, position_accuracy=uploaded_location_position_accuracy, altitude=uploaded_location_altitude, altitude_accuracy=uploaded_location_altitude_accuracy, heading=uploaded_location_heading, location_speed=uploaded_location_speed, location_dt=datetime.utcnow()) else: uploaded_location = None # TODO: get taken location details from form taken_location_latitude = helpers.get_gps_value(request.form, 'taken_location_latitude') taken_location_longitude = helpers.get_gps_value( request.form, 'taken_location_longitude') taken_location_position_accuracy = helpers.get_gps_value( request.form, 'taken_location_position_accuracy') taken_location_altitude = helpers.get_gps_value(request.form, 'taken_location_altitude') taken_location_altitude_accuracy = helpers.get_gps_value( request.form, 'taken_location_accuracy') taken_location_heading = helpers.get_gps_value(request.form, 'taken_location_heading') taken_location_speed = helpers.get_gps_value(request.form, 'taken_location_speed') got_taken_location_data = any([ taken_location_latitude is not None and taken_location_longitude is not None, taken_location_position_accuracy is not None, taken_location_altitude is not None, taken_location_altitude_accuracy is not None, taken_location_heading is not None, taken_location_speed is not None ]) if got_taken_location_data: coordinates = f"POINT({taken_location_longitude} {taken_location_latitude})" taken_location = models.Location( coordinates=coordinates, position_accuracy=taken_location_position_accuracy, altitude=taken_location_altitude, altitude_accuracy=taken_location_altitude_accuracy, heading=taken_location_heading, location_speed=taken_location_speed, location_dt=datetime.utcnow()) else: taken_location = None try: exif = helpers.get_exif(file) geotags = helpers.get_geotagging(exif) extracted_latitude, extracted_longitude = helpers.get_coordinates( geotags) current_app.logger.error( f"{file.filename} extracted location ({extracted_latitude}, {extracted_longitude})" ) coordinates = f"POINT({extracted_longitude} {extracted_latitude})" extracted_location = models.Location(coordinates=coordinates, location_dt=datetime.utcnow()) except ValueError: extracted_location = None current_app.logger.info( f"{file.filename} did not contain location information") except UnidentifiedImageError as uie: extracted_location = None current_app.logger.info(uie) except Exception as ex: extracted_location = None current_app.logger.exception( f"Error trying to extract location information from {file.filename}" ) uploaded_file = models.UploadedFile( model_name=model_name, model_id=model_id, document_id=document_id, original_filename=file.filename, remote_filename=upload.name, uploaded_location=uploaded_location, taken_location=taken_location, extracted_location=extracted_location, created_by=g.request_user, ) app.db.session.add(uploaded_file) app.db.session.commit() return jsonify(uploaded_file.__getstate__()), 200
def post(self): cache = _InvitationCache() guest_file = self.request.POST.get('guest_list') location_file = self.request.POST.get('location_list') if guest_file == '' or not guest_file.file: self.session[GUEST_LIST_ERR] = ( 'Please provide a guest_list.csv file') self.redirect('/admin/populate') return if location_file == '' or not location_file.file: self.session[LOCATION_LIST_ERR] = ( 'Please provide a location_list.csv file') self.redirect('/admin/populate') return guest_reader = csv.DictReader(guest_file.file) got_guest_fields = set(guest_reader.fieldnames) if not WANT_GUEST_LIST_FIELDS.issubset(got_guest_fields): self.session[GUEST_LIST_ERR] = ( 'guest_list.csv should have the fields %s' % ', '.join(WANT_GUEST_LIST_FIELDS)) self.redirect('/admin/populate') return location_reader = csv.DictReader(location_file.file) got_location_fields = set(location_reader.fieldnames) if not WANT_LOCATION_LIST_FIELDS.issubset(got_location_fields): self.session[LOCATION_LIST_ERR] = ( 'location_list.csv should have the fields %s' % ', '.join(WANT_LOCATION_LIST_FIELDS)) self.redirect('/admin/populate') return ndb.delete_multi(models.Guest.query().fetch(keys_only=True)) ndb.delete_multi(models.Location.query().fetch(keys_only=True)) for row in guest_reader: invitation_code = row.get('invitation_code') if not invitation_code: continue invitation = cache.get_or_create(invitation_code) guest = models.Guest( parent=invitation.key, first_name=row.get('first_name') or None, last_name=row.get('last_name') or None, email=row.get('email') or None, is_child=row.get('is_child') == '1' or False, ) guest.put() for row in location_reader: invitation_code = row.get('invitation_code') if not invitation_code: continue invitation = cache.get_or_create(invitation_code) try: location = models.Location( parent=invitation.key, location=LOCATION_MAP[row.get('location')], has_plus_one=row.get('has_plus_one') == '1' or False, additional_child_count=int( row.get('additional_child_count', 0)), ) location.put() except (KeyError, ValueError): continue self.redirect('/admin')
def test_location(): assert models.Location() is not None
im = Image.open('images/' + imgName) width, height = im.size # Get dimensions new_width = 160 new_height = 160 left = (width - new_width) / 2 top = (height - new_height) / 2 right = (width + new_width) / 2 bottom = (height + new_height) / 2 im = im.crop((left, top, right, bottom)) im.save('images/' + imgName) if type == "kids": type = "entertainment" forKids = True if type == "hard" or type == "amusement": type = "amusement" intensive = True excludedCategory = 'elderly' if models.Location.query.filter_by(name=title).first() is None: l = models.Location(title, description, 0, 0, imgName, intensive, rating, type, excludedCategory, forKids) db.session.add(l) db.session.commit()
def edit_profile(request, username): # Getting current user if User.objects.filter(username=username).exists(): user = User.objects.get(username=username) else: return render( request, "errors/does-not-exist", context={ "title": "User doesn't exist!", "content": "We're sorry, but we couldn't find the user you were looking for! That user has either been removed, or never existed in the first place. Please go back to the previous page if possible." }) # Getting profile from current user profile = models.Profile.objects.get(user=user) # Checking to see if current user is the one editing profile if user != request.user: return render( request, "errors/does-not-exist.html", context={ "title": "Permission Error", "content": "We're sorry, but you don't have permission to modify this profile. Only the logged in user of this account has permission to modify any of the content of their profile." }) if request.method == "POST": # Grabbing all pieces of form POST data # Grabbing default Django User data first_name = request.POST.get("first-name") last_name = request.POST.get("last-name") email = request.POST.get("email") username = request.POST.get("username") password = request.POST.get("password") # Grabbing custom profile data biography = request.POST.get("biography") birthday = request.POST.get("birthday") locationName = request.POST.get("location") education = request.POST.get("education") skills = request.POST.get("skills").split(",") # Social Links facebook_profile = request.POST.get("facebook-profile") instagram_profile = request.POST.get("instagram-profile") linkedin_profile = request.POST.get("linkedin-profile") twitter_profile = request.POST.get("twitter-profile") github_profile = request.POST.get("github-profile") youtube_profile = request.POST.get("youtube-profile") medium_profile = request.POST.get("medium-profile") personal_website = request.POST.get("personal-website") # Check if username/email is used if (User.objects.filter(email=email).exists() and email != request.user.email) or ( User.objects.filter(username=username).exists() and username != request.user.username): return render( request, "app/profile/edit-profile.html", context={ "message": "Username and/or email is already taken. Please double check.", "status": "bad", "profile": profile }) # Creating location object if exists location = None if locationName: response = requests.get( f"https://maps.googleapis.com/maps/api/geocode/json?address={locationName}&key={settings.GOOGLE_API_KEY}" ) location = models.Location(name=locationName) if response.json()["results"]: location.lat = response.json( )["results"][0]["geometry"]["location"]["lat"] location.lng = response.json( )["results"][0]["geometry"]["location"]["lng"] location.save() # Updating user user = User.objects.get(id=request.user.id) user.first_name = first_name user.last_name = last_name user.email = email user.username = username # Updating profile profile = models.Profile.objects.get(user=request.user) profile.biography = biography profile.location = location profile.education = education profile.skills = skills profile.facebook_profile = facebook_profile profile.instagram_profile = instagram_profile profile.linkedin_profile = linkedin_profile profile.twitter_profile = twitter_profile profile.github_profile = github_profile profile.youtube_profile = youtube_profile profile.medium_profile = medium_profile profile.personal_website = personal_website # To avoid 'Invalid Date Format' error for empty birthday if birthday: profile.birthday = birthday # Checking if they provided picture if 'profile-picture' in request.FILES: profile.profile_picture = request.FILES['profile-picture'] # Turning off update_profile field on model if not profile.updated_profile: profile.updated_profile = True user.save() profile.save() return HttpResponseRedirect("/@" + user.username) skills = None if profile.skills: skills = ",".join(profile.skills) return render(request, "app/profile/edit-profile.html", context={ "profile": profile, "skills": skills, "google_api_key": settings.GOOGLE_API_KEY })