def create_user(): body = request.get_json() exists = db.session.query( db.exists().where(User.email == body['email'])).scalar() if exists == True: user = User.query.filter_by(email=body["email"]).first() is_active = user.is_active if is_active == False: hashed_password = generate_password_hash(body['password'], method='sha256') old_new_user = user old_new_user.reactivate_user(body['name'], body['last_name'], hashed_password, is_active) return jsonify(old_new_user.serialize()), 200 else: return "Email alredy in use", 400 else: try: hashed_password = generate_password_hash(body['password'], method='sha256') new_user = User(email=body["email"], password=hashed_password, is_active=True, name=body["name"], last_name=body["last_name"]) new_user.create_user() return jsonify(new_user.serialize()), 200 except: return "Couldn't create the user", 401
def subscribe(channel_id): if not db.session.query(db.exists().where(User.id == channel_id)).scalar(): return redirect(request.referrer) new_subscribe = SubscriberAssociation(author_id=channel_id, subscriber_id=current_user.id) db.session.add(new_subscribe) db.session.commit() return redirect(request.referrer)
def searchbox(): """Search area for restroom""" search = request.args.get('q') client = GoogleSearchClass(api_key = API_KEY, address_or_postal_code=search) search_result=client.search() filtered_list = client.filter_results() detailed_list = client.detail() filtered=list(filtered_list) if search_result['status'] == "INVALID_REQUEST": raise ValueError('invalid zip code or address') for place in detailed_list: blacklist_exists = db.session.query(db.exists().where(Blacklist.restroom_id == place['place_id'])).scalar() if blacklist_exists is True: detailed_list.remove(place) else: for restroom in filtered[0]: name = restroom['name'] latitude = restroom['geometry']['location']['lat'] longitude = restroom['geometry']['location']['lng'] address = restroom['vicinity'] place_id = restroom['place_id'] user_id = g.user.id toilet = Restroom(name=name, latitude=latitude, longitude=longitude, address=address, place_id=place_id, user_id = user_id ) restroom_exists = db.session.query(db.exists().where(Restroom.place_id == place_id)).scalar() if restroom_exists is True: continue else: db.session.add(toilet) db.session.commit() return render_template('restrooms.html', detailed_list=detailed_list)
def create_venue_submission(): # TODO: insert form data as a new Venue record in the db, instead DONE # TODO: modify data to be the data object returned from db insertion # venue = request.form try: # venue = Venue( # name=request.form['name'], # genres=request.form.getlist('genres'), # address=request.form['address'], # city=request.form['city'], # state=request.form['state'], # phone=request.form['phone'], # facebook_link=request.form['facebook_link'], # website=request.form['website'], # image_link=request.form['image_link'], # seeking_talent=True if request.form['seeking_talent'] in ('y', True, 't', 'True') else False, # seeking_description=request.form['seeking_description'], # ) # print(venue.seeking_talent) exists = db.session.query( db.exists().where(Venue.name == request.form['name'])).scalar() if exists: flash('This venue is already exist') return render_template('pages/venues.html') venue = Venue() for field in request.form: if field == 'genres': setattr(venue, field, request.form.getlist(field)) elif field == 'seeking_talent': setattr( venue, field, True if request.form.get(field) in ('y', True, 't', 'True') else False) else: setattr(venue, field, request.form.get(field)) try: db.session.add(venue) db.session.commit() flash('Venue ' + request.form['name'] + ' was successfully listed!') except: db.session.rollback() flash('An error occurred. Venue ' + venue.name + ' could not be listed.') return render_template('errors/500.html'), 500 finally: db.session.close() except: return render_template('errors/500.html'), 500 # on successful db insert, flash success # TODO: on unsuccessful db insert, flash an error instead. DONE # e.g., flash('An error occurred. Venue ' + data.name + ' could not be listed.') # see: http://flask.pocoo.org/docs/1.0/patterns/flashing/ return render_template('pages/home.html')
def test_promote_active_recruiter_to_senior(self): response = set_roles(self.recruiter.id, is_senior_recruiter=True, current_user=self.admin) self.assertEqual(response, {'status': 'ok'}) self.assertTrue(self.recruiter.recruiter.is_senior) self.assertTrue( db.session.query(db.exists().where( db.and_(Application.user_id == self.applicant.id, Application.is_concluded == False))).scalar())
def add_comment(): comment = request.form.get("comment") commenter_id = request.form.get("commenter_id") post_id = request.form.get("post_id") if not comment: return make_response( jsonify({ "code": 403, "msg": "Cannot put comment. Comment is empty." }), 403) person_exists = db.session.query( db.exists().where(Person.id == commenter_id)).scalar() if not person_exists: return make_response( jsonify({ "code": 403, "msg": "Cannot comment on post. User does not exist." }), 403) post_exists = db.session.query( db.exists().where(Post.post_id == post_id)).scalar() if not post_exists: return make_response( jsonify({ "code": 403, "msg": "Cannot comment on post. Post does not exist." }), 403) c = Comment(post_id=post_id, commenter_id=commenter_id, comment=comment) db.session.add(c) try: db.session.commit() except sqlalchemy.exc.SQLAlchemyError as e: error = "Cannot put post. " print(app.config.get("DEBUG")) if app.config.get("DEBUG"): error += str(e) return make_response(jsonify({"code": 404, "msg": error}), 404) return jsonify({"code": 200, "msg": "success"})
def get_user_characters(user_id, current_user=None): user = User.get(user_id) if not has_applicant_access(current_user, user, self_access=True): raise ForbiddenException( 'User {} does not have access.'.format(current_user)) if not db.session.query(db.exists().where(User.id == user_id)).scalar(): raise BadRequestException( 'User with id={} does not exist.'.format(user_id)) character_dict = {} for character in db.session.query(Character).filter( Character.user_id == user_id): character_dict[character.id] = { 'name': character.name, 'corporation_id': character.corporation_id, 'corporation_name': character.corporation.name, } return {'info': character_dict}
def create_artist_submission(): # called upon submitting the new artist listing form # TODO: insert form data as a new Venue record in the db, instead # TODO: modify data to be the data object returned from db insertion try: exists = db.session.query( db.exists().where(Artist.name == request.form['name'])).scalar() if exists: flash('This artist is already exist') return render_template('pages/artists.html') artist = Artist() for field in request.form: if field == 'genres': setattr(artist, field, request.form.getlist(field)) elif field == 'seeking_venue': setattr( artist, field, True if request.form.get(field) in ('y', True, 't', 'True') else False) else: setattr(artist, field, request.form.get(field)) try: db.session.add(artist) db.session.commit() flash('Artist ' + request.form['name'] + ' was successfully listed!') except: db.session.rollback() flash('An error occurred. Artist ' + artist.name + ' could not be listed.') return render_template('errors/500.html'), 500 finally: db.session.close() except: return render_template('errors/500.html'), 500 # on successful db insert, flash success # flash('Artist ' + request.form['name'] + ' was successfully listed!') # TODO: on unsuccessful db insert, flash an error instead. # e.g., flash('An error occurred. Artist ' + data.name + ' could not be listed.') return render_template('pages/home.html')
def delete_post_by_id(post_id): post_exists = db.session.query( db.exists().where(Post.post_id == post_id)).scalar() if not post_exists: return make_response( jsonify({ "code": 403, "msg": "Post does not exist." }), 403) post = Post.query.filter_by(post_id=post_id).first() if post: Post.query.filter_by(post_id=post_id).delete() Comment.query.filter_by(post_id=post_id).delete() db.session.commit() return jsonify({"code": 200, "msg": "success"}) else: return make_response( jsonify({ "code": 404, "msg": "Post does not exist." }), 404)
def get(self): if current_identity.has_role('admin') or current_identity.has_role('researcher'): survey = database.survey.get(current_identity.survey_id) survey_users = [] users_with_coordinates = (survey.mobile_users.filter( db.exists().where(MobileUser.id == MobileCoordinate.mobile_id))) for user in users_with_coordinates: survey_users.append({ 'uuid': user.uuid, 'created_at': user.created_at.isoformat() }) else: survey_users = [{ 'uuid': current_identity.participant_uuid, 'created_at': current_identity.created_at.isoformat() }] return Success(status_code=200, headers=self.headers, resource_type=self.resource_type, body=survey_users)
def fetch_data(): date = datetime.today().date() - timedelta(days=1) date_to_url = str(date).replace('-', '') URL = f'https://www.espn.com/nba/scoreboard/_/date/{date_to_url}' driver = webdriver.Chrome(ChromeDriverManager().install()) driver.get(URL) soup = BeautifulSoup(driver.page_source, 'html.parser') teams = soup.find_all("tbody", {"id": "teams"}) if not soup and not teams: return if db.session.query(db.exists().where(DateResults.date == date)).scalar(): return date_results_model = DateResults(date=date) date_results_model.save() for i in teams: away = i.find("tr", {"class": "away"}) home = i.find("tr", {"class": "home"}) data = { 'away_name': away.find('span', { 'class': 'sb-team-short' }).text, 'away_score': int(away.find('td', { 'class': 'total' }).text), 'home_name': home.find('span', { 'class': 'sb-team-short' }).text, 'home_score': int(home.find('td', { 'class': 'total' }).text), 'date_results_id': date_results_model.id } teams_scores_model = TeamsScores(**data) teams_scores_model.save() driver.close() return
def get_answers(user_id, current_user=None): if not db.session.query(db.exists().where(User.id == user_id)).scalar(): raise BadRequestException( 'User with id={} does not exist.'.format(user_id)) user = User.get(user_id) current_user = current_user or user if not has_applicant_access(current_user, user, self_access=True): raise ForbiddenException( 'User {} does not have access to user {}'.format( current_user, user_id)) application = Application.get_for_user(user_id) if not application: raise BadRequestException( 'User with id={} has no application.'.format(user_id)) questions = get_questions() response = {'questions': {}, 'has_application': False} if application: response['has_application'] = True # get a dict keyed by question id of questions & answers answers = {a.question_id: a.text for a in application.answers} for question_id in questions: answer = answers[question_id] if question_id in answers else "" response['questions'][question_id] = { 'question': questions[question_id], 'user_id': user_id, 'answer': answer, } else: # no application yet, create empty answers for question_id in questions: response['questions'][question_id] = { 'question': questions[question_id], 'user_id': user_id, 'answer': '', } return response
import models from models import db, Picar from flask_socketio import SocketIO, emit webcam_w = 320 webcam_h = 240 fps = 10 app = Flask(__name__) app.config.from_object(Config) db.init_app(app) # create db if it doesn't exists with app.app_context(): db.create_all() exists = db.session.query(db.exists().where(Picar.id == 1)).scalar() #exists = Picar.query.filter_by(id=0).first().scalar() if (exists == 0): print("creating defaults for picar in db") picarDb = Picar(name="picarv1") db.session.add(picarDb) db.session.commit() # query to make sure it's in there #ppp = db.session.query(db.exists().where(Picar.id == 0)) ppp = Picar.query.filter_by(id=1).first() #ppp = Picar.query.get(0) print("got picar from db name:" + ppp.name)