def get_user(id): if (key_users in cache and (datetime.now() - cache[key_users]['datetime']).total_seconds() < 5 ) or lock_users.locked(): users = cache[key_users]['data'] else: lock_users.acquire() session = db.getSession(engine) dbResponse = session.query(entities.User) session.close() users = dbResponse[:] now = datetime.now() cache[key_users] = {'data': users, 'datetime': now} lock_users.release() print('Using db') """ # Without cache db_session = db.getSession(engine) users = db_session.query(entities.User).filter(entities.User.id == id) session.close() """ final_user = [] for user in users: if user['id'] == id: final_user.append(user) break for user in final_user: js = json.dumps(final_user, cls=connector.AlchemyEncoder) return Response(js, status=200, mimetype='application/json') message = {'status': 404, 'message': 'Not Found'} return Response(json.dumps(message), status=404, mimetype='application/json')
def get_answers(): answers = [] if (key_answers in cache and (datetime.now() - cache[key_answers]['datetime']).total_seconds() < 5 ) or lock_answers.locked(): answers = cache[key_answers]['data'] else: lock_answers.acquire() session = db.getSession(engine) dbResponse = session.query(entities.Answers) session.close() answers = dbResponse[:] now = datetime.now() cache[key_answers] = {'data': answers, 'datetime': now} lock_answers.release() print('Using db') response = [] for answer in answers: copy = {} copy['id'] = answer.id copy['content'] = answer.content copy['sent_on'] = answer.sent_on.strftime("%m/%d/%Y %H:%M:%S") copy['user_id'] = answer.user_id copy['user'] = answer.user copy['question_id'] = answer.question_id copy['question_course_id'] = answer.question_course_id copy['question'] = answer.question response.append(copy) return Response(json.dumps(response, cls=connector.AlchemyEncoder), mimetype='application/json')
def get_course(semester): semester = int(semester) if (key_courses in cache and (datetime.now() - cache[key_courses]['datetime']).total_seconds() < 20 ) or lock_courses.locked(): courses = cache[key_courses]['data'] else: lock_courses.acquire() session = db.getSession(engine) dbResponse = session.query(entities.Courses) session.close() courses = dbResponse[:] now = datetime.now() cache[key_courses] = {'data': courses, 'datetime': now} lock_courses.release() print('Using db') """ # Without cache db_session = db.getSession(engine) questions = db_session.query(entities.Questions).filter(entities.Questions.course_id == course_id) session.close() """ courses_requested = [] for course in courses: if course['semester'] == semester: courses_requested.append(course) if len(courses_requested) > 0: data = sorted(data, key=lambda msj: msj.semester) js = json.dumps(courses_requested, cls=connector.AlchemyEncoder) return Response(js, status=200, mimetype='application/json') message = {'status': 404, 'msg': 'Not Found'} return Response(json.dumps(message), status=404, mimetype='application/json')
def decks_warrior(): session = DBManager.create_session() decks = session.query(Deck).filter_by(deck_class='warrior').order_by(Deck.last_used.desc(), Deck.first_used.desc()).all() session.close() return render_template('decks/by_class.html', decks=decks, deck_class='Warrior')
def start(self): app = Flask(__name__) app.config.from_object(Config) print(app.app_context()) app.app_context().push() with app.app_context(): db.init_app(app) url = "http://tor01.com/hashcode/api/v1/posthash/" headers = {'Content-Type': 'application/json'} session = db.session() for result in self.tableslice(): for a in result: print("read files..") files = session.query(TORFILES).filter( TORFILES.infohash == a.info_hash).all() a.files = files print("dump json..") ajson = json.dumps(a, cls=AlchemyEncoder) print(ajson) #requests.post(url, headers=headers) requests.request("post", url, data=ajson, headers=headers) session.close()
def models_committed(sender,changes): session = db.create_scoped_session() query = session.query(User) for change in changes: if isinstance(change[0],Star): s = change[0] hashtag = change[0].hashtag reason = s.description users = query.filter(User.id.in_([s.owner_id,s.issuer_id])) owner_name = '' issuer_email ='' issuer_name = '' for user in users: if user.id == s.owner_id: owner_name = str(makeName(user.firstName,user.lastName)) else: issuer_email = user.email issuer_name = str(makeName(user.firstName,user.lastName)) if user.oauth_token is not None and s.tweet: success = tweet(s.id) if success: print "Tweet successful" else: print "Tweet failed" startThread(issuer_name,issuer_email,"interacted",owner_name,hashtag,reason) session.close()
def download_region(region_slug): try: session = models.create_session(models.DB_URL) region = session.query( models.Region).filter_by(slug=region_slug).first() outfile = StringIO.StringIO() writer = unicodecsv.writer(outfile) header = ('ptolemy_id', 'ptolemy_name', 'modern_name', 'ptolemy_lat', 'ptolemy_lon', 'modern_lat', 'modern_lon', 'disposition') writer.writerow(header) for place in region.places: ptolemy_coords = to_shape(place.ptolemy_point) ptolemy_lat = ptolemy_coords.y ptolemy_lon = ptolemy_coords.x if place.modern_point is not None: modern_coords = to_shape(place.modern_point) modern_lat = modern_coords.y modern_lon = modern_coords.x else: modern_coords = None modern_lat = None modern_lon = None row = (place.ptolemy_id, place.ptolemy_name, place.modern_name, ptolemy_lat, ptolemy_lon, modern_lat, modern_lon, place.disposition) writer.writerow(row) response = make_response(outfile.getvalue()) response.headers[ 'Content-Disposition'] = 'attachment; filename=%s.csv' % ( region.slug) response.headers['Content-type'] = 'text/csv' session.close() return response except Exception as e: current_app.logger.error(e.message, exc_info=e)
def models_committed(sender, changes): session = db.create_scoped_session() query = session.query(User) for change in changes: if isinstance(change[0], Star): s = change[0] hashtag = change[0].hashtag reason = s.description users = query.filter(User.id.in_([s.owner_id, s.issuer_id])) owner_name = '' issuer_email = '' issuer_name = '' for user in users: if user.id == s.owner_id: owner_name = str(makeName(user.firstName, user.lastName)) else: issuer_email = user.email issuer_name = str(makeName(user.firstName, user.lastName)) if user.oauth_token is not None and s.tweet: success = tweet(s.id) if success: print "Tweet successful" else: print "Tweet failed" startThread(issuer_name, issuer_email, "interacted", owner_name, hashtag, reason) session.close()
def get(self, name): session = Session() movie = session.query(Movie).filter_by(name=name).first() movieSchema = MovieSchema() output = movieSchema.dump(movie) session.close() return jsonify({'Result': output})
def save_place(ptolemy_id): try: if request.form['submit'] == 'Submit': session = models.create_session(models.DB_URL) place = session.query(models.Place).get(ptolemy_id) place.ptolemy_name = request.form['ptolemy_name'] place.modern_name = request.form['modern_name'] ptolemy_lat, ptolemy_lon = [ float(s) for s in request.form['ptolemy_coords'].split(' ') ] place.ptolemy_point = from_shape(Point(ptolemy_lon, ptolemy_lat)) if len(request.form['modern_coords'].split(' ')) > 1: modern_lat, modern_lon = [ float(s) for s in request.form['modern_coords'].split(' ') ] place.modern_point = from_shape(Point(modern_lon, modern_lat)) else: place.modern_point = None place.disposition = request.form['disposition'] session.add(place) session.commit() session.close() return redirect(url_for('main.show_place', ptolemy_id=ptolemy_id)) except Exception as e: current_app.logger.error(e.message, exc_info=e)
def get_user_messages(u_id_from, u_id_to): data = [] #age_required=(cache[key_messages]['time']-datetime.now()).total_seconds() < 5 # lock=threading.Lock() # lock.acquire() #consultamos cache if key_users in cache and (datetime.now() - cache[key_users]['time']).total_seconds() < 0: #get cache data = cache[key_users]['data'] else: session = db.getSession(engine) dbResponse = session.query(entities.Message).filter( entities.Message.user_from_id == u_id_from, entities.Message.user_to_id == u_id_to) dbResponse2 = session.query(entities.Message).filter( entities.Message.user_from_id == u_id_to, entities.Message.user_to_id == u_id_from) session.close() data = dbResponse[:] data2 = dbResponse2[:] data = data + data2 #set cache{ cache[key_users] = {'data': data, 'time': datetime.now()} # lock.release() return Response(json.dumps(data, cls=connector.AlchemyEncoder), mimetype='application/json')
def getBackbones(): session = loopDB.Session() baseSeq = session.query(BaseSeq).all() jBackbones = list(map(baseSeqToJSON, baseSeq)) #print jBackbones session.close() return jBackbones
def highlight_list_date(date): # Make sure we were passed a valid date try: parsed_date = datetime.datetime.strptime(date, '%Y-%m-%d') except ValueError: # Invalid date return redirect('/highlights/', 303) session = DBManager.create_session() dates_with_highlights = [] highlights = session.query(StreamChunkHighlight).filter( cast(StreamChunkHighlight.created_at, Date) == parsed_date).order_by( StreamChunkHighlight.created_at.desc()).all() for highlight in session.query(StreamChunkHighlight): dates_with_highlights.append( datetime.datetime(year=highlight.created_at.year, month=highlight.created_at.month, day=highlight.created_at.day)) try: return render_template( 'highlights_date.html', highlights=highlights, date=parsed_date, dates_with_highlights=set(dates_with_highlights)) finally: session.close()
def stats_duels(): session = DBManager.create_session() data = { 'top_5_winners': session.query(UserDuelStats).order_by( UserDuelStats.duels_won.desc())[:5], 'top_5_points_won': session.query(UserDuelStats).order_by(UserDuelStats.profit.desc())[:5], 'top_5_points_lost': session.query(UserDuelStats).order_by(UserDuelStats.profit.asc())[:5], 'top_5_losers': session.query(UserDuelStats).order_by( UserDuelStats.duels_lost.desc())[:5], 'top_5_winrate': session.query(UserDuelStats).filter( UserDuelStats.duels_won >= 5).order_by( UserDuelStats.winrate.desc())[:5], 'bottom_5_winrate': session.query(UserDuelStats).filter( UserDuelStats.duels_lost >= 5).order_by( UserDuelStats.winrate.asc())[:5], } try: return render_template('stats_duels.html', **data) finally: session.close()
def get_yelp_ratings(business_id): """ Returns yelp ratings and related yelp information for a food truck with a given business id """ # OAuth credentials CONSUMER_KEY = os.environ.get('YELP_CONSUMER_KEY') CONSUMER_SECRET = os.environ.get('YELP_CONSUMER_SECRET') TOKEN = os.environ.get('YELP_TOKEN') TOKEN_SECRET = os.environ.get('YELP_TOKEN_SECRET') session = rauth.OAuth1Session(consumer_key=CONSUMER_KEY, consumer_secret=CONSUMER_SECRET, access_token=TOKEN, access_token_secret=TOKEN_SECRET) url = "http://api.yelp.com/v2/business/{0}".format(business_id) print "**** url", url try: request = session.get(url) # transform json api response into dictionary data = request.json() except ValueError: return False session.close() return data
def asteroid_impacting(): session = Session(engine) results = session.query(asteroid_impacts.object_name, asteroid_impacts.period_start, asteroid_impacts.period_end, asteroid_impacts.possible_impacts, asteroid_impacts.cumulative_impact_probability, asteroid_impacts.asteroid_velocity, asteroid_impacts.asteroid_magnitude, asteroid_impacts.asteroid_diameter_km, asteroid_impacts.cumulative_palermo_scale, asteroid_impacts.maximum_palermo_scale).all() session.close() return jsonify(results)
def get_data(): model_id1=request.form['suggestion1'] model_id2=request.form['suggestion2'] model_id3=request.form['suggestion3'] client_id = request.form['client_id'] df=recommender.update_history2(client_id, model_id1, model_id2, model_id3) listToWrite = df.to_dict(orient='records') print("***********************************") print(listToWrite) Session = sessionmaker(bind=engine) session = Session() metadata = sqlalchemy.schema.MetaData(bind=engine,reflect=True) table = sqlalchemy.Table("inbox_table", metadata, autoload=True) # Inser the dataframe into the database in one bulk conn = engine.connect() conn.execute(table.insert(), listToWrite) # Commit the changes session.commit() # Close the session session.close() #get the other stuff to repopulate the page return redirect(url_for("index"))
def get(self): args = parser.events_get_parser.parse_args(strict=True) session = g.Session() try: events = session.query(db.Events).filter( db.Events.related_class_id == args.get("class_id")).all() msg = { "i_status": 1, "err_code": -1, "msg": "", "deliver": json.dumps(events, cls=db.AlchemyEncoder) } except Exception as e: l.error(e) session.rollback() msg = { "i_status": 0, "err_code": 15, "msg": "Events query error.", "deliver": [] } finally: session.close() return msg
def statisticsReport(): startDate = request.args.get("startDate") endDate = request.args.get("endDate") if not startDate or not endDate: abort(404, description="Dates must be defined to export CSV report") fx_product = "SPOT" startDate = datetime.strptime(startDate, "%Y-%m-%d").date() endDate = datetime.strptime(endDate, "%Y-%m-%d").date() session = SessionMaker() column_names, transaction_report = get_transactions_report( session, fx_product, startDate, endDate) session.close() reports_dir = os.getenv("RFX_HISTORY_DIR") filename = f"{fx_product}_report_{startDate}_{endDate}.csv" filepath = f"{reports_dir}/{filename}" try: with open(filepath, 'w') as csvfile: writer = csv.DictWriter(csvfile, fieldnames=column_names) writer.writeheader() for transaction in transaction_report: writer.writerow(transaction) except IOError: print("I/O error") return send_from_directory(directory=reports_dir, filename=filename, as_attachment=True, attachment_filename=filename)
def set_garbage(): j = sanitize_set_garbage(request.get_json(force=True,silent=True)) if not j: example = json.dumps({ "id":"123", "price_bonus":12.34 }) return json.dumps({ 'error': ('provide a valid json body! example: %s' % (example,)) }), 400 session = db.Session() print "bla" tid = j['id'] try: task = session.query(db.OpenTask).filter(db.OpenTask.id == tid).one() except NoResultFound: session.close() return json.dumps({ 'error': 'id does not exists' }), 400 except MultipleResultsFound: session.close() return json.dumps({ 'error': 'more than one result found' }), 400 print(task.id) session.delete(task) session.commit() result = { 'error': None, 'success': True }, 200 return json.dumps(result)
def pay(order_name, order_amount): # Create payment # Stripe payment button calls this print("\n\n\n\n\n\n\n\n\n\n\n\n") # Create stripe charge customer = stripe.Customer.create(email=request.form['stripeEmail'], source=request.form['stripeToken']) charge = stripe.Charge.create(customer=customer.id, amount=int(order_amount), currency='usd', description=order_name) print("\n pay " + order_amount + " for " + order_name + " \n") # Add order to database engine = create_engine('sqlite:///drinks_paid.db', echo=True) Session = sessionmaker(bind=engine) session = Session() user = User(order_name) session.add(user) session.commit() session.close() # Push to thanks page return redirect(url_for('thanks'))
def set_bonus(): j = sanitize_set_bonus(request.get_json(force=True,silent=True)) if not j: example = json.dumps({ "id":"123", "price_bonus":12.34 }) return json.dumps({ 'error': ('provide a valid json body! example: %s' % (example,)) }), 400 session = db.Session() tid = j['id'] if session.query(db.OpenTask).filter(db.OpenTask.id == tid).count() == 0: session.close() return json.dumps({ 'error': 'id does not exists' }), 400 else: session.close() session = db.Session() tasks = session.query(db.OpenTask).filter(db.OpenTask.id == tid) for task in tasks: task.price_bonus = j['price_bonus'] session.commit() result = { 'error': None, 'success': True }, 200 return json.dumps(result) session.commit()
def delete(self): if not g.get('admin'): msg = { "i_status": 0, "err_code": 11, "msg": "Not login." } return msg args = class_delete_parser.parse_args(strict=True) session = g.Session() try: Class2Del = session.query(db.Classes).filter(db.Classes.id == args.get('class_id')).one() session.delete(Class2Del) session.commit() msg = { "i_status": 1, "err_code": -1, "msg": "" } except Exception as e: l.error(e) session.rollback() msg = { "i_status": 0, "err_code": 18, "msg": "Class delete err" } finally: session.close() return msg
def get_user(): session = Session() type_utilisateur = session.query(Type_utilisateur).order_by( desc(Type_utilisateur.id)) session.close() return render_template('user_data.html', typeUtilisateur=type_utilisateur)
def flush(self): session = Session() infohashlist = [z.info_hash for z in self.bulkSearchHash] dhtHashStoreList = session.query(SearchHash).filter(SearchHash.info_hash in infohashlist).all() infohashlistStored = [z.info_hash for z in dhtHashStoreList] infohashlistNoFile = [z.info_hash for z in dhtHashStoreList if not z.filescount or z.filescount == 0] dhtHashNewList = [z for z in self.bulkSearchHash if not z.info_hash in infohashlistStored ] for y in dhtHashStoreList: for z in self.bulkSearchHash: if z.info_hash == y.info_hash : y.last_seen = z.last_seen y.filescount = z.filescount = len(files) break self.bulkSearchHash = dhtHashStoreList + dhtHashNewList session.bulk_save_objects(self.bulkSearchHash) if len(self.bulkTorFiles) > 0: self.bulkTorFiles = [z for z in self.bulkTorFiles if z.infohash not in infohashlistStored or z.infohash in infohashlistNoFile] session.bulk_save_objects(self.bulkTorFiles) session.commit() session.close() self.bulkTorFiles = [] self.bulkSearchHash = []
def getMessages(): session = db.getSession(engine) rdmsg = session.query(entities.Message) session.close() contenido = rdmsg[:] return Response(json.dumps(contenido, cls=connector.AlchemyEncoder), mimetype='application/json')
def new(): form = PromiseForm(request.form) if request.method == 'POST' and form.validate(): print("Type of the input", type(form.startDate.data), form.startDate.data) newPromise = Promise( #generate a unique ID for the task by hashing the concatenation of the taskname, #details and references (it may be possible to have two tasks with the same name) taskID= hashlib.sha256(bytes(str(form.task.data) + str(form.details.data) + str(form.references.data), encoding='utf-8')).hexdigest(), task=form.task.data, progress=round(form.progress.data, 2), startdate=form.startDate.data, enddate=form.endDate.data, details=form.details.data, references=form.references.data, approved=False ) #add to sql db session = DBSession() session.add(newPromise) session.commit() session.close() return render_template('newpromise.html', form=PromiseForm(), complete=True, home=url_for('home')) flash(form.errors) return render_template('newpromise.html', form=PromiseForm(), complete=False)
def getJson(cypher_sql): driver = GraphDatabase.driver(bolt_conncect_string, auth=(user, password)) with driver.session() as session: result = session.run(cypher_sql).data() session.close() return jsonify(result)
def view(): session = EventSession() # fixes need to query: join multiple tables sorted_portfolios = session.query( Portfolio.rank, Portfolio.name, Committee.name, Student.name, School.name, School.grade).join( Portfolio.committee, Portfolio.student, Student.school).filter(Portfolio.student != None).order_by( School.id).all() extra_portfolios = session.query( Portfolio.rank, Portfolio.name, Committee.name).join(Portfolio.committee).filter( Portfolio.student == None).order_by(Portfolio.committee_id).all() schools = session.query(School).all() unsorted_schools = [] for school in schools: portfolio = session.query(Portfolio).join( Portfolio.student, Student.school).filter(School.id == school.id).first() if portfolio == None: unsorted_schools.append( [School.id, School.name, School.grade, School.delegation_size]) session.close() return render_template("view.html", sorted_portfolios=sorted_portfolios, extra_portfolios=extra_portfolios, schools=unsorted_schools)
def dates_completed_goals(): now = dt.datetime.now() rescue_time = RescueTime() toggl = Toggl().get_daily_pomodoros() moves = Moves() total_pomodoros = sum(toggl.values()) #Check that we are almost done the day, we use two minutes in case the url #doesn't get pinged during the 59th minute for whatever reason if now.hour == 23 and now.minute == 59: if moves.get_current_days_steps() >= STEPS_GOAL and \ total_pomodoros >= FOCUS_GOAL and \ rescue_time.get_current_days_data()["unproductive_hours"] < 1: now = time.time() todayDict = {str(now) : 100} try: goalCompletion = GoalCompletion(date=todayDict) db.session.add(goalCompletion) db.session.commit() except Exception as e: print(e) print("Unable to add items to database") try: session = db.session() rows = session.execute("SELECT * FROM dates_completed_goals") datesDict={} for row in rows: datesDict={**datesDict, **row[0]} session.close() return jsonify(datesDict) except psycopg2.DatabaseError as e: print('Error %s') % e sys.exit(1)
def tweet(star_id): session = db.create_scoped_session() try: query = session.query(Star) star = query.get(star_id) if star.owner.twitterUser: status = '#GoldStar: @' + star.owner.twitterUser + ' for ' + star.description + ' #' + star.hashtag + ' www.Goldstars.me/star/' + str(star_id) else: fullName = star.owner.firstName + ' ' + star.owner.lastName status = '#GoldStar: ' + fullName + ' for ' + star.description + ' #' + star.hashtag + ' www.Goldstars.me/star/' + str(star_id) if len(status) > 140: cutDescriptionBy = len(status) - 135 cutDescriptionBy = len(star.description) - cutDescriptionBy if star.owner.twitterUser: status = '#GoldStar: @' + star.owner.twitterUser + ' for ' + star.description[0:cutDescriptionBy] + ' #' + star.hashtag + ' www.Goldstars.me/star/' + str(star_id) else: status = '#GoldStar: ' + fullName + ' for ' + star.description[0:cutDescriptionBy] + ' #' + star.hashtag + ' www.Goldstars.me/star/' + str(star_id) resp = twitter.post('statuses/update.json', data = {'status': status}) return True except Exception as ex: userQuery = session.query(User) user = userQuery.get(star.owner.id) user.twitterUser = None user.oauth_secret = None user.oauth_token = None session.commit() finally: session.close()
def post(self): if g.get('admin'): msg = { "i_status": 0, "err_code": 5, "msg": "Already login." } return msg args = event_post_parser.parse_args(strict=True) session = g.Session() try: event = db.Events( related_class_id = args.get("related_class_id"), event_type = args.get("event_type"), event_title = args.get("event_title"), event_msg = args.get("event_msg"), ) session.add(event) msg = { "i_status": 1, "err_code": -1, "msg": "", } except Exception as e: l.error(e) session.rollback() msg = { "i_status": 0, "err_code": 13, "msg": "Event add err.", } finally: session.close() return msg
def getdata_timeline(): """Video streaming home page.""" session = Session() sites = session.query(Sites).limit(10).order_by(desc(Sites.id)) session.close() return render_template('data.html', sites=sites)
def upload(): if request.method == 'GET': return render_template('uploadForm.html') elif request.method == 'POST': file = request.files['file'] num = int(request.form['num']) print(num) # get the filename #filename = secure_filename(file.filename) # save it to static folder file.save("myProject/static/file/client.csv") Session = sessionmaker(bind=engine) session = Session() conn = engine.connect() try: conn.execute("DROP TABLE inbox_table") except sqlalchemy.exc.OperationalError: print("The table has been deleted") try: conn.execute("DROP TABLE dropdown_table_new") except sqlalchemy.exc.OperationalError: print("The table has been deleted") # Commit the changes session.commit() # Close the session session.close() # generate new tables g = generate("client.csv", "famillesall_04-25-2019.csv", num) g.gen() return redirect(url_for('index'))
def insert(): rdata = request.get_json() points = rdata["points"] db_points = [logdb.log_value.from_obj(obj) for obj in points] session = current_app.config["logger.db"]() session.add_all(db_points) session.commit() session.close() return ""
def decks(): session = DBManager.create_session() top_decks = [] for deck in session.query(Deck).order_by(Deck.last_used.desc(), Deck.first_used.desc())[:25]: top_decks.append(deck) session.close() return render_template('decks/all.html', top_decks=top_decks, deck_class=None)
def sessionScope(sessionClass=Session): session = sessionClass() try: yield session session.commit() except: session.rollback() raise finally: session.close()
def with_db(Session): session = Session() try: yield session except: session.rollback() raise else: session.commit() finally: session.close()
def load_user(userid): session = dbsession() try: user = session.query(User).filter(User.user_id==int(userid)).one() except: user = None session.close() return user
def stats(): top_5_commands = sorted(bot_commands_list, key=lambda c: c.data.num_uses if c.data is not None else -1, reverse=True)[:5] if 'linefarming' in modules: session = DBManager.create_session() top_5_line_farmers = session.query(User).order_by(User.num_lines.desc())[:5] session.close() else: top_5_line_farmers = [] return render_template('stats.html', top_5_commands=top_5_commands, top_5_line_farmers=top_5_line_farmers)
def points(): custom_content = custom_web_content.get('points', '') try: custom_content = Markup(markdown.markdown(custom_content)) except: log.exception('Unhandled exception in def index') session = DBManager.create_session() top_30_users = [] for user in session.query(User).order_by(User.points.desc())[:30]: top_30_users.append(user) session.close() return render_template('points.html', top_30_users=top_30_users, custom_content=custom_content)
def highlight_id(date, highlight_id, highlight_title=None): session = DBManager.create_session() highlight = session.query(StreamChunkHighlight).filter_by(id=highlight_id).first() if highlight is None: session.close() return render_template('highlight_404.html'), 404 else: stream_chunk = highlight.stream_chunk stream = stream_chunk.stream session.close() return render_template('highlight.html', highlight=highlight, stream_chunk=stream_chunk, stream=stream)
def get_twitter_token(): session = db.create_scoped_session() try: query = session.query(User) user = query.get(current_user.get_id()) if user is not None and user.oauth_token is None and user.oauth_secret is None: returnToken = None elif user is not None: returnToken = str(user.oauth_token), str(user.oauth_secret) else: returnToken = None return returnToken finally: session.close()
def get_yelp_results(businessID): # Session setup session = rauth.OAuth1Session( consumer_key = yelp_consumer_key, consumer_secret = yelp_consumer_secret, access_token = yelp_token, access_token_secret = yelp_token_secret) request = session.get('http://api.yelp.com/v2/business/' + businessID) # Transform JSON API response into Python dictionary data = request.json() session.close() return data
def highlights(): session = DBManager.create_session() dates_with_highlights = [] highlights = session.query(StreamChunkHighlight).order_by(StreamChunkHighlight.created_at_with_offset.desc()).all() for highlight in highlights: dates_with_highlights.append(datetime.datetime( year=highlight.created_at.year, month=highlight.created_at.month, day=highlight.created_at.day)) try: return render_template('highlights.html', highlights=highlights[:10], dates_with_highlights=set(dates_with_highlights)) finally: session.close()
def stats_duels(): session = DBManager.create_session() data = { 'top_5_winners': session.query(UserDuelStats).order_by(UserDuelStats.duels_won.desc())[:5], 'top_5_points_won': session.query(UserDuelStats).order_by(UserDuelStats.profit.desc())[:5], 'top_5_points_lost': session.query(UserDuelStats).order_by(UserDuelStats.profit.asc())[:5], 'top_5_losers': session.query(UserDuelStats).order_by(UserDuelStats.duels_lost.desc())[:5], 'top_5_winrate': session.query(UserDuelStats).filter(UserDuelStats.duels_won >= 5).order_by(UserDuelStats.winrate.desc())[:5], 'bottom_5_winrate': session.query(UserDuelStats).filter(UserDuelStats.duels_lost >= 5).order_by(UserDuelStats.winrate.asc())[:5], } try: return render_template('stats_duels.html', **data) finally: session.close()
def user_profile(username): session = DBManager.create_session() user = session.query(User).filter_by(username=username).one_or_none() if user is None: return render_template('no_user.html'), 404 rank = session.query(func.Count(User.id)).filter(User.points > user.points).one() rank = rank[0] + 1 user.rank = rank user_duel_stats = session.query(UserDuelStats).filter_by(user_id=user.id).one_or_none() try: return render_template('user.html', user=user, user_duel_stats=user_duel_stats) finally: session.close()
def index(): session = current_app.config["logger.db"]() query = session.query(logdb.log_value) for key, value in request.args.iteritems(): tag_alias = aliased(logdb.log_tag) query = query.join(tag_alias) query = query.filter(tag_alias.tag_key == key) query = query.filter(tag_alias.tag_value == value) query = query.filter(logdb.log_value.measurement == "log") query = query.order_by(logdb.log_value.time.desc()).limit(100) output = "" for row in query.all(): output += line(row) + "<BR>" session.close() return output
def save_place(ptolemy_id): try: if request.form['submit'] == 'Submit': session = models.create_session(models.DB_URL) place = session.query(models.Place).get(ptolemy_id) place.ptolemy_name = request.form['ptolemy_name'] place.modern_name = request.form['modern_name'] ptolemy_lat, ptolemy_lon = [float(s) for s in request.form['ptolemy_coords'].split(' ')] place.ptolemy_point = from_shape(Point(ptolemy_lon, ptolemy_lat)) if len(request.form['modern_coords'].split(' ')) > 1: modern_lat, modern_lon = [float(s) for s in request.form['modern_coords'].split(' ')] place.modern_point = from_shape(Point(modern_lon, modern_lat)) else: place.modern_point = None place.disposition = request.form['disposition'] session.add(place) session.commit() session.close() return redirect(url_for('main.show_place', ptolemy_id=ptolemy_id)) except Exception as e: current_app.logger.error(e.message, exc_info=e)
def city_search(): get_location = request.form["location"] params = {"term": "sushi", "radius_filter": "2000"} params["location"] = [get_location] #Obtain these from Yelp's manage access page session = rauth.OAuth1Session( consumer_key = consumer_key ,consumer_secret = consumer_secret ,access_token = token ,access_token_secret = token_secret) get_data = session.get("http://api.yelp.com/v2/search",params=params) #Transforms the JSON API response into a Python dictionary data = get_data.json() session.close() return render_template('results.html', data=data)
def highlight_list_date(date): # Make sure we were passed a valid date try: parsed_date = datetime.datetime.strptime(date, '%Y-%m-%d') except ValueError: # Invalid date return redirect('/highlights/', 303) session = DBManager.create_session() dates_with_highlights = [] highlights = session.query(StreamChunkHighlight).filter(cast(StreamChunkHighlight.created_at, Date) == parsed_date).order_by(StreamChunkHighlight.created_at.desc()).all() for highlight in session.query(StreamChunkHighlight): dates_with_highlights.append(datetime.datetime( year=highlight.created_at.year, month=highlight.created_at.month, day=highlight.created_at.day)) try: return render_template('highlights_date.html', highlights=highlights, date=parsed_date, dates_with_highlights=set(dates_with_highlights)) finally: session.close()
def download_region(region_slug): try: session = models.create_session(models.DB_URL) region = session.query(models.Region).filter_by(slug=region_slug).first() outfile = StringIO.StringIO() writer = unicodecsv.writer(outfile) header = ('ptolemy_id', 'ptolemy_name', 'modern_name', 'ptolemy_lat', 'ptolemy_lon', 'modern_lat', 'modern_lon', 'disposition') writer.writerow(header) for place in region.places: ptolemy_coords = to_shape(place.ptolemy_point) ptolemy_lat = ptolemy_coords.y ptolemy_lon = ptolemy_coords.x if place.modern_point is not None: modern_coords = to_shape(place.modern_point) modern_lat = modern_coords.y modern_lon = modern_coords.x else: modern_coords = None modern_lat = None modern_lon = None row = (place.ptolemy_id, place.ptolemy_name, place.modern_name, ptolemy_lat, ptolemy_lon, modern_lat, modern_lon, place.disposition) writer.writerow(row) response = make_response(outfile.getvalue()) response.headers['Content-Disposition'] = 'attachment; filename=%s.csv' % (region.slug) response.headers['Content-type'] = 'text/csv' session.close() return response except Exception as e: current_app.logger.error(e.message, exc_info=e)
def init_app(self, app, **kwargs): self._init_flask(app) self._init_conf(app, **self._conf_args(**kwargs)) self._init_engine() if app.secret_key is None: app.secret_key = self._generate_secret_key() app.extensions["wok"] = self.engine db_path = os.path.join(self.engine.work_path, "server.db") new_db = not os.path.exists(db_path) engine = db.create_engine(uri="sqlite:///{}".format(db_path)) session = db.Session() db_init(engine, session, new_db) session.commit() session.close() self._initialized = True if self._start_engine: self.start_engine()
def shutdown_session(exception=None): if session is not None: session.close()