def create_notification(payment_id): """ Notify about payment status """ payment = db_session.query(Payment).get(payment_id) if not payment: abort(404) if not request.json or 'notification_url' not in request.json: logger.debug( 'Not enough data to create notification! Request data: {0}'.format( request.json)) abort(400) if payment.status in [ PaymentStatus.timeout, PaymentStatus.success, PaymentStatus.refused ]: logger.debug('Payment has already finished') return jsonify({'error': 'Payment has already finished'}), 400 user_data = request.json.get('user_data', {}) notification = Notification(payment.payment_id, request.json.get('notification_url'), user_data) payment.notifications.append(notification) db_session.add(payment) db_session.commit() return jsonify({'id': notification.notification_id}), 201
def get_or_create(hostname): rv = Server.query.filter_by(hostname=hostname).first() if rv is None: rv = Server() rv.steam_id = hostname db_session.add(rv) return rv
def transfer_amount_db(source_account: str, to_account: str, amount: float, description: str = None): balance = get_account_balance(source_account) if balance < amount: return False, "Transaction Failed! Insufficient funds." source_transaction_id = get_transaction_id(source_account) source_transaction = Transaction( transaction_id=source_transaction_id, transaction_time=datetime.now(), account_number=source_account, amount=amount, transaction_type=Transaction.get_debit_type(), details=description) receiver_transaction_id = get_transaction_id(to_account) receiver_transaction = Transaction( transaction_id=receiver_transaction_id, transaction_time=datetime.now(), account_number=to_account, amount=amount, transaction_type=Transaction.get_credit_type(), details=description) db_session.add(source_transaction) db_session.add(receiver_transaction) db_session.commit() return True, "Transaction Successful"
def get_or_create(steam_id): rv = User.query.filter_by(steam_id=steam_id).first() if rv is None: rv = User() rv.steam_id = steam_id db_session.add(rv) return rv
def create_account(): output = render_template("dashboard/register.html") if request.form.get("remail1"): output = redirect(url_for("index")) email = request.form.get("remail2") if request.form.get("rpw") != None: password = request.form.get("rpw") else: password = "******" user = User(nickname=request.form.get("username"), email=email, password=password, email_confirmed=0) # Now we'll send the email confirmation link subject = "Confirm your email" token = ts.dumps(user.email, salt='email-confirm-key') confirm_url = url_for('confirm_email', token=token, _external=True) html = render_template('dashboard/email/activate.html', confirm_url=confirm_url) db_session.add(user) db_session.commit() checkbox = request.form.get("remember") login_user(user, checkbox) drill(user.email, subject, html) output = redirect(url_for("dashboard")) return output
def save_bitcoin_data(data): """ Save to database using db_session. """ db_session.add(data) db_session.commit() return True
def create_account(): output = render_template("dashboard/register.html") if request.form.get("remail1"): output = redirect(url_for("index")) email = request.form.get("remail2") if request.form.get("rpw") != None: password = request.form.get("rpw") else: password = "******" user = User(nickname=request.form.get("username"), email=email, password=password, email_confirmed=0) # Now we'll send the email confirmation link subject = "Confirm your email" token = ts.dumps(user.email, salt='email-confirm-key') confirm_url = url_for( 'confirm_email', token=token, _external=True) html = render_template( 'dashboard/email/activate.html', confirm_url=confirm_url) db_session.add(user) db_session.commit() checkbox = request.form.get("remember") login_user(user, checkbox) drill(user.email, subject, html) output = redirect(url_for("dashboard")) return output
def join_program(bot, update): """ Add new user to program as referraler :param bot: bot :type bot: telegram.Bot :param update: update event :type update: relegram.Update """ _, channel_id, channel_name = update.callback_query.data.split(':') username = update.effective_user.username user_id = update.effective_user.id if not db_session.query(Inviter.inviter_id).filter_by( inviter_id=user_id).scalar(): logger.debug('Adding inviter <{0}> to DB'.format(user_id)) inviter = Inviter(user_id, username, update.effective_user.first_name, update.effective_user.last_name) db_session.add(inviter) q = db_session.query(ChannelInviter).filter_by(inviter_id=user_id, channel_id=channel_id) if not db_session.query(q.exists()).scalar(): logger.info('Adding assoc SI <{0}:{1}> to DB' .format(user_id, channel_id)) association = ChannelInviter(user_id, channel_id) db_session.add(association) db_session.commit() update.callback_query.answer()
def new_item(category_id): if 'username' not in login_session: return redirect('/login') category = db_session.query(Category).filter_by(id=category_id).one() all_categories = db_session.query(Category).order_by(asc(Category.name)) if request.method == 'POST': try: photo = request.files.get('photo') new_item = CategoryItem(name=request.form['name'], description=request. form['description'], category_id=category_id) with store_context(local_storage): new_item.picture.from_file(photo) new_item.picture.generate_thumbnail(width=300) db_session.add(new_item) db_session.commit() except: flash("Item creation failed") return redirect(url_for('show_items', category_id=category_id, categories=all_categories)) flash('New %s Item Successfully Created' % (new_item.name)) return redirect(url_for('show_items', category_id=category_id, categories=all_categories)) else: return render_template('new_item.html', category_id=category_id, categories=all_categories)
def _delete_profile_photo(current_user): s3_fs.rm(current_user.profile_photo_s3_key) current_user.profile_photo_s3_key = "" db_session.add(current_user) db_session.commit() resp = jsonify({}) return resp, 200
def page(): user = None content = None pages = Page.query.filter(Page.url.isnot(None)) if "user" in session: user = User.query.filter_by(email=session["user"]).first() if request.form.get("inputURL") != None: content = { "aid": user.id, "url": request.form.get("inputURL"), "gender": request.form.get("gender"), "countries": request.form.get("countries"), "ppc": request.form.get("points"), } page = Page( aid=user.id, url=request.form.get("inputURL"), type=request.form.get("type"), gender=request.form.get("gender"), countries=request.form.get("countries"), ppc=request.form.get("points"), ex=0, ) db_session.add(page) db_session.commit() return render_template("dashboard/page.html", pages=pages, user=user)
def behavior_user(array): # "10002", dict['f'], dict['b'], dict['d'] user = None try: # user = User.query.filter(User.user_id == user_id).first() user = User.query.filter(User.user_id == "10002").first() try: for dict in array: timeStamp = dict['b'] # 秒转换为时间 timeArray = time.localtime(timeStamp) otherStyleTime = time.strftime("%Y-%m-%d %H:%M:%S", timeArray) behavior = table_behavior_log(user.id) behavior.func_id = dict['f'] behavior.begin_time = otherStyleTime behavior.duration = dict['d'] db_session.add(behavior) db_session.commit() print ('提交成功') except Exception, e: print ("异常 插入用户行为异常", e) except Exception,e: print ("异常 查询 user_id 失败", e)
def createUser(login_session): newUser = User(name=login_session['username'], email=login_session[ 'email'], picture=login_session['picture']) db_session.add(newUser) db_session.commit() user = db_session.query(User).filter_by(email=login_session['email']).one() return user.id
def page(): user = None content = None pages = Page.query.filter(Page.url.isnot(None)) if 'user' in session: user = User.query.filter_by(email=session['user']).first() if request.form.get("inputURL") != None: content = { "aid": user.id, "url": request.form.get("inputURL"), "gender": request.form.get("gender"), "countries": request.form.get("countries"), "ppc": request.form.get("points") } page = Page(aid=user.id, url=request.form.get("inputURL"), type=request.form.get("type"), gender=request.form.get("gender"), countries=request.form.get("countries"), ppc=request.form.get("points"), ex=0) db_session.add(page) db_session.commit() return render_template("dashboard/page.html", pages=pages, user=user)
def add(object): try: db_session.add(object) db_session.commit() except: db_session.rollback() finally: closeDbSession()
def checkr(): if request.method == "POST": if (session['level'] == 2): ans = Answer.query.filter( Answer.answer == request.form['answer'].replace("_", " ", 10) and Answer.q_id == request.form['q_id']).first() if ans.is_correct: user = User.query.filter( User.username == session['username']).first() user.marks = user.marks + session['marks'] session.pop('marks') db_session.add(user) db_session.commit() return jsonify(color="green") else: session.pop('marks') return jsonify(color="red") elif (session['level'] == 1): ans = Answer.query.filter( Answer.answer == request.form['answer'] and Answer.q_id == request.form['q_id']).first() if ans.is_correct: user = User.query.filter( User.username == session['username']).first() user.marks = user.marks + session['marks'] if user.marks > 30: user.level = user.level + 1 session['level'] = user.level session.pop('marks') print "##############################" db_session.add(user) db_session.commit() return jsonify(color="green") else: session.pop('marks') return jsonify(color="red") # @app.route("/question",methods=['GET','POST']) # def question(): # if request.method == "POST": # q = Question(request.form['question'],request.form['marks'],request.form['level']) # db_session.add(q) # db_session.commit() # return q.q_id # @app.route("/user",methods=['GET','POST']) # def user(): # if request.method == "POST": # u = User(request.form['username']) # db_session.add(u) # db_session.commit() # @app.route("/answer",methods=['GET','POST']) # def answer(): # if request.method == "POST": # ans = Answer(request.form['answer'],request.form['q_id'],True if request.form['is_correct'] == "True" else False) # db_session.add(ans) # db_session.commit()
def post(self): form = self.get_form() if form.validate(): obj = self.create_object(form) db_session.add(obj) db_session.commit() flash(u'%s added' % self.main_model.__name__) return redirect(url_for(self.default_route)) return render_template(self.template_name, form=form)
def post(self,serial_no): data = request.json args = self.parser.parse_args() Ser = Servers(serial_no, args["name"], args["vendor"], args["rackno"], args["runits"], args["mgmt_ip"], args["env"]) Ser_desc = Server_DESC(serial_no,args["type"], args["hostname"], args["role"], args["owner"],args["data_ip"], args["gateway"], args["netmask"], args["interface"]) db_session.add(Ser) db_session.add(Ser_desc) db_session.commit() return data
def create_items(): for item in ITEMS: new_item = CatalogItem(name=item['name'], description=item['description'], user_id=item['user_id'], catalog_id=item['catalog_id']) db_session.add(new_item) db_session.commit()
def databaseOperations(subject): targetsearch = Pynionquery.query.filter_by(searchword = subject).first() if (targetsearch): print("found and updating") db_session.query(Pynionquery).filter(Pynionquery.searchword == subject).update({Pynionquery.count: Pynionquery.count+1}) else: print("db file initialised....") pynionquery = Pynionquery(subject) db_session.add(pynionquery) db_session.commit()
def post(self, id): obj = db_session.query(self.main_model).get(id) form = self.get_form(obj) if form.validate(): form.populate_obj(obj) db_session.add(obj) db_session.commit() flash(u'%s updated' % self.main_model.__name__) return redirect(url_for(self.default_route)) return render_template(self.template_name, obj=obj, form=form)
def post(self, serial_no): data = request.json args = self.parser.parse_args() Ser = Servers(serial_no, args["name"], args["vendor"], args["rackno"], args["runits"], args["mgmt_ip"]) Ser_desc = Server_DESC(serial_no, args["type"], args["hostname"], args["role"], args["owner"], args["data_ip"]) db_session.add(Ser) db_session.add(Ser_desc) db_session.commit() return data
def post(self): args = self.reqparse.parse_args() o = UserRoles(args["role_name"]) try: db_session.add(o) db_session.commit() except IntegrityError as err: db_session.rollback() return {"DB Error: {0}".format(err)}, 500 return o.as_dict(),201
def post(self): args = self.reqparse.parse_args() o = SubCategory(args["name"],args["description"],args["image_url"],args["category_id"]) try: db_session.add(o) db_session.commit() except IntegrityError as err: db_session.rollback() return {"DB Error: {0}".format(err)}, 500 return o.as_dict(),201
def post(self): args = self.reqparse.parse_args() o = Orders(args["table_id"],args["waiter_id"],args["chef_id"],args["order_details"],args["order_status"],args["cost"]) try: db_session.add(o) db_session.commit() except IntegrityError as err: db_session.rollback() return {"DB Error: {0}".format(err)}, 500 #return o.as_dict(),201 return "Success"
def repair(): if request.method == 'GET': repairs = models.Repair.query.filter_by(person=current_user.person_id) return render_template('repair.html', current_user=current_user, repairs=repairs) elif request.method == 'POST': db_session.add( models.Repair(request.form['description'], request.form['tag'], current_user.person_id)) db_session.commit() return redirect(url_for('repair'))
def upload_profile_photo(self, file): db_session.add(self) s3_dir = PROFILE_PHOTOS_DIR.format(bucket=config['S3_BUCKET'], id=self.id) s3_key = f'{s3_dir}/{file.filename}' if s3_fs.exists(s3_dir): # Remove existing folder s3_fs.rm(s3_dir) with s3_fs.open(s3_key, 'wb') as s3_fp: s3_fp.write(file.read()) self.profile_photo_s3_key = s3_key db_session.add(self) db_session.commit() return s3_key
def create_user(jdic): group_user = db_session.query(Group).filter_by(name='user').one() time_expire = datetime.timedelta(10)+datetime.datetime.now() s = Session(time_expire, jdic['username'],jdic['password']) db_session.add(s) db_session.commit() u = User(jdic['username'],jdic['email'],jdic['password'],group_user) u.session = s db_session.add(u) db_session.commit() db_session.close() return s.token
def create_blog(): if 'logged_in' not in session: flash("Not logged in", category='errors') return redirect('/') else: title = request.form['title'] body = request.form['body'] owner_id = session['user_id'] blog = Blog(title=title, body=body, owner_id=owner_id) db_session.add(blog) db_session.commit() return redirect('/blog/{}'.format(blog.id))
def verify_email(self, token): """Verify that the provided token is for this user's id.""" data = deserialize_data(token) if not data: logging.warning(f"Error verifying email for user " f"id {self.id}: BadSignature or SignatureExpired") return False if data.get('id') != self.id: logging.warning(f"Error verifying email for user " f"id {self.id}: {data}") self.verified_email = True db_session.add(self) db_session.commit() return True
def deposit_money_db(source_account: str, amount: float, description: str = None): source_transaction_id = get_transaction_id(source_account) source_transaction = Transaction( transaction_id=source_transaction_id, transaction_time=datetime.now(), account_number=source_account, amount=amount, transaction_type=Transaction.get_credit_type(), details=description) db_session.add(source_transaction) db_session.commit() return True, "Transaction Successful"
def newFunc(*args, **kwargs): if request.headers.getlist("X-Forwarded-For"): ip = request.headers.getlist("X-Forwarded-For")[0] else: ip = request.remote_addr l = models.Logger(url=request.url, remote_addr=ip, method=request.method, user_agent=request.user_agent, datetime=datetime.now()) db_session.add(l) db_session.commit() # db_session.commit() return func(*args, **kwargs)
def oauth_callback(provider): if not current_user.is_anonymous(): return redirect(url_for('index')) oauth = OAuthSignIn.get_provider(provider) social_id, username, email = oauth.callback() if social_id is None: flash('Authentication failed.') return redirect(url_for('index')) user = User.query.filter_by(social_id=social_id).first() if not user: user = User(social_id=social_id, nickname=username, email=email) db_session.add(user) db_session.commit() login_user(user, True) return redirect(url_for('index'))
def oauth_callback(provider): if not current_user.is_anonymous(): return redirect(url_for("index")) oauth = OAuthSignIn.get_provider(provider) social_id, username, email = oauth.callback() if social_id is None: flash("Authentication failed.") return redirect(url_for("index")) user = User.query.filter_by(social_id=social_id).first() if not user: user = User(social_id=social_id, nickname=username, email=email) db_session.add(user) db_session.commit() login_user(user, True) return redirect(url_for("index"))
def terminate(self, operation=None, err=None): if not hasattr(self, 'run'): return if err is not None: self.run['status'] = 'error' self.run['error_msg'] = str(err) self.run['operation'] = operation self.run['end_time'] = datetime.now() self.run['new_records'] = self.record_counter run = Run(**self.run) db_session.add(run) db_session.commit()
def setup_general(): """Runs the set-up needed for both local development and production. Also sets up first admin user.""" if User.query.filter_by(email=config['ADMIN_EMAIL']).first() is None: user = User( role=Role.ADMIN, first_name='Admin', last_name='Account', password=config['ADMIN_PASSWORD'], email=config['ADMIN_EMAIL'], verified_email=True, ) db_session.add(user) db_session.commit() print('Added administrator {}'.format(user.full_name()))
def add_employee(data): try: new_employee = Employee(employee_username=data['employee_username'], employee_email=data['employee_email'], employee_status=data['employee_status']) new_employee._set_password = data['employee_password'] db_session.add(new_employee) db_session.commit() db_session.refresh(new_employee) flash( 'Employee {} added successfully .'.format( data['employee_username']), 'success') except exc.SQLAlchemyError as e: db_session.rollback() flash('there was an error committing your data.', 'danger')
def new_wash(): from dateutil.parser import parse WASH_PER_DAY = 3 if len( models.Washing.query.filter_by( start=parse(request.form['startDate'])).all()) < WASH_PER_DAY: db_session.add( models.Washing(start=parse(request.form['startDate']), end=parse(request.form['endDate']), person=request.form['name'], hostel=request.form['location'])) db_session.commit() return json.dumps({'status': 'ok'}) else: return abort(500)
def create_account(): output = render_template("dashboard/register.html") if request.form.get("email"): output = redirect(url_for("index")) email = request.form.get("email") if request.form.get("password") != None: password = request.form.get("password") else: password = "******" exists = User.query.filter_by(email=email).first() if current_user.is_authenticated(): user = User(nickname=request.form.get("username"), email=email, password=password, vpoints=0, email_confirmed=0, oauth_token=current_user.token, oath_secret=current_user.secret) else: user = User(nickname=request.form.get("username"), email=email, password=password, vpoints=0, email_confirmed=0) # Now we'll send the email confirmation link subject = "Confirm your email" token = ts.dumps(user.email, salt='email-confirm-key') confirm_url = url_for('confirm_email', token=token, _external=True) html = render_template('dashboard/email/activate.html', confirm_url=confirm_url) if exists == None: db_session.add(user) db_session.commit() login_user(user, True) drill(user.email, subject, html) else: print "x is %s" db_session.merge(user) db_session.commit() login_user(user, True) output = redirect(url_for("index")) return output
def register(): form = RegisterForm(request.form) if request.method == 'POST' and form.validate(): if User.query.filter_by(uid=form.uid.data).first(): msg = f"{form.uid.data} already exists" print(msg) return msg user = User(form.uid.data, form.upw.data, form.msg.data, form.email.data) db_session.add(user) db_session.commit() msg = f"register success, {user.uid}" print(msg) flash(msg) return redirect(request.args.get('next') or url_for('account.index')) return render_template('register.html', form=form)
def add_menu_item(data): try: new_item = MenuItemsTable(item_name=data['item_name'], item_category=data['item_category'], item_status=data['item_status'], item_price=data['item_price'], item_size=data['item_size'], item_image=data['item_image']) db_session.add(new_item) db_session.commit() db_session.refresh(new_item) flash('Item {} added successfully .'.format(data['item_name']), 'success') except exc.SQLAlchemyError: db_session.rollback() flash('there was an error committing your data.', 'danger')
def change_referral_state(bot, update, is_running): """ Stopping referral program by stop managment button :param bot: bot :type bot: telegram.Bot :param update: update event :type update: relegram.Update """ _, channel_id, channel_name = update.callback_query.data.split(':') channel = Channel.query.get(channel_id) channel.is_running = is_running db_session.add(channel) db_session.commit() return Managment.channel_managment(bot, update)
def reset_password(token, new_password): """Verify the new password for this user.""" data = deserialize_data(token) if data is None: logging.warning(f"Error reseting password: BadSignature or " f"SignatureExpired") return None user_id = data.get('id') user = db_session.query(User).filter_by(id=user_id).first() if user is None: logging.warning(f"User with id {user_id} does not exist.") return None user.password = new_password db_session.add(user) db_session.commit() return user
def isOauth(cls): try: serverOauthUrl = 'http://test.yundong99.net/weixin/oauth' #serverOauthUrl = '123.206.25.118/weixin/oauth' url = request.url # 跳转授权url # 保存需要授权的url authUrl = OauthUrl() authUrl.url = url authUrl.id = randomStr(16) db_session.add(authUrl) current_app.logger.debug(' oauth redirect url : ' + url) return WeixinHelper.oauth2_info(serverOauthUrl, authUrl.id) except Exception, e: current_app.logger.error(str(e)) return
def create_account(): output = render_template("dashboard/register.html") if request.form.get("email"): output = redirect(url_for("index")) email = request.form.get("email") if request.form.get("password") != None: password = request.form.get("password") else: password = "******" exists = User.query.filter_by(email=email).first() if current_user.is_authenticated(): user = User( nickname=request.form.get("username"), email=email, password=password, vpoints=0, email_confirmed=0, oauth_token=current_user.token, oath_secret=current_user.secret, ) else: user = User( nickname=request.form.get("username"), email=email, password=password, vpoints=0, email_confirmed=0 ) # Now we'll send the email confirmation link subject = "Confirm your email" token = ts.dumps(user.email, salt="email-confirm-key") confirm_url = url_for("confirm_email", token=token, _external=True) html = render_template("dashboard/email/activate.html", confirm_url=confirm_url) if exists == None: db_session.add(user) db_session.commit() login_user(user, True) drill(user.email, subject, html) else: print "x is %s" db_session.merge(user) db_session.commit() login_user(user, True) output = redirect(url_for("index")) return output
def oauth_authorized(resp): next_url = request.args.get("next") or url_for("index") if resp is None: return redirect(next_url) this_account = User.query.filter_by(nickname=resp["screen_name"]).first() if this_account is None: new_account = User( nickname=resp["screen_name"], oauth_token=resp["oauth_token"], oauth_secret=resp["oauth_token_secret"] ) db_session.add(new_account) db_session.commit() login_user(new_account, True) else: login_user(this_account, True) return redirect(url_for("social"))
def post(self): args = self.reqparse.parse_args() o = Category(args["name"],args["description"],args["image_url"]) try: db_session.add(o) db_session.commit() except IntegrityError as err: db_session.rollback() return {"DB Error: {0}".format(err)}, 500 file = args['image'] if file: extension = os.path.splitext(file.filename)[1] filename = "uploads/categories/category_img_" + str(o.id) + extension o.image_url = filename file.save(os.path.join(os.getcwd(), filename)) return o.as_dict(),201
def new_category(): if 'username' not in login_session: return redirect('/login') if request.method == 'POST': new = Category(name=request.form['name'], user_id=login_session['user_id']) db_session.add(new) user = getUserInfo(login_session['user_id']) flash('New Category %s Successfully Created by %s' % (new.name, user.name)) db_session.commit() categories = db_session.query(Category).order_by(asc(Category.name)) return redirect(url_for('show_categories', username=login_session["username"], categories=categories)) else: categories = db_session.query(Category).order_by(asc(Category.name)) return render_template('new_category.html', username=login_session["username"], categories=categories)
def simulatePOST(jobid, user): ''' Create simulation job for the worker ''' job = Job.query.get(jobid) sim = Simulation.query.get(job.sim_id) # treat seed and samples specially params = { "_seed": job.seed, "_samples": job.samples, "_npoints": job.npoints } # filter params by what the simulation expects (needed!) valid = set(pd.name for pd in sim.params) params.update(dict( (pv.param.name, pv.value) for pv in job.params if pv.param.name in valid)) # create simulation run (for the worker to compute) run = SimRun(user=user, job=job, sim=sim, params=params) db_session.add(run) db_session.commit() # send user to status page return redirect(url_for('status', runid=run.id))
def edit_item(category_id, item_id): if 'username' not in login_session: return redirect('/login') edited_item = db_session.query(CategoryItem).filter_by(id=item_id).one() # confirm category exists db_session.query(Category).filter_by(id=category_id).one() print edited_item.category.name if request.method == 'POST': if request.form['name']: edited_item.name = request.form['name'] if request.form['description']: edited_item.description = request.form['description'] if request.form['category']: edited_item.category = db_session.query(Category).filter_by( id=request.form['category']).one() print edited_item.category.name photo = request.files.get('photo') if photo: with store_context(local_storage): edited_item.picture.from_file(photo) edited_item.picture.generate_thumbnail(width=300) db_session.add(edited_item) db_session.commit() else: db_session.add(edited_item) db_session.commit() flash('Item Successfully Edited') return redirect(url_for('show_items', category_id=category_id)) else: all_categories = db_session.query(Category).\ order_by(asc(Category.name)) return render_template('edit_item.html', category_id=category_id, item_id=item_id, item=edited_item, categories=all_categories)
# Get gps_data try: type=_values['type'] print type if type=='register': name = _values['name'] print name passwd = _values['passwd'] print passwd sip_address=_values['sip_address'] print sip_address token=_values['token'] print token print 'a new people want to register ' user = User(name, passwd, 1, token , sip_address); db_session.add(user) db_session.commit() elif type=='location': latitude = _values['latitude'] longitude = _values["longitude"] heading = _values["heading"] name = _values['name'] passwd = _values['passwd'] registered_user = User.query.filter(User.name == name, User.passwd == passwd).first() # this sentence is correct if registered_user is None: print "error" else: ####################
def info(bin): # Insert new simulation sim_name = basename(bin)[:-1*len('.out')] sim = None if exist(Simulation, name=sim_name): print 'Updating existing simulation: ' + sim_name sim = fetch(Simulation, name=sim_name)[0] else: # Create new simulation sim = Simulation(name=sim_name) db_session.add(sim) db_session.commit() # Delete old params print sim.id, sim_name # Get info from executable status, out = getstatusoutput('%s --info' % bin) if status != 0: raise RuntimeWarning('Could not get info from %s' % bin) lines = out.split('\n') # Extract types and defaults types = dict(RE_types.findall(filter(lambda x: 'Parameters:' in x, lines)[0])) defaults = {} map(lambda s: defaults.update(dict([RE_default.match(s).groups()])), filter(lambda x: 'Param:' in x, lines)) # Extract priority, unit information and description messages infos = read_params('%s.instr' % bin[:-1*len('.out')]) # Insert param default convertfns = {'string' : lambda x: x, 'double' : float } # Insert new params for param in sorted(types.keys()): if not exist(Param, sim_id=sim.id, name=param): print 'new param: ', param p = Param(sim=sim, name=param) db_session.add(p) db_session.commit() else: [p] = fetch(Param, sim_id=sim.id, name=param) if param.lower() in infos: priority, unit, msg = infos[param.lower()] else: priority = 100000 unit = DEFAULT_UNIT msg = DEFAULT_MSG p.priority = priority p.unit = unit p.msg = msg p.default_value = convertfns[types[param]](defaults[param]) # Commit work so far db_session.commit()
def test_follow_posts(self): # pdb.set_trace() # make four users u1 = User(username = '******', email = '*****@*****.**') u2 = User(username = '******', email = '*****@*****.**') u3 = User(username = '******', email = '*****@*****.**') u4 = User(username = '******', email = '*****@*****.**') db_session.add(u1) db_session.add(u2) db_session.add(u3) db_session.add(u4) db_session.commit() # make four posts utcnow = datetime.utcnow() p1 = Post(body = "post from john", author = u1, timestamp = utcnow + timedelta(seconds = 1)) p2 = Post(body = "post from susan", author = u2, timestamp = utcnow + timedelta(seconds = 2)) p3 = Post(body = "post from mary", author = u3, timestamp = utcnow + timedelta(seconds = 3)) p4 = Post(body = "post from david", author = u4, timestamp = utcnow + timedelta(seconds = 4)) db_session.add(p1) db_session.add(p2) db_session.add(p3) db_session.add(p4) db_session.commit() # setup the followers u1.follow(u1) # john follows himself u1.follow(u2) # john follows susan u1.follow(u4) # john follows david u2.follow(u2) # susan follows herself u2.follow(u3) # susan follows mary u3.follow(u3) # mary follows herself u3.follow(u4) # mary follows david u4.follow(u4) # david follows himself db_session.add(u1) db_session.add(u2) db_session.add(u3) db_session.add(u4) db_session.commit() # check the followed posts of each user f1 = u1.followed_posts().all() f2 = u2.followed_posts().all() f3 = u3.followed_posts().all() f4 = u4.followed_posts().all() assert len(f1) == 3 assert len(f2) == 2 assert len(f3) == 2 assert len(f4) == 1 assert f1 == [p4, p2, p1] assert f2 == [p3, p2] assert f3 == [p4, p3] assert f4 == [p4]
form = request.form sim = Simulation.query.filter_by(name=request.form['sim']).one() # defaults seed = 0 samples = 10^6 npoints = 1 # lookup job job = Job.query.get(jobid) if job is None: # create job # TODO: check types of seed and samples job = Job(id=jobid, seed=seed, samples=samples, npoints=npoints, sim=sim) db_session.add(job) seed = ok("seed", seed, lambda : abs(int(form['seed']))) samples = ok("samples", samples, lambda : abs(int(form['samples']))) npoints = ok("samples", samples, lambda : abs(int(form['npoints']))) # update job job.seed = seed job.samples = samples job.npoints = npoints job.sim_id = sim.id # commit job db_session.commit() # insert / update params