def subscribe(): error = None if request.method == 'POST': username = session.get('user') subscribee = request.form['subscribee'] s = Subscription(username, subscribee) db_session().add(s) db_session().commit() flash('You subscribed!') return redirect(url_for('manage_account')) elif request.method == 'GET': subscribed_users = [ result.subscribed_user for result in Subscription.query.filter_by( email_id=session.get('user')).all() ] rv = db_session().query(User).filter( User.email != session.get('user')).all() results = [] for row in rv: if row.email not in subscribed_users: results.append(row) users = [ dict(email=row.email, first_name=row.first_name, last_name=row.last_name, profilepic=row.profilepic) for row in results ] return render_template('subscribe.html', entries=users)
def create_plan(): with DBSession() as session: new = Plan(name=request.get_json().get("name"), content={}) session.add(new) db_session().refresh(new) return jsonify({ k: v for k, v in new.__dict__.items() if k in new._sa_instance_state.attrs.keys() })
def add_entry(): if not session.get('logged_in'): abort(401) tweet = Tweet(session.get('user'), request.form['text'], datetime.now(), None) db_session().add(tweet) db_session().commit() flash('New entry was successfully posted') return redirect(url_for('show_entries'))
def update_trade_threshold(client: Client): ''' Update all the coins with the threshold of buying the current held coin ''' all_tickers = get_all_market_tickers(client) current_coin = get_current_coin() current_coin_price = get_market_ticker_price_from_list(all_tickers, current_coin + BRIDGE) if current_coin_price is None: logger.info("Skipping update... current coin {0} not found".format(current_coin + BRIDGE)) return session: Session with db_session() as session: for pair in session.query(Pair).filter(Pair.to_coin == current_coin): from_coin_price = get_market_ticker_price_from_list(all_tickers, pair.from_coin + BRIDGE) if from_coin_price is None: logger.info("Skipping update for coin {0} not found".format(pair.from_coin + BRIDGE)) continue pair.ratio = from_coin_price / current_coin_price
def initialize_trade_thresholds(client: Client): ''' Initialize the buying threshold of all the coins for trading between them ''' all_tickers = get_all_market_tickers(client) session: Session with db_session() as session: for pair in session.query(Pair).filter(Pair.ratio == None).all(): if not pair.from_coin.enabled or not pair.to_coin.enabled: continue logger.info("Initializing {0} vs {1}".format(pair.from_coin, pair.to_coin)) from_coin_price = get_market_ticker_price_from_list(all_tickers, pair.from_coin + BRIDGE) if from_coin_price is None: logger.info("Skipping initializing {0}, symbol not found".format(pair.from_coin + BRIDGE)) continue to_coin_price = get_market_ticker_price_from_list(all_tickers, pair.to_coin + BRIDGE) if to_coin_price is None: logger.info("Skipping initializing {0}, symbol not found".format(pair.to_coin + BRIDGE)) continue pair.ratio = from_coin_price / to_coin_price
def migrate_old_state(): if os.path.isfile('.current_coin'): with open('.current_coin', 'r') as f: coin = f.read().strip() logger.info(f".current_coin file found, loading current coin {coin}") set_current_coin(coin) os.rename('.current_coin', '.current_coin.old') logger.info(f".current_coin renamed to .current_coin.old - You can now delete this file") if os.path.isfile('.current_coin_table'): with open('.current_coin_table', 'r') as f: logger.info(f".current_coin_table file found, loading into database") table: dict = json.load(f) session: Session with db_session() as session: for from_coin, to_coin_dict in table.items(): for to_coin, ratio in to_coin_dict.items(): if from_coin == to_coin: continue pair = session.merge(get_pair(from_coin, to_coin)) pair.ratio = ratio session.add(pair) os.rename('.current_coin_table', '.current_coin_table.old') logger.info(f".current_coin_table renamed to .current_coin_table.old - You can now delete this file")
def vote(): shader_id = bottle.request.params.getunicode('id') vote = bottle.request.params.getunicode('vote') ip = bottle.request.environ.get('REMOTE_ADDR') voting_dict = { 'up': 1, 'piggy': 0, 'down': -1 } session = db_session() if not session.query(exists().where(Shader.id==shader_id)): return bottle.abort(404, 'Not Found') voting = Vote( shader_id = shader_id, ip = ip, value = voting_dict[vote] ) existing_vote = session.query(Vote).filter(Vote.shader_id == shader_id, Vote.ip == ip) if existing_vote.count(): session.close() return bottle.abort(403, 'Forbidden') try: session.add(voting) session.commit() session.close() except: return bottle.abort(500, 'Internal Server Error') return json.dumps({'error': 'success'})
def add(self): self.publish_time = datetime.now() sc = db_session() sc.add(self) sc.commit() sc.close()
def photographer_register(): if request.method == "POST": # check if the current user has photographer linked to him or her if not current_user.photographer: # create a photographer with the current user id photographer = Photographer(user_id=current_user.id) # save to db db_session().add(photographer) db_session().commit() flash("You are now registered as a Photographer.Welcome {}".format( current_user.first_name)) # show error message and redirect to dashboard flash("You are now registered as a photographer") return redirect('/dashboard') # render the photographer register template return render_template('photographer_register.html')
def import_to_datastore(): from models import User, Marker i = 0 session = db_session() commit_every = 1000 for irow, data in enumerate(import_data()): show_progress_spinner() marker = Marker( user = None, title = "Accident", description = data["description"].decode("utf8"), address = data["address"].decode("utf8"), latitude = data["lat"], longitude = data["lng"], type = Marker.MARKER_TYPE_ACCIDENT, subtype = data["severity"], created = data["date"], ) session.add(marker) if irow>0 and irow%commit_every == 0: print "committing..." session.commit() session.flush() print "done."
def photographer_upload(): # if request method is post if request.method == 'POST': form = PhotoUploadForm(name=request.form.get("name"), file=request.files.get("file")) if form.validate(): # get the photographer id from the user # save the image and link to photographer image_file = form.file.data photo = Photo(name=form.name.data, photographer_id=current_user.photographer.id, file=image_file.read()) image = Image.open(image_file) file_type = image_file.headers.get("Content-Type") photo.add_image_data(*image.size, file_type) # save photo to db session_object = db_session() session_object.add(photo) session_object.commit() # success message flash("Image Uploaded Successfully", "success") return redirect(url_for('dashboard')) else: return render_template('photographer_uploads.html', form=form) # if the request is any other than get return render_template('photographer_uploads.html', form=PhotoUploadForm())
def check_status(self, contact=None): session = db_session() if contact: return session.query(Applicant).filter( Applicant.contact == contact).all() else: return None
def check_status(self, contact=None): session = db_session() if contact: return session.query(Applicant).filter(Applicant.contact==contact).all() else: return None
def report_weather(): log('Checking emails.') Digester(db_session(), host=environ['INREACH_MAIL_HOST'], username=environ['INREACH_MAIL_USERNAME'], password=environ['INREACH_MAIL_PASSWORD']).check_emails() messages = db_session.query(Message).filter( Message.response_sent == False).all() if environ['INREACH_RESPOND_TO_MESSAGES'] == 'YES': for message in messages: log(f'Responding to {message.text_msg_extid} @ {message.latitude}, {message.longitude}' ) query_params = message.query_params() response = Weatherman(message).send_forecast() if response.status_code == 200 and json.loads( response.text)['Success'] is True: # NB: json.loads may throw an error when the POST request was unsuccessful, # since inreach.garmin.com returns an html "Error page", along with status code 200. message.response_sent = True db_session.commit() log('Response sent.') else: log(f'Not responding to new emails.') db_session.remove()
def addBank(): params = [ 'name', 'locality', 'city', 'ifsc_code', 'start_time', 'end_time', 'password', 'username' ] for param in params: if request.form.get(param) is None: return Response(param + ' field is required', status=400) bank = Bank.query.filter_by(ifsc_code=request.form['ifsc_code']).first() if bank is not None: return Response('Bank with the same ifsc code already exists', status=400) bank = Bank.query.filter_by(username=request.form['username']).first() if bank is not None: return Response('Bank with the same username already exists', status=400) bank = Bank(name=request.form['name'], locality=request.form['locality'], city=request.form['city'], start_time=request.form['start_time'], end_time=request.form['end_time'], ifsc_code=request.form['ifsc_code'], password=request.form['password'], username=request.form['username']) session = db_session() session.add(bank) session.commit() bank_json = as_dict(bank) return Response(json.dumps(bank_json), status=200)
def edit_shader(shader_id): source = bottle.request.params.getunicode('source') authcode = bottle.request.params.getunicode('authcode') screenshot = bottle.request.params.getunicode('screenshot') session = db_session() try: shader = session.query(Shader).filter(Shader.id == shader_id) if shader.count(): shader = shader.one() else: session.close() raise('Shader not found') if not shader.authcode == authcode: session.close() return bottle.abort(403, 'Forbidden') except: session.close() return bottle.abort(404, 'Not found') try: shader.source = source shader.updated = datetime.datetime.now() session.commit() session.close() except: return bottle.abort(500, 'Internal Server Error') if not save_screenshot(shader_id, screenshot): print("yo?") return json.dumps({'id': shader_id, 'authcode': authcode, 'redirect': False})
def add_record(): content = request.get_json().get("content") with DBSession() as session: plan = db_session().query(Plan).filter( Plan.id == request.get_json().get("plan_id")).one() if not plan: abort(404) for currency, detail in content.items(): if currency not in plan.content: plan.content[currency] = {} plan.content[currency]["total_amount"] = 0 plan.content[currency]["total_quantity"] = 0 plan.content[currency]["avg_price"] = 0 plan.content[currency]["ratio"] = 0 plan.content[currency]["total_amount"] += detail["amount"] plan.content[currency]["total_quantity"] += detail["quantity"] plan.content[currency]["avg_price"] = plan.content[currency][ "total_amount"] / plan.content[currency]["total_quantity"] plan.content[currency]["earning"] = ( float(get_currency_price().get(currency)) - plan.content[currency]["avg_price"] ) / plan.content[currency]["avg_price"] plan.total_invest_money += detail["amount"] for currency, detail in plan.content.items(): plan.content[currency]["ratio"] = plan.content[currency][ "total_amount"] / plan.total_invest_money new = Record(plan_id=request.get_json().get("plan_id"), content=content) session.add(new) flag_modified(plan, "content") db_session().refresh(plan) total = 0 for currency, detail in plan.content.items(): total += float( get_currency_price().get(currency)) * detail.get("total_quantity") total_earning = (total - plan.total_invest_money) / plan.total_invest_money result = { k: v for k, v in plan.__dict__.items() if k in plan._sa_instance_state.attrs.keys() } result["total_earning"] = total_earning return jsonify(result)
def get_gallery(page=1): session = db_session() items_per_page = 16 shaders = session.query(Shader) total_pages = shaders.count() / items_per_page + (1 if shaders.count() % items_per_page != 0 else 0) session.close() return { 'shaders': shaders.order_by(Shader.updated.desc()).offset(items_per_page * (page - 1)).limit(items_per_page).all(), 'page': page, 'total_pages': total_pages }
def create_item(user_id: UUID4, item: ItemCreate) -> Item: with db_session() as db: item = Item(id=str(uuid.uuid4()), name=item.name, description=item.description, user_id=user_id) db.add(item) return item
def change_profilepic(): error = None if request.method == 'POST': user = User.query.filter_by(email=session.get('user')).first( ) # .update(dict(profilepic=request.files['profilepic'].filename)) user.profilepic = request.files['profilepic'].filename db_session().commit() print(user) upload_file(request.files['profilepic']) flash('successfully changed profile picture!') return redirect(url_for('manage_account')) else: return render_template('change_profilepic.html', error=error)
def update(self, *uuid, **new_status): session = db_session() query = session.query(Applicant) for id in uuid: applicant = query.filter(Applicant.id == id).first() for key in new_status: applicant.__setattr__(key, new_status[key]) session.commit()
def renew_google_user(existing_user): renewed_user_info = google_auth.refresh_user_keys(existing_user.renew_key) renewed_user_info = map_google_user_data(renewed_user_info) s = db_session() s.begin() update_user_keys(existing_user, renewed_user_info) s.commit() return existing_user.session
def trade_history(): session: Session with db_session() as session: query = session.query(Trade).order_by(Trade.datetime.asc()) query = filter_period(query, Trade) trades: List[Trade] = query.all() return jsonify([trade.info() for trade in trades])
def current_coin_history(): session: Session with db_session() as session: query = session.query(CurrentCoin) query = filter_period(query, CurrentCoin) current_coins: List[CurrentCoin] = query.all() return jsonify([cc.info() for cc in current_coins])
def create_user(user_create: UserCreate) -> User: with db_session() as db: user = User(id=str(uuid.uuid4()), email=user_create.email, name=user_create.name, bio=user_create.bio, password=user_create.password) db.add(user) return user
def coins(): session: Session with db_session() as session: current_coin = session.merge(database.get_current_coin()) coins: List[Coin] = session.query(Coin).all() return jsonify([{ **coin.info(), "is_current": coin == current_coin } for coin in coins])
def insert_advice(self, form): session = db_session() new_advice = Advice(id=uuid.uuid4(), name=form.name.data, major=form.major.data, email=form.email.data, advice=form.advice.data) session.add(new_advice) session.commit() session.close()
def put(self): tid = self.get_argument('id') inter_time = self.get_argument('inter_time') inter_place = self.get_argument('inter_place') session = db_session() row = session.query(Applicant).filter(Applicant.id == tid).first() row.inter_time = inter_time row.inter_place = inter_place session.commit() session.remove() self.write("success")
def cancel_reservation(unique_id, session): try: session = db_session() reservation_query = session.query(Reservation).filter_by( id=unique_id).delete() session.commit() return 'cancelled successfully' except Exception as e: session.close() print(e) return "cancel reservation has failed"
def save_error_task(urls, failure_devs, wrong_ret): """ 保存失败的信息到数据库 :param urls: :param failure_devs: :param wrong_ret: """ # return # 暂时不记录错误信息 errortask_list = [] for dev in failure_devs: errortask_list.append({ 'urls': urls, "dev_id": urls[0].get("dev_id"), "host": dev.get('host'), 'created_time': datetime.datetime.now(), 'name': dev.get('name'), 'status': dev.get('status'), "wrongRet": wrong_ret }) db_session().error_task.insert(errortask_list)
def scouting_history(): current_coin = database.get_current_coin() coin = current_coin.symbol if current_coin is not None else None session: Session with db_session() as session: query = session.query(ScoutHistory).join(ScoutHistory.pair).filter( Pair.from_coin_id == coin).order_by(ScoutHistory.datetime.asc()) query = filter_period(query, ScoutHistory) scouts: List[ScoutHistory] = query.all() return jsonify([scout.info() for scout in scouts])
def put(self, tid, status): session = db_session() row = session.query(Applicant).filter(Applicant.id == tid).first() status = int(status) if status: row.status = "进行中" row.inter_round += 1 else: row.status = "未通过" session.commit() session.remove() self.write("success")
def total_value_history(): session: Session with db_session() as session: query = session.query(CoinValue.datetime, func.sum(CoinValue.btc_value), func.sum(CoinValue.usd_value)).group_by( CoinValue.datetime) query = filter_period(query, CoinValue) total_values: List[Tuple[datetime, float, float]] = query.all() return jsonify([{"datetime": tv[0], "btc": tv[1], "usd": tv[2]} for tv in total_values])
def _test_delete_article(): _id = 197 _dbss = db_session() try: _dbss.execute(association_table_catalog_article.delete().where(association_table_catalog_article.c.article_id==_id)) # @UndefinedVariable _dbss.query(Article).filter_by(id=_id).delete() # @UndefinedVariable _dbss.commit() # @UndefinedVariable except: import sys print sys.exc_info()[1] _dbss.rollback() print 'Article deleted [%s]' % _id
def insert_applicant(self, form): session = db_session() new_applicant = Applicant(id=uuid.uuid4(), name=form.name.data, gender=form.gender.data, campus=form.campus.data, major=form.major.data, contact=form.contact.data, backup_contact=form.backup_contact.data, group=form.group.data, intro=form.intro.data) session.add(new_applicant) session.commit() session.close()
def test_create_reply(): _author_id = random.randint(1, 20) _article_id = random.randint(1, 200) _reply = ArticleReply() _reply.article_id = _article_id _reply.author_id = _author_id _random_seed = str(random.random()) _reply.content = 'reply content - %s' % (''.join(random.randint(10, 50)*sha224(_random_seed).hexdigest())) _reply.published_datetime = datetime.datetime.now() time.sleep(0.3) _dbss = db_session() _dbss.add(_reply) _dbss.commit()
def create_shader(): source = bottle.request.params.getunicode('source') screenshot = bottle.request.params.getunicode('screenshot') session = db_session() shader = Shader(source=source) session.add(shader) session.commit() if not save_screenshot(shader.id, screenshot): shader.delete() session.commit() session.close() return bottle.abort(500, "Internal Server Error") session.close() return json.dumps({'id': shader.id, 'authcode': shader.authcode, 'redirect': True})
def get_wall(shader_id=None): if shader_id: try: session = db_session() shader = session.query(Shader).filter(Shader.id == shader_id).one() session.close() return { 'shader_id': shader.id, 'shader_source': shader.source, 'save_button_text': '', 'save_url': '', 'authcode': '', } except: return {'save_url': '', 'save_button_text': '', 'authcode': '', 'screenshot_size': screenshot_size} else: return {'save_url': '', 'save_button_text': '', 'authcode': '', 'screenshot_size': screenshot_size}
def import_to_datastore(ratio=1): from models import User, Marker i = 0 session = db_session() # wipe all the Markers first session.query(Marker).delete() session.flush() commit_every = 100 for irow, data in enumerate(import_data()): show_progress_spinner() if irow % ratio == 0: marker = Marker( user = None, title = "Accident", description = data["description"].decode("utf8"), address = data["address"].decode("utf8"), latitude = data["lat"], longitude = data["lng"], type = Marker.MARKER_TYPE_ACCIDENT, subtype = data["subType"], severity = data["severity"], created = data["date"], ) session.add(marker) i += 1 if i % commit_every == 0: print "committing (%d items done)..." % (i,) session.commit() session.flush() print "done." if i % commit_every != 0: # we still have data in our transaction, flush it print "committing..." session.commit() session.flush() print "done." print "imported %d items" % (i,)
def get(self, group=None): session = db_session() counts = { 'all': 0, 'refuse': 0, 'pass': 0 } if group: rows = session.query(Applicant).filter(Applicant.group == group).all() counts['all'] = len(rows) counts['refuse'] = len(session.query(Applicant).filter(Applicant.status == '未通过') .filter(Applicant.group == group).all()) counts['pass'] = counts['all'] - counts['refuse'] else: rows = session.query(Applicant).all() counts['all'] = len(rows) counts['refuse'] = len(session.query(Applicant).filter(Applicant.status == '未通过').all()) counts['pass'] = counts['all'] - counts['refuse'] session.remove() self.render("invite.html", data=rows, counts=counts)
def get(self, phone_number=None): session = db_session() rows = session.query(Applicant).filter(Applicant.contact == phone_number).all() if not phone_number: self.render("query.html", result={}) if rows: rows = rows[0] result = { "name": rows.name, "contact": rows.contact, "group": rows.group, "inter_place": rows.inter_place, "inter_round": rows.inter_round, "inter_time": rows.inter_time, "status": rows.status } session.remove() self.render("query.html", result=result) else: session.remove() self.render("query.html", result=False)
def get_gallery(shader_id=None): if shader_id: authcode = bottle.request.params.getunicode('authcode') try: session = db_session() shader = session.query(Shader).filter(Shader.id == shader_id).one() votes = session.query(Vote).filter(Vote.shader_id == shader_id, Vote.ip == bottle.request.environ.get('REMOTE_ADDR')) if votes.count() > 0: voting_disabled = ' disabled' vote = 'up' if votes.one().value > 0 else 'down' else: voting_disabled = '' vote = None shader.views += 1 session.commit() if shader.authcode == authcode: save_button_text = 'Save' save_url = '/shaders/%d' % shader_id else: save_button_text = 'Fork' save_url = '/shaders' session.close() return { 'shader_id': shader.id, 'shader_source': shader.source, 'save_button_text': save_button_text, 'save_url': save_url, 'authcode': authcode, 'screenshot_size': screenshot_size, 'voting_disabled': voting_disabled, 'vote': vote } except: return {'save_url': '/shaders', 'save_button_text': 'Create', 'authcode': '', 'screenshot_size': screenshot_size, 'shader_source': default_shader_source, 'voting_disabled': '', 'vote': None } else: return {'save_url': '/shaders', 'save_button_text': 'Create', 'authcode': '', 'screenshot_size': screenshot_size, 'shader_source': default_shader_source, 'voting_disabled': '', 'vote': None }
# -*- coding: utf-8 -*- from database import init_db, db_session from models import User, Group, Location, Event from werkzeug import generate_password_hash import datetime init_db() session = db_session() user = User( username='******', first_name='Martin', last_name='Czygan', dob=datetime.datetime(1979, 4, 29), email='*****@*****.**', identifier_id='0000', city='Leipzig', country='DEU', zipcode='04277', street='Brandstr. 15', password=generate_password_hash('dev') ) group = Group(name='admin') user.groups.append(group) session.add(user) session.add(group) session.commit()
def open(self, id): self.ws_methods = [ "subscribe" ] self.danmaku_id = id self.session = database.db_session()
def initialize(self): self.session = db_session() self.redis_cli = redis_cli
def initialize(self): self.session = db_session() self.set_header('Content-type', 'application/json;charset=UTF-8') self.item = dict()
def populate(): data = json.loads(open("DB/users.json").read()) u = User('*****@*****.**', 'abc123', 'ben', 'ahlbrand', 'profile.png') db_session().add(u) u = User('*****@*****.**','abc123','George','Constanza', '') db_session().add(u) u = User('*****@*****.**','mary123', 'Mary', 'Lamb', '') db_session().add(u) u = User('*****@*****.**','peter123','Peter','Piper', '') db_session().add(u) db_session().commit() # s = Subscription('*****@*****.**', '*****@*****.**') # db_session.add(s) # s = Subscription('*****@*****.**', '*****@*****.**') # db_session.add(s) # s = Subscription('*****@*****.**', '*****@*****.**') # db_session.add(s) # s = Subscription('*****@*****.**', '*****@*****.**') # db_session.add(s) # s = Subscription('*****@*****.**', '*****@*****.**') # db_session.add(s) # db_session().commit() for row in data: user = User.query.filter_by(email=row['email']).first() if user is None: u = User(row['email'], row['password'], row['first_name'], row['last_name'], row['profilepic_path']) db_session().add(u) db_session().commit() # u.follow(u) # db_session().commit() # print(u.is_following()) users = User.query.all() shuffle(users) unusers = users shuffle(unusers) # print(unusers) data = json.loads(open("DB/tweets.json").read()) for row, user in zip(data, users): date_object = datetime.strptime(row['timestamp'], '%I:%M %p') tweet = Tweet(user.email, row['text'], date_object) db_session().add(tweet) db_session().commit() topush = [] for unuser in unusers: # print(unuser.email) sub = Subscription('*****@*****.**', unuser.email) topush.append(sub) for sub in topush: db_session().add(sub) db_session().commit() print("database is populated")