def post_business(payload): body = request.get_json() id = body.get('id', None) name = body.get('name', None) address = body.get('address', None) phone = body.get('phone', None) cif = body.get('cif', None) email = body.get('email', None) try: if id is None: business = Business(name=name, address=address, phone=phone, cif=cif, email=email) else: business = Business(id=id, name=name, address=address, phone=phone, cif=cif, email=email) business.insert() except: abort(422) return jsonify({ 'success': True, 'business': business.long(), 'status': 200 }), 200
def signup(): """ signup route :return: """ form = RegisterForm(request.form) if request.method == 'POST' and form.validate(): print('validate', request.form) username = form.name.data.title() email = form.email.data.capitalize() business = form.business.data.title() language = form.language.data.title() password = generate_password_hash(form.password.data, method='sha256') check_valid = User.query.filter_by(name=username).first() if check_valid is None: check_valid = User.query.filter_by(email=email).first() if check_valid is not None: return render_template('signup.html', error='Username, Email or address already taken', form=form) new_user = User(name=username, email=email, password=password, language=language, verified=True) db.session.add(new_user) db.session.commit() new_bus = Business(name=business, user_id=new_user.id) db.session.add(new_bus) db.session.commit() return redirect(url_for('login')) else: print(form.errors) return render_template('signup.html', form=form, error='')
def post(self): request_text = request.get_json(force=True) business_json = json.loads(json.dumps(request_text)) if('city' in business_json and 'review_count' in business_json and 'name' in business_json and 'business_id' in business_json and 'longitude' in business_json and 'hours' in business_json and 'state' in business_json and 'postal_code' in business_json and 'stars' in business_json and 'address' in business_json and 'latitude' in business_json and 'is_open' in business_json and 'attributes' in business_json and 'categories' in business_json and 'deleted' in business_json): new_business = Business( address = business_json['address'], business_attributes = business_json['attributes'], business_id = business_json['business_id'], categories = business_json['categories'], city = business_json['city'], deleted = business_json['deleted'], hours = business_json['hours'], is_open = business_json['is_open'], latitude = business_json['latitude'], longitude = business_json['longitude'], business_name = business_json['name'], postal_code = business_json['postal_code'], review_count = business_json['review_count'], stars = business_json['stars'], business_state = business_json['state'] ) postgres.session.add(new_business) postgres.session.commit() return "Success" return "Invalid fields"
def add_favorite(business_id): """Add favorite business to the current user""" if not g.user: flash("Please log in first.", "danger") return redirect('/signin') # get business's name url = API_BASE_URL + '/businesses/' + business_id req = requests.get(url, headers=headers) business = json.loads(req.text) business_name = business.get('name', None) # check if the item is on the Business models # if Business.query.all() == [] or not Business.query.filter(Business.business_id == business_id).first(): # get id for user's favorite businesses fav_business_ids = [] for each_fav_business in g.user.favorite_business: fav_business_ids.append(each_fav_business.business_id) # check if current id is in favourite businesses already if business_id not in fav_business_ids: new_business = Business(business_id=business_id, business_name=business_name) g.user.favorite_business.append(new_business) db.session.commit() return redirect('/users/' + g.user.username)
def create_or_update_business(self, alias_name, import_data): business = self.businessDao.query_by_alias(alias_name) if business is not None: business_key = business.key import_data.business_id = business_key logger.info('Business Already Exist with Key %s' % str(business_key)) else: try: business = Business() business.name = import_data.name business.description = import_data.description business.alias = import_data.alias business.contact_info = import_data.contact_info business_key = self.businessDao.persist( business, self.user_info) import_data.business_id = business_key logger.info('New Business Created for %s with key %s' % (alias_name, str(business_key))) except StandardError as e: #Skip the error and continue logger.error('Error occured, %s, for %s' % (str(e), alias_name)) raise return business_key
def add_bus_from_resp(self): if not Business.query.filter(Business.yelp_id==self.yelp_id).first(): business = Business(yelp_id=self.yelp_id,name=self.name) db.session.add(business) db.session.commit() return self return self
def post(self): r = request.get_json(force=True) businessBatch = r[10:len(r) - 6].strip().replace("\n", "").split('}, {') for singleBusiness in businessBatch: json_data = json.loads('{' + singleBusiness + '}') try: business = Business( city=json_data['city'], review_count=json_data['review_count'], business_name=json_data['name'], business_id=json_data['business_id'], longitude=json_data['longitude'], hours=json_data['hours'], business_state=json_data['state'], postal_code=json_data['postal_code'], stars=json_data['stars'], address=json_data['address'], latitude=json_data['latitude'], is_open=json_data['is_open'], business_attributes=json_data['attributes'], categories=json_data['categories'], deleted=json_data['deleted']) except Exception as e: return (str(e)) postgres.session.add(business) postgres.session.commit() return {}
def update_company(): user = Users.query.filter_by(email=current_user.email).first() business = Business.query.filter_by(owner_id=user.id).first() name = request.form.get('business_name') address = request.form.get('business_address') phone_number = request.form.get('phone_number') email = request.form.get('business_email') sector = request.form.get('business_sector') description = request.form.get('business_description') if business is not None: business.name = name business.address = address business.phone_number = phone_number business.business_email = email business.sector = sector business.description = description db.session.commit() else: new_business = Business(owner_id=user.id, name=name, address=address, phone_number=phone_number, sector=sector, business_email=email, description=description) db.session.add(new_business) db.session.commit() return redirect(url_for('main.profile'))
def form_to_dao_business(self, **update): business = Business() business.name = update['name'] #Create an automatic alias for the business business.alias = utils.slugify(update['name']) business.description = update['description'] business = self.form_to_dao_contact_info_import(business, **update) return business
def create_or_update_business(self, event): if event.business_id is not None: business = self.businessDao.get_record(long(event.business_id.id())) else: business = Business() business.name = event.name business.description = event.description business.alias = event.alias business.contact_info = event.contact_info return business
def create_or_update_business(self, trainingcentre): if trainingcentre.business_id is not None: business = self.businessDao.get_record(long(trainingcentre.business_id.id())) else: business = Business() business.name = trainingcentre.name business.description = trainingcentre.description business.alias = trainingcentre.alias business.contact_info = trainingcentre.contact_info return business
def create_or_update_business(self, playground): if playground.business_id is not None: business = self.businessDao.get_record(long(playground.business_id.id())) else: business = Business() business.name = playground.name business.description = playground.description business.alias = playground.alias business.contact_info = playground.contact_info return business
def displayBusinessForm(): if request.method == 'GET': return render_template('business-registration-form.html') elif request.method == 'POST': bname = request.form.get('bname') num_interns = request.form.get('num_interns') duration = request.form.get('duration') credits = request.form.get('credits') stipend = request.form.get('stipend') lang = request.form.get('lang') design = request.form.get('design') dbms = request.form.get('dbms') soft_skills = request.form.get('soft_skills') business = Business.query.filter_by(bname=bname).first() if business is None: new_business = Business(bname=bname, num_interns=num_interns, duration=duration, stipend=stipend, credits=credits, language=lang, design=design, dbms=dbms, soft_skills=soft_skills) db.session.add(new_business) db.session.commit() proj_name = request.form.get('proj_name') proj_descript = request.form.get('proj_descript') activities = request.form.get('activities') internship = Internship.query.filter_by( proj_name=proj_name).first() if internship is None: new_internship = Internship( proj_name=proj_name, proj_descript=proj_descript, activities=activities, business_ID=new_business.businessID) try: db.session.add(new_internship) db.session.commit() #return render_template('business-homepage.html') return redirect(url_for('displayBusinessForm')) except IntegrityError: return 'Application does not exist', render_template( "business-registration.html"), 400 return
def form_to_dao(self, business_id): business = None if business_id is not None and len(business_id) > 1: business = self.businessDao.get_record(long(business_id)) logger.debug('business ' + str(business)) else: business = Business() logger.debug('business 2 ' + str(business)) business.name = self.form.name.data #Create an automatic alias for the business business.alias = utils.slugify(self.form.name.data) business.description = self.form.description.data return cms_utils.form_to_dao_contact_info(self.form, business)
def signup_business(): request_body = request.get_json() print(request_body) business1 = Business( business_name=request_body["business_name"], address=request_body["address"], phone_number=request_body["phone_number"], email=request_body["email"], password=request_body["password"], ) db.session.add(business1) db.session.commit() return jsonify(request_body), 200
def test_business_details(self): with app.test_client() as client: client.get('/') # Create a user with info shown below b1 = Business(business_id = 'OSZ6bFeCcv4PvUmvuiMEJw', business_name = 'Little Sweet') db.session.add(b1) db.session.commit() res = client.get("foodies/details/OSZ6bFeCcv4PvUmvuiMEJw") html = res.get_data(as_text = True) self.assertEqual(res.status_code, 200) self.assertIn('<i class="fab fa-yelp" style="color: #c41200;"></i> More Reviews', html) # this item has not been added to user's favourite self.assertIn('style="display: inline-block; margin-right: 0.1rem" style="display: inline-block; margin-right: 0.1rem">Add it to Favorite?</a>', html)
def add_business(payload): body = request.get_json() if not request.get_json(): abort(400) name = body['name'] description = body['description'] date_added = datetime.today() business = Business(name=name, description=description, date_added=date_added) Business.insert(business) return jsonify({'success': True, 'new_business': business.format()})
def validate_db(yelp_object, haven_model=None): """takes the result of a yelp query by businesses id and compares it to the database entry. If any information on the local db is out of date, it is updated accordingly. Will also create new db if the haven_model is none""" print "yelp object in validate_db:", yelp_object print "haven_model in validate_db", haven_model new = False if haven_model is None: haven_model = Business() haven_model.yelp_id = yelp_object['id'] new = True haven_model.name = yelp_object['name'] if yelp_object['location'].get('address'): if len(yelp_object['location']['address']) > 1: haven_model.address_line_2 = yelp_object['location']['address'][1] haven_model.address_line_1 = yelp_object['location']['address'][0] # nothing in local db should not have a city and state code but if for some reason yelp wiped them, it prevents it # from being cleared, protecting db integrity if yelp_object['location'].get('city'): haven_model.city = yelp_object['location']['city'] if yelp_object['location'].get('state_code'): haven_model.state = yelp_object['location']['state_code'] if yelp_object['location'].get('postal_code'): haven_model.zipcode = yelp_object['location']['postal_code'] if yelp_object.get('phone'): haven_model.phone = yelp_object['phone'] if yelp_object['location'].get('coordinate'): haven_model.latitude = yelp_object['location']['coordinate']['latitude'] haven_model.longitude = yelp_object['location']['coordinate']['longitude'] try: if new: db.session.add(haven_model) print "successfully added" db.session.commit() print 'successfully committed' print "committed business:", haven_model except: print 'ut-oh'
def create_business_profile(): if request.method == 'GET': return render_template('new_business_form.html', userinfo=session['business_profile']) body = request.get_json() try: name = body.get('name') email = body.get('email') zip_code = body.get('zip_code') goals = body.get('goals') website = body.get('website') address = body.get('address') description = body.get('description') skills = body.get('skills'), auth_id = body.get('auth_id') business = Business(name=name, email=email, zip_code=zip_code, goals=goals, website=website, address=address, description=description, skills=skills, auth_id=auth_id) if not business: abort(404) business.insert() return jsonify({ 'success': True, 'name': business.name, 'email': business.email, 'zip_code': business.zip_code, 'goals': business.goals, 'website': business.website, 'address': business.address, 'description': business.description, 'skills': business.skills, 'auth_id': business.auth_id }), 200 except: abort(422)
def save_businesses(): for bdata in iterate_file("business", shortcircuit=False): business = Business() business.business_id = bdata['business_id'] business.name = bdata['name'] business.full_address = bdata['full_address'] business.city = bdata['city'] business.state = bdata['state'] business.latitude = bdata['latitude'] business.longitude = bdata['longitude'] business.stars = decimal.Decimal(bdata.get('stars', 0)) business.review_count = int(bdata['review_count']) business.is_open = True if bdata['open'] == "True" else False business.save() save_categories(bdata['business_id'], bdata['categories']) save_neighborhoods(bdata['business_id'], bdata['neighborhoods'])
def save_todo_list(): if request.method == 'GET': todolists = TodoList.query.filter_by(user_id=current_user.id).filter( TodoList.status >= 1).all() if len(todolists) < 1: return redirect(url_for('add_todo_list')) return render_template('savecore.html', todolists=todolists) elif request.method == 'POST': data = request.json for con in data['option']: id, number = con todolist = Business(id, number) db.session.add(todolist) db.session.commit() # flash('保存了家务') return redirect(url_for('save_todo_list'))
def save_businesses(): for bdata in iterate_file("business", shortcircuit=False): business = Business() business.business_id = bdata['business_id'] business.name = bdata['name'] business.address = bdata['address'] business.city = bdata['city'] business.neighborhood = bdata['neighborhood'] business.state = bdata['state'] business.latitude = bdata['latitude'] business.longitude = bdata['longitude'] business.stars = decimal.Decimal(bdata.get('stars', 0)) business.review_count = int(bdata['review_count']) business.is_open = True if bdata['is_open'] == "1" else False business.save() temp = bdata['attributes'] if bdata['attributes'] is not None else [] temp1 = bdata['categories'] if bdata['categories'] is not None else [] save_categories(bdata['business_id'], temp1) save_attributes(bdata['business_id'], temp)
def test_add_business_to_favorites(self): with app.test_client() as client: client.get('/') # Sign up first and save user signin_test into the database data = { "username":"******", "password":"******", "email":"*****@*****.**", "age":8, "gender":"male", "photo_url":"", "favorite_business":[] } res = client.post("/signup", data = data, follow_redirects = True) # have user signed in signin_data = { "username": "******", "password": "******" } res = client.post("/signin", data = signin_data, follow_redirects = True) # Create a business which is added as a favourite one of user signin_test b1 = Business(business_id = 'OSZ6bFeCcv4PvUmvuiMEJw', business_name = 'Little Sweet') # add business to user's favourite item list fav = FavoriteBusiness(username = '******', business_id = 'OSZ6bFeCcv4PvUmvuiMEJw') db.session.add(b1, fav) db.session.commit() res = client.get('/users/favorites/OSZ6bFeCcv4PvUmvuiMEJw', follow_redirects = True) html = res.get_data(as_text = True) self.assertEqual(res.status_code, 200) self.assertIn('Little Swee', html) self.assertIn('<button class="btn btn-outline-danger ml-2">Delete User</button>', html)
def post(self): # # PARSE THE POSTED OBJECT # parser = reqparse.RequestParser() parser.add_argument('name', type=str, required=True) parser.add_argument('store_address', type=str, required=True) parser.add_argument('city_name', type=str, required=True) parser.add_argument('state_name', type=str, required=True) args = parser.parse_args() # # VALIDATE POSTED OBJECT ARGUMENTS # # Scrub name argument for length between 1 and 50, all characters allowed if re.match('^.{1,50}$', args['name']) is None: return {'error': 'specified name is too short or too long'}, 400 # Scrub store address for length between 1 and 50, all characters allowed if re.match('^.{1,50}$', args['store_address']) is None: return { 'error': 'specified store_address is too short or too long' }, 400 # Scrub city name for length between 1 and 50, all characters allowed if re.match('^.{1,50}$', args['city_name']) is None: return { 'error': 'specified city_name is not formatted correctly' }, 400 # Scrub state name for length between 1 and 50, all characters allowed if re.match('^.{1,50}$', args['state_name']) is None: return { 'error': 'specified state_name is not formatted correctly' }, 400 # # SET BUSINESS OWNER USING JWT TOKEN # # Set manager to the token's identity, and add to args manager = get_jwt_identity() # # TRY/EXCEPT TO HANDLE API ERRORS # try: # # USE GOOGLE API TO FIND STORE ADDRESS LOCATION # # Get the geolocation of the store using its address, city, and state geo = geopy.geocoders.GoogleV3( api_key='AIzaSyD56wh0KThJ-ekY1WBICUzt_wEX6MtEH7c') location = geo.geocode('{}, {}, {}'.format(args["store_address"], args["city_name"], args["state_name"])) # Handle case when no location returned if location is None: return {'error': 'location does not exist'}, 400 # Parse returned address, city, and state names store_address = location.address.split(",")[0].strip() city_name = location.address.split(",")[1].strip() state_name = location.address.split(",")[2].split()[0].strip() # Get the timzone of the store using its latitude and longitude timezone = geo.timezone((location.latitude, location.longitude)) # # VALIDATE/CREATE CITY # # Fetch the city from the database city = City.query.filter_by(city_name=city_name, state_name=state_name).first() # If city does not exist in database, create and add it if city is None: # Make a second Google API query to find general city location, as opposed to business specific location city_location = geo.geocode('{}, {}'.format( args["city_name"], args["state_name"])) # Create new city object using city specific information city = City(city_name=city_name, state_name=state_name, timezone=timezone.zone, latitude=city_location.latitude, longitude=city_location.longitude) # Add new city and inform db db.session.add(city) db.session.flush() except: # Handle wide array of erros with error message return {'error': 'unable to create business at this time'}, 400 # # CREATE BUSINESS # init = { "name": args["name"], "store_address": store_address, "latitude": location.latitude, "longitude": location.longitude, "manager_address": manager, "city_id": city.id } business = Business(**init) db.session.add(business) # # HANDLE POTENTIAL INTEGRITY ERRORS # try: db.session.commit() except exc.IntegrityError: # If integrity error resulting from violation of unique constraint, rollback db.session.rollback() return { 'error': 'business at location in same city already exists' }, 400 resp = business.serialize resp['isOwner'] = True return resp, 201
def test_unicode_pk(self): # Primary key may be unicode string bus = Business(name=u'jaźń') bus.save()
def test_custom_pk(self): dan = Employee(employee_code=123, first_name='Dan', last_name='Jones') dan.save() self.assertQuerysetEqual(Employee.objects.all(), ['<Employee: Dan Jones>']) fran = Employee(employee_code=456, first_name='Fran', last_name='Bones') fran.save() self.assertQuerysetEqual(Employee.objects.all(), ['<Employee: Fran Bones>', '<Employee: Dan Jones>']) self.assertEqual(repr(Employee.objects.get(pk=123)), '<Employee: Dan Jones>') self.assertEqual(repr(Employee.objects.get(pk=456)), '<Employee: Fran Bones>') self.assertRaises(Employee.DoesNotExist, Employee.objects.get, pk=42) # Use the name of the primary key, rather than pk. self.assertEqual(repr(Employee.objects.get(employee_code__exact=123)), '<Employee: Dan Jones>') # pk can be used as a substitute for the primary key. self.assertQuerysetEqual(Employee.objects.filter(pk__in=[123, 456]), ['<Employee: Fran Bones>', '<Employee: Dan Jones>']) # The primary key can be accessed via the pk property on the model. e = Employee.objects.get(pk=123) self.assertEqual(e.pk, 123) # Or we can use the real attribute name for the primary key: self.assertEqual(e.employee_code, 123) # Fran got married and changed her last name. fran = Employee.objects.get(pk=456) fran.last_name = 'Jones' fran.save() self.assertQuerysetEqual(Employee.objects.filter(last_name__exact='Jones') , ['<Employee: Dan Jones>', '<Employee: Fran Jones>']) emps = Employee.objects.in_bulk([123, 456]) self.assertEqual(repr(emps[123]), '<Employee: Dan Jones>') b = Business(name='Sears') b.save() b.employees.add(dan, fran) self.assertQuerysetEqual(b.employees.all(), ['<Employee: Dan Jones>', '<Employee: Fran Jones>']) self.assertQuerysetEqual(fran.business_set.all(), ['<Business: Sears>']) self.assertEqual(repr(Business.objects.in_bulk(['Sears'])), "{u'Sears': <Business: Sears>}") self.assertQuerysetEqual(Business.objects.filter(name__exact='Sears'), ['<Business: Sears>']) self.assertQuerysetEqual(Business.objects.filter(pk='Sears'), ['<Business: Sears>']) # Queries across tables, involving primary key self.assertQuerysetEqual(Employee.objects.filter(business__name__exact='Sears'), ['<Employee: Dan Jones>', '<Employee: Fran Jones>']) self.assertQuerysetEqual(Employee.objects.filter(business__pk='Sears'), ['<Employee: Dan Jones>', '<Employee: Fran Jones>']) self.assertQuerysetEqual(Business.objects.filter(employees__employee_code__exact=123), ['<Business: Sears>']) self.assertQuerysetEqual(Business.objects.filter(employees__pk=123), ['<Business: Sears>']) self.assertQuerysetEqual(Business.objects.filter(employees__first_name__startswith='Fran'), ['<Business: Sears>'])
def addBusiness(business, business_type, features_dict): biz = Business(business, business_type, features_dict) db.session.add(biz) db.session.commit()
def insert(self, item): business_item = item['kolay']['business'] # try: # logo_url = item['kolay']['business']['logo'] # opener = urllib2.build_opener() # image = opener.open(logo_url) # logo = image.read() # except: # logo = None review_item = item['kolay']['reviews'] all_services_item = item['kolay']['services'] all_services_dict_list = self.get_all_services_list(all_services_item) engine = db_engine_connect() Session = sessionmaker(bind=engine) session = Session() business = self.get_entity_dict_values(entity=Business, item=business_item) review = self.get_entity_dict_values(entity=Review, item=review_item) # if logo: # business_entity = Business(logo=logo, **business) # else: business_entity = Business(**business) session.add(business_entity) session.add(Review(business=business_entity, **review)) for service_dict in all_services_dict_list: service_item = service_dict['service'] category_item = service_dict['category'] business_service_rel_item = service_dict['business_service_rel'] category = self.get_entity_dict_values(entity=Category, item=category_item) service = self.get_entity_dict_values(entity=Service, item=service_item) business_service_rel = self.get_entity_dict_values( entity=BusinessServicesRel, item=business_service_rel_item) category_entity_exists = session.query(Category).filter_by( name=category['name']).first() if category_entity_exists: service_entity = Service(category=category_entity_exists, **service) session.add(service_entity) session.add( BusinessServicesRel(service=service_entity, business=business_entity, **business_service_rel)) else: category_entity = Category(**category) service_entity = Service(category=category_entity, **service) session.add(category_entity) session.add(service_entity) session.add( BusinessServicesRel(service=service_entity, business=business_entity, **business_service_rel)) session.commit() session.close()
from models import Business import os from django.conf import settings b = Business(name='A business', password = '******') b.save()
def build_db(city, state): # categories = ['active', 'arts', 'auto', 'beautysvc', 'education', 'eventservices', 'financialservices', 'food', # 'health', 'homeservices', 'hotelstravel', 'localflavor', 'localservices', 'massmedia', 'nightlife', # 'pets', 'professional', 'publicservicesgovt', 'realestate', 'religiousorgs', 'restaurants', # 'shopping'] city_state = city + ", " + state # for category in categories: # result_count = yelp_api.search_query(location=city_state, category_filter=category)['total'] result_count = yelp_api.search_query(location=city_state)['total'] offset = 0 added = 0 skipped = 0 print result_count # max offset is 1000 # try: while offset < result_count: while offset < 1000: # print category # results = yelp_api.search_query(location=city_state, category_filter=category, offset=offset) results = yelp_api.search_query(location=city_state, offset=offset) for result in results['businesses']: try: business = Business() # id business.yelp_id = result['id'] # name business.name = result['name'] # address lines 1 and 2 if result['location'].get('address'): business.address_line_1 = result['location'][ 'address'][0] if len(result['location']['address']) > 1: business.address_line_2 = result['location'][ 'address'][1] # city business.city = result['location']['city'] # state code business.state = result['location']['state_code'] # zip code business.zipcode = result['location']['postal_code'] # phone if result.get('phone'): business.phone = result['phone'] # latitude and longitude if result['location'].get('coordinate'): business.latitude = result['location']['coordinate'][ 'latitude'] business.longitude = result['location']['coordinate'][ 'longitude'] # list of categories if result.get('categories'): cat_list = [] for group in result['categories']: for subtype in group: if not Category.query.filter_by( category_name=subtype).first(): category = Category(category_name=subtype) db.session.add(category) cat_list.append(subtype) # if not Business.query.filter_by(yelp_id=business.yelp_id).first(): # db.session.add(business) db.session.add(business) db.session.commit() bus_id = business.business_id for cat in cat_list: # creates row in reference table catbus = BusinessCategory() catbus.business_id = bus_id cat_object = Category.query.filter_by( category_name=cat).first() catbus.category_id = cat_object.category_id db.session.add(catbus) db.session.commit() added += 1 print "added" + str(added) print business.name except: print "already added:" + business.name print 'skipped' + str(skipped) skipped += 1 print "added so far: " + str(added) db.session.commit() offset += 20