def article(article_id): cur = get_db().cursor() cur.execute(str(sqlpuzzle.select('title', 'text').from_('article').where({'id': article_id}))) row = cur.fetchone() article = { 'title': row[0], 'text': row[1], } return render_template('article/detail.html', article=article)
def add_article(): form = ArticleForm(request.form) if request.method == 'POST' and form.validate(): sql = sqlpuzzle.insert_into('article').values({ 'title': form.title.data, 'text': form.text.data, }) cur = get_db().cursor() cur.execute(str(sql)) return redirect(url_for('article_page.articles')) return render_template('article/add.html', form=form)
def save_message(src, msg): ''' stores the given message to the database ''' db = get_db() db.execute('INSERT INTO communication (source, message)' ' VALUES (?,?)', (src, msg)) db.commit()
def complete_order(orderId): ''' marks a pending order as complete ''' db = get_db() # update custOrder table db.execute('UPDATE custOrder SET completed=?' ' WHERE id=?', (1, orderId)) db.commit()
def get_total_failed_requests(self): db = get_db() row = db.execute( "SELECT COUNT(*) FROM LOGS WHERE `x-edge-response-result-type` lIKE '%error%'" ).fetchone() return int((row and row[0]) or 0)
def is_log_imported(self, file_name): db = get_db() row = db.execute("SELECT 1 FROM LOGFILE_NAMES WHERE file_name = ?", (file_name, )).fetchone() return int((row and row[0]) or 0)
def _register_log_file(self, logname): db = get_db() db.execute("INSERT INTO LOGFILE_NAMES (file_name) values (?)", (self.logname, )) db.commit()
def create_app(test_config=None): app = Flask(__name__, instance_relative_config=True) app.config.from_mapping() CORS(app) try: os.makedirs(app.instance_path) except OSError: pass @app.errorhandler(400) def not_found(error): return make_response(jsonify(error='Not found'), 400) @app.errorhandler(500) def error_500(error): return make_response({}, 500) db.get_db(mongo=mongo, app=app) from app.api import fetch from app.api import balance app.register_blueprint(fetch.bp) app.register_blueprint(balance.bp) #--------Schedulers timing and days functionality------------ auto_fetch_scheduler = BackgroundScheduler() auto_fetch_scheduler.add_job(auto_fetch, trigger='cron', day_of_week='mon-sat', hour=11, minute=41) auto_fetch_scheduler.start() ''' pgp_verification_scheduler = BackgroundScheduler() pgp_verification_scheduler.add_job(pgp_verification, trigger='cron', day_of_week='mon-sat', hour=13,minute=7) pgp_verification_scheduler.start() ''' ''' heist_associated_fetch_scheduler = BackgroundScheduler() heist_associated_fetch_scheduler.add_job(heist_associated_fetch, trigger='cron', day_of_week='mon-sat', hour=12,minute=28) heist_associated_fetch_scheduler.start() ''' tx_two_yearold_scheduler = BackgroundScheduler() tx_two_yearold_scheduler.add_job(tx_two_yearold, trigger='cron', day_of_week='sat', hour=14, minute=2) tx_two_yearold_scheduler.start() risk_score_by_safename_scheduler = BackgroundScheduler() risk_score_by_safename_scheduler.add_job(risk_score_by_safename, trigger='cron', day_of_week='mon-sat', hour=14, minute=38) risk_score_by_safename_scheduler.start() risk_score_by_heist_scheduler = BackgroundScheduler() risk_score_by_heist_scheduler.add_job(risk_score_by_heist, trigger='cron', day_of_week='sat', hour=12, minute=59) risk_score_by_heist_scheduler.start() tx_notification_scheduler = BackgroundScheduler() #tx_notification_scheduler.add_job(tx_notification, trigger='cron', day_of_week='mon-sat', hour=15, minute=25) tx_notification_scheduler.add_job(tx_notification, trigger='interval', minutes=7) tx_notification_scheduler.start() #tx_notification_scheduler.add_job(tx_notification, trigger='interval', minutes=tx_notification_scheduler_minute) #tx_notification_scheduler.add_job(tx_notification, trigger='interval', hours=20) #tx_notification_scheduler.add_job(tx_notification, trigger='interval', seconds=60) risk_score_scheduler = BackgroundScheduler() risk_score_scheduler.add_job(risk_score, trigger='cron', day_of_week='mon', hour=12, minute=9) risk_score_scheduler.start() profile_risk_score_scheduler = BackgroundScheduler() profile_risk_score_scheduler.add_job(profile_risk_score, trigger='cron', day_of_week='fri', hour=15, minute=17) profile_risk_score_scheduler.start() invoice_notification_scheduler = BackgroundScheduler() invoice_notification_scheduler.add_job(invoice_notification, trigger='cron', day_of_week='mon', hour=13, minute=5) invoice_notification_scheduler.start() Top_user_percentage_scheduler = BackgroundScheduler() Top_user_percentage_scheduler.add_job(Top_user_percentage, trigger='cron', day_of_week='mon-sat', hour=11, minute=00) Top_user_percentage_scheduler.start() try: return app except: auto_fetch_scheduler.shutdown() # pgp_verification_scheduler.shutdown() heist_associated_fetch_scheduler.shutdown() tx_two_yearold_scheduler.shutdown() risk_score_by_safename_scheduler.shutdown() risk_score_by_heist_scheduler.shutdown() tx_notification_scheduler.shutdown() risk_score_scheduler.shutdown() invoice_notification_scheduler.shutdown() profile_risk_score_scheduler.shutdown() Top_user_percentage_scheduler.shutdown()
def delete(id): get_post(id) db = get_db() db.execute('DELETE FROM post WHERE id = ?', (id, )) db.commit() return redirect(url_for('blog.index'))
def create(): if request.method == 'POST': title = request.form['title'] image_url = request.form['image_url'] body = request.form['body'] error = None if not title: error = 'Title is required.' if error is not None: flash(error) else: db = get_db() db.execute( 'INSERT INTO post (title, body, image_url, author_id)' ' VALUES (?, ?, ?, ?)', (title, body, image_url, g.user['id']) ) db.commit() return redirect(url_for('blog.index')) return render_template('blog/create.html') def get_post(id, check_author=True): post = get_db().execute( 'SELECT p.id, title, body, image_url, created, author_id, username' ' FROM post p JOIN user u ON p.author_id = u.id' ' WHERE p.id = ?', (id,) ).fetchone() if post is None: abort(404, "Post id {0} doesn't exist.".format(id)) if check_author and post['author_id'] != g.user['id']: abort(403) return post @bp.route('/<int:id>/update', methods=('GET', 'POST')) @login_required def update(id): post = get_post(id) if request.method == 'POST': title = request.form['title'] image_url = request.form['image_url'] body = request.form['body'] error = None if not title: error = 'Title is required.' if error is not None: flash(error) else: db = get_db() db.execute( 'UPDATE post SET title = ?, body = ?, image_url = ? WHERE id = ?', (title, body, image_url, id) ) db.commit() return redirect(url_for('blog.index')) return render_template('blog/update.html', post=post) @bp.route('/<int:id>/delete', methods=('POST',)) @login_required def delete(id): get_post(id) db = get_db() db.execute('DELETE FROM post WHERE id = ?', (id,)) db.commit() return redirect(url_for('blog.index'))
def index(): db = get_db() posts = db.execute('SELECT p.id, title, body, created, author_id, username' ' FROM post p JOIN user u ON p.author_id = u.id' ' ORDER BY created DESC').fetchall() return render_template('blog/index.html', posts=posts)
def cron(): projectid = request.args.get('id') db = get_db() project = db.execute( 'SELECT id, name FROM projects WHERE id = ? and owner = ?', (projectid, session['username'], ) ).fetchone() if not project: return render_template('info.html', username=session['username'], info='Not found') if request.args.get('limit') in ['10', '20', '30', '50', '100']: limit = int(request.args.get('limit')) else: limit = 10 if 'page' not in request.args: page = 1 else: try: page = int(request.args.get('page')) except ValueError: page = 1 if 'search' not in request.args: search = '.*' else: search = request.args.get('search').strip() if request.args.get('period') in ["1", "2", "3", "4", "5"]: period = request.args.get('period') else: period = '%' if request.args.get('status') == "On": status = 1 status_t = "On" elif request.args.get('status') == "Off": status = 0 status_t = "Off" else: status = "%" status_t = "All" crons = db.execute( 'SELECT * FROM crontab WHERE project = ? AND domain REGEXP ? AND status LIKE ? AND period LIKE ? ORDER BY rowid DESC LIMIT ? OFFSET ?', (projectid, search, status, period, limit, limit * (page - 1), ) ).fetchall() allcrons = db.execute( 'SELECT * FROM crontab WHERE project = ? AND domain REGEXP ? AND status LIKE ? AND period LIKE ? ORDER BY rowid DESC', (projectid, search, status, period, ) ).fetchall() if len(allcrons) % limit == 0: pages = int(len(allcrons) / limit) else: pages = int(len(allcrons) / limit + 1) return render_template('cron/cron.html', username=session['username'], project=project, rows=crons, limit=limit, page=page, search=search, period=period, pages=pages, status=status_t)
def winners(): class Player: def __init__(self): self.uuid = "" self.name = "" self.score = 0 self.lost = 0 def parse_result(result, best_score): player = Player() player.uuid = result['user_uuid'] player.name = uuid_players_dict[player.uuid] player.score = result['score'] player.lost = result['score'] - best_score return player def have_player_played(players_sql): players_uuids = [] for player in players_in_game: players_uuids.append(player['user_uuid']) user_uuid = g.user['uuid'] if user_uuid in players_uuids: return True else: return False def get_date(datestamp): (year, month, day) = str(datestamp).split("-") return (day, get_month(month) + " " + year) db = get_db() results = [] uuid_players_dict = dict() # Prepare the players uuid-username dict users_db = db.execute('SELECT * FROM user').fetchall() for user in users_db: uuid_players_dict[user['uuid']] = user['username'] # Get list of all games games_db = db.execute('SELECT * FROM game ORDER BY datestamp DESC').fetchall() # For every game for game in games_db: # Create an instance of GameEntry game_entry = GameEntry() game_entry.id = game['id'] game_entry.uuid = game['uuid'] game_entry.date = get_date(game['datestamp']) game_entry.map_url = get_url_to_map(game['map']) players_in_game_formula = "SELECT * FROM result WHERE game_uuid = '{}' ORDER BY score DESC".format(game_entry.uuid) players_in_game = db.execute(players_in_game_formula).fetchall() game_entry.no_players = len(players_in_game) # Check if current player played that map game_entry.have_I_played = have_player_played(players_in_game) best_results = players_in_game[:3] best_score = best_results[0]['score'] if (len(best_results) > 0): game_entry.first_place = parse_result(best_results[0], best_score) if (len(best_results) > 1): game_entry.second_place = parse_result(best_results[1], best_score) if (len(best_results) > 2): game_entry.third_place = parse_result(best_results[2], best_score) # Parsing link to challenge game_hash_obj = db.execute("SELECT * FROM link WHERE game_uuid = '{}'".format(game_entry.uuid)).fetchone() if game_hash_obj: (game_entry.game_url, game_entry.results_url) = get_url_to_challenge(game_hash_obj['game_hash']) results.append(game_entry) return render_template('result/winners.html', results=results)
def get_name_from_uuid(uuid): db = get_db() user = db.execute("SELECT * FROM user WHERE uuid = '{}'".format(uuid)).fetchone() if user: return user['username'] return "unknown"
def get_uuid_from_name(self): db = get_db() user = db.execute("SELECT * FROM user WHERE username = '******'".format(self.username)).fetchone() if user: self.user_uuid = user['uuid']
def check_if_user_exists(username): db = get_db() formula = "SELECT * FROM user WHERE username = '******'".format(username) result = db.execute(formula).fetchone() return result
def get_all(cls): return get_db().query(cls).order_by(cls.id).all()
def update(user_id, request_data): id = request_data.get('id') title = request_data.get('title') start_datetime_string = request_data.get('start_datetime') end_datetime_string = request_data.get('end_datetime') contacts = request_data.get('contacts') description = request_data.get('description') notes = request_data.get('notes') db = get_db() error = None if id is None: error = 'Meeting ID is required' else: error = check_meeting(user_id, request_data) if error is None: meeting = db.execute( 'SELECT * FROM meeting WHERE id = ? AND user_id = ?', (id, user_id) ).fetchone() if meeting is None: error = 'There is no meeting with such ID' if error is None: db.execute( 'UPDATE meeting SET ' + 'title = ?, ' + 'start_datetime = ?, ' + 'end_datetime = ?, ' + 'description = ?, ' + 'notes = ? ' + 'WHERE id = ? ' + 'AND user_id = ?', ( title, start_datetime_string, end_datetime_string, description, notes, id, user_id, ) ) existing_contacts_ids = db.execute( 'SELECT contact.id ' 'FROM contact ' 'JOIN meetings_to_contacts AS map ON contact.id = map.contact_id ' 'WHERE contact.user_id = ? AND map.meeting_id = ?', (user_id, id) ).fetchall() existing_contacts_ids = set( [dict(contact_id)['id'] for contact_id in existing_contacts_ids] ) new_contact_ids = set(map(lambda contact: contact['id'], contacts)) for contact_id in existing_contacts_ids.difference(new_contact_ids): db.execute( 'DELETE from meetings_to_contacts ' 'WHERE meeting_id = ? AND contact_id = ?', (id, contact_id) ) for contact_id in new_contact_ids.difference(existing_contacts_ids): db.execute( 'INSERT INTO meetings_to_contacts (meeting_id, contact_id) ' 'VALUES (?, ?)', (id, contact_id) ) db.commit() return { 'status': 200, 'success': True, 'error': error, 'data': None } else: return { 'status': 400, 'success': False, 'error': error, 'data': None }
def get_by_id(cls, id): return get_db().query(cls).filter_by(id = id).one_or_none()
def _set_log_id(self): db = get_db() row = db.execute("SELECT max(id) FROM LOGFILE_NAMES").fetchone() if row and len(row) > 0: self.id = row[0]
def get_restaurant_menu(cls, id): return get_db().query(cls).filter(MenuItem.restaurant_id == id).order_by(desc(cls.id)).all()
def get_bytes_for_cdn_request_type(self, cdn_request_type): db = get_db() row = db.execute( "SELECT SUM(`cs-bytes`+`sc-bytes`) FROM LOGS WHERE `x-edge-response-result-type`= ?", (cdn_request_type.capitalize(), )).fetchone() return int((row and row[0]) or 0)
def get_all(): return get_db().query(User).all()
def get_total_success_requests(self): db = get_db() row = db.execute( "SELECT COUNT(*) FROM LOGS WHERE `sc-status` = 200").fetchone() return int((row and row[0]) or 0)
def get_by_id(cls, facebook_id): return get_db().query(User).filter(cls.fb_id == facebook_id).one_or_none()
def delete_item(id): ''' deletes an item in the database given its id ''' db = get_db() db.execute('DELETE FROM item WHERE id=?', (id, )) db.commit()
def save(self): ses = get_db() ses.add(self) ses.commit()
def pay_bill(orderIDs): ''' marks the given orders as paid ''' db = get_db() for id in orderIDs: db.execute('UPDATE custOrder SET paid=? WHERE id=?', (1, id)) db.commit()
def delete(self): ses = get_db() ses.delete(self) ses.commit()
def articles(): cur = get_db().cursor() cur.execute(str(sqlpuzzle.select('id', 'title').from_('article'))) rows = cur.fetchall() articles = [{'id': row[0], 'title': row[1]} for row in rows] return render_template('article/list.html', articles=articles)
def get_all(cls): return get_db().query(Restaurant).order_by(cls.id.desc()).all()
def get_by_id(id): return get_db().query(Restaurant).filter_by(id = id).one_or_none()
from flask_login import UserMixin from werkzeug.security import generate_password_hash, check_password_hash from app import login_manager from app.db import get_db db = get_db() class UsersToFilms(db.Model): """ Create an Films table """ # Ensures table will be named in plural and not in singular # as is the name of the model __tablename__ = 'users_to_films' id = db.Column(db.Integer, primary_key=True) user_id = db.Column('user_id', db.Integer, db.ForeignKey('users.id')) film_id = db.Column('film_id', db.Integer, db.ForeignKey('films.id'))