def showcategoryItem(category): """This page will be for showing all items in the category""" login_already=current_user.is_authenticated() # Get all items in the selected category i = session.query(Item).filter_by(category=category).order_by(desc(Item.create_time)).all() c = session.query(Category).all() return render_template("home.html", c=c, items=i, login_already=login_already)
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 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 question_detail(question_id): page = request.args.get('page', 1, int) session = get_session() offset = (page - 1) * LIMIT question = session.query(Question.id, Question.title, Question.content, ) \ .filter_by(id=question_id).first() if not question: abort(404) answers_query = session.query(Answer.id, Answer.question_id, Answer.user_token, Answer.vote_up, Answer.summary, ).filter(Answer.question_id == question_id) \ .order_by(Answer.vote_up.desc()) answers = answers_query.offset(offset).limit(LIMIT) pagination = get_pagination(answers_query.count(), LIMIT, page) return render_template('question/detail.html', question=question, answers=answers, pagination=pagination)
def get_users(): session = Session() filter_ = literal_eval(request.args.get("filter", "None")) if filter_: if filter_.get("group", None): users = ( session.query(User) .filter(User.shakecast_id > request.args.get("last_id", 0)) .filter(User.groups.any(Group.name.like(filter_["group"]))) .limit(50) .all() ) else: users = session.query(User).filter(User.shakecast_id > request.args.get("last_id", 0)).limit(50).all() else: users = session.query(User).filter(User.shakecast_id > request.args.get("last_id", 0)).limit(50).all() user_dicts = [] for user in users: user_dict = user.__dict__.copy() user_dict.pop("_sa_instance_state", None) user_dicts += [user_dict] user_json = json.dumps(user_dicts, cls=AlchemyEncoder) Session.remove() return user_json
def validate_creation(record_type, name, optional_category_id = None): # Takes a record_type parameter, which determines if the validations performed will be for # item or category. # For Categories, it checks that the name issued doesn't already exist # For items, it checks that the item name doesnt already exist in the same category # For both, it checks that the new name used in creation is not empty # If availabe name and not empty name pass, return true and appropiate message # Else returns false, with another message if record_type == "Category": record = session.query(Category).filter(Category.name.like(name)).first() else: if (optional_category_id == None): raise NameError, "Optional category_id was not given as argument, and was needed" record = session.query(Item).filter(Item.name.like(name)) \ .filter(Item.category_id == optional_category_id).first() new_record = record == None empty_name = len(name) == 0 # Form Validation if new_record and not empty_name: message = "{0} {1} Successfully Created".format(record_type, name) return [True, message] # Prevents Empty Name elif empty_name: print("Failed: Empty Name") message = "{0} Name can't be empty. Try another name".format(record_type) return [False, message] # Prevents Repeated name elif not new_record: print("Failed: Repeated {0}") message = "{0} Name {1} already exists. Try another name".format(record_type, name) return [False, message]
def delete(): repo_id = request.args.get('repo_id', '') build_id = request.args.get('build_id', '') user_id = request.args.get('user_id', '') session = request.db_session delete_target = None if build_id: delete_target = session.query(Build).get(build_id) if not request.user.can_manage: return abort(403) elif repo_id: delete_target = session.query(Repository).get(repo_id) if not request.user.can_manage: return abort(403) elif user_id: delete_target = session.query(User).get(user_id) if delete_target and delete_target.id != request.user.id and not request.user.can_manage: return abort(403) if not delete_target: return abort(404) try: session.delete(delete_target) session.commit() except Build.CanNotDelete as exc: session.rollback() utils.flash(str(exc)) referer = request.headers.get('Referer', url_for('dashboard')) return redirect(referer) utils.flash('{} deleted'.format(type(delete_target).__name__)) return redirect(url_for('dashboard'))
def editItem(item): """This page will be for editing the selected item""" error=None login_already=current_user.is_authenticated() if login_already: i = session.query(Item).filter_by(id=item).one() if request.method == "POST": """Update the infomation of the item. Item's id is used for index the url. And it won't change.""" error=vacant_input("photo") # Check if there is any empty input except photo. if not error: # go on input database if no empty imput. If there any, # reload and labels of the empty form will turn red. i.name= request.form['name'] i.discription= request.form['discription'] i.category= request.form['category'] if request.files['photo']: i.photo=upload_image(i.id) # the photo file will not be change if no file upload. session.add(i) session.commit() return redirect("/item/%s" %item) c = session.query(Category).all() return render_template("add.html", c=c, login_already=login_already, error=error) i=session.query(Item).filter_by(id=item).one() c=session.query(Category).all() return render_template("edit.html", c=c, item=i, login_already=login_already, error=error) else: return redirect("/")
def newItem(): """This page will be for adding a new item.""" error=None login_already=current_user.is_authenticated() # This function will return to homepage if it found user is not login. # There are same setting in pages below which are able to edit the database. if login_already: if request.method == "POST": error = vacant_input() if not error: """go on input database if no empty imput. If there any, reload and labels of the empty form will turn red.""" time_now=datetime.now().strftime("%Y-%m-%d %H:%M:%S") """ Get currunt time and insert to create_time. This will use for index items display order""" i = Item(create_time=time_now, name=request.form['name'], discription=request.form['discription'], category=request.form['category']) session.add(i) session.flush() i.photo=upload_image(i.id) session.commit() return redirect("/") c = session.query(Category).all() return render_template("add.html", c=c, login_already=login_already, error=error) c = session.query(Category).all() return render_template("add.html", c=c, login_already=login_already, error=error) else: return redirect("/")
def dashboard(): session = request.db_session context = {} context['repositories'] = session.query(Repository).order_by(Repository.name).all() context['user'] = request.user context['public_key'] = get_public_key() context['all_users'] = session.query(User).all() return render_template('dashboard.html', **context)
def edit_view(rid): #debug if(request.form.has_key('subbtn')): subbtn = request.form['subbtn'] app.logger.debug("subbtn = %s" % subbtn) else: app.logger.debug("no subbtn key") subbtn=None rec = session.query(Records).filter(Records.id == rid).first() form = EditForm(request.form, obj=rec) # set choices l = Records.getValuesFromField('phase') form.phase.choices = listToChoices(l) form.final_action.choices = listToChoices(Records.getValuesFromField('final_action')) if form.validate_on_submit(): val = True else: val = False if subbtn: if subbtn == form.cancel: app.logger.debug("cancel") flash("Changes canceled") return redirect('/select/') else: app.logger.debug("saving record") #form.populate_obj(rec) # f***s up boolean nulls data = form.data for d in data: print "ghetto populate: %s -> %s" % (d, data[d]) setattr(rec,d,data[d]) if val and not subbtn==form.saveselect: rec.status ="%s-done" % session.query(User).filter(id=uid).first().initials session.add(rec) session.commit() if subbtn == form.savenext: rec.checkin(current_user.id) n = getNextRecord() msg = record.checkout(current_user.id) flash(msg) return redirect('/edit/%d' % n.id) elif subbtn==form.saveselect: flash("Record saved but not checked in") return redirect('/select/') if form.errors: app.logger.debug("oh shit:") app.logger.debug(form.errors) flash("error") app.logger.debug("edit form validation failed") return render_template('records/edit.html', form=form, rec=rec, idx=AutoIncrement() )
def remainingRecords(order_asc = True): # unreviewed records have no open edits - either in and out are both null (never edited) or # both are not null (edit has closed) sq = session.query(Edits.rid).filter(Edits.date_in==None).filter(Edits.date_out!=None).subquery() q = session.query(Records).filter(Records.status=='unreviewed').filter(not_(Records.id.in_(sq))) if order_asc: q = q.order_by(asc(Records.title)) else: q = q.order_by(desc(Records.title)) return q.all()
def test_write_bill_committees(self): query = session.query(bill_committee).all() startSize = len(query) session.add(bill_committee(bill_id=7, committee_id=5)) res = session.query(bill_committee).all() endSize = len(res) self.assertEqual(startSize + 1, endSize) query = session.query(bill_committee).filter(bill_committee.bill_id == 7).first() session.delete(query)
def test_write_votes(self): query = session.query(vote).all() startSize = len(query) session.add(vote(legislator_id=1, bill_id=2)) res = session.query(vote).all() endSize = len(res) self.assertEqual(startSize + 1, endSize) query = session.query(vote).filter(vote.legislator_id == 1).first() session.delete(query)
def pleblist_history_redirect(): with DBManager.create_session_scope() as session: current_stream = session.query(Stream).filter_by(ended=False).order_by(Stream.stream_start.desc()).first() if current_stream is not None: return redirect('/pleblist/history/{}/'.format(current_stream.id), 303) last_stream = session.query(Stream).filter_by(ended=True).order_by(Stream.stream_start.desc()).first() if last_stream is not None: return redirect('/pleblist/history/{}/'.format(last_stream.id), 303) return render_template('pleblist_history_no_stream.html'), 404
def chatChannelStatus(channel_id): messages = session.query(ChatChannelMessage, User).filter_by(channel_id=channel_id).join(User).order_by(ChatChannelMessage.timestamp.desc()).limit(10).all() messagesJson = [] for message, user in messages: messagesJson.append('{"message": "'+message.message+'", "username": "******", "timestamp": "'+ message.timestamp.strftime('%H:%m:%S') +'"}') messagesJson.reverse() users = session.query(User).filter_by(currentChatChannelId=channel_id).all() usersJson=[e.toJson() for e in users] return jsonify(users=usersJson, messages=messagesJson)
def test_write_legislator_3(self): query = session.query(legislator).all() startSize = len(query) session.add(legislator(first_name="WRITETHREE", party="TEST")) session.commit() query = session.query(legislator).all() endSize = len(query) self.assertEqual(startSize + 1, endSize)
def test_write_legislator_multiple(self): query = session.query(legislator).all() startSize = len(query) session.add(legislator(first_name="TESTMULTIPLE", party="TEST")) session.add(legislator(first_name="TESTMULTIPLE", party="TEST")) session.commit() query = session.query(legislator).all() endSize = len(query) self.assertEqual(startSize + 2, endSize)
def home(): # Shows the homepage for the catalog project, displaying all categories and latest items categories = session.query(Category).order_by(Category.id.desc()).all() items = session.query(Item).order_by(Item.id.desc()).limit(10) # Forgery Protection state = ''.join(random.choice(string.ascii_uppercase + string.digits) for x in xrange(32)) login_session['state'] = state return render_template("home.html", items= items, categories = categories, \ login_session = login_session, state = state)
def update_count(winner, loser): Session = sessionmaker() engine = create_engine('sqlite:///' + os.path.join(basedir, 'data-dev.sqlite')) Session.configure(bind=engine) session = Session() curr_usr = session.query(Post).get(winner) loser_guy = session.query(Post).get(loser) session.query(Post).filter_by(id=winner).update({'total_votes': curr_usr.total_votes+1}) session.commit() flash("{} has {} votes and {} has {} votes".format(curr_usr.description, curr_usr.total_votes, loser_guy.description, loser_guy.total_votes)) return redirect(url_for('main.index'))
def test_write_committees(self): query = session.query(committee).all() startSize = len(query) session.add(committee(name="TEST")) res = session.query(committee).all() session.commit() query = session.query(committee).all() endSize = len(query) self.assertEqual(startSize + 1, endSize)
def test_delete_bill_row2(self): session.add(bill(name="delete2")) session.commit() query = session.query(bill).filter(bill.name == "delete2").first() assert query != None session.delete(query) session.commit() toRemove = session.query(bill).filter(bill.name == "delete2").first() assert toRemove == None
def test_write_bills(self): query = session.query(bill).all() startSize = len(query) session.add(bill(name="Test")) res = session.query(bill).all() session.commit() query = session.query(bill).all() endSize = len(query) self.assertEqual(startSize + 1, endSize)
def test_delete_committee_members_row(self): session.add(committee_member(legislator_id=10, committee_id=10)) session.commit() query = session.query(committee_member).filter(committee_member.legislator_id == 10).first() assert query != None session.delete(query) session.commit() toRemove = session.query(committee_member).filter(committee_member.legislator_id == 10).first() assert toRemove == None
def test_delete_votes_row(self): session.add(vote(legislator_id=5, bill_id=6)) session.commit() query = session.query(vote).filter(vote.legislator_id == 5).first() assert query != None session.delete(query) session.commit() toRemove = session.query(vote).filter(vote.legislator_id == 5).first() assert toRemove == None
def test_delete_bill_committees_row(self): session.add(bill_committee(bill_id=9, committee_id=10)) session.commit() query = session.query(bill_committee).filter(bill_committee.bill_id == 9).first() assert query != None session.delete(query) session.commit() toRemove = session.query(bill_committee).filter(bill_committee.bill_id == 9).first() assert toRemove == None
def new_expense(): expense_accounts = session.query(AccountAccount)\ .filter_by(user_id=user_id, account_type='expense', is_quick=True)\ .order_by(AccountAccount.code) print expense_accounts bank_accounts = session.query(AccountAccount)\ .filter_by(user_id=user_id, account_type='bank', is_possible_to_pay=True)\ .order_by(AccountAccount.code) return render_template( 'new_expense.html', expense_accounts=expense_accounts, bank_accounts=bank_accounts, )
def test_write_committee_members(self): query = session.query(committee_member).all() startSize = len(query) session.add(committee_member(legislator_id=8, committee_id=8)) res = session.query(committee_member).all() session.commit() query = session.query(committee_member).all() endSize = len(query) self.assertEqual(startSize + 1, endSize) query = session.query(committee_member).filter(committee_member.legislator_id == 8).first() session.delete(query)
def test_read_bill_committees(self): session.add(bill_committee(bill_id=8, committee_id=9)) session.commit() query = session.query(bill_committee).all() found = False for x in query: if x.bill_id == 8: found = True assert found query = session.query(bill_committee).filter(bill_committee.bill_id == 8).first() session.delete(query)
def new_cashout(): bank_out_accounts = session.query(AccountAccount)\ .filter_by(user_id=user_id, account_type='bank', is_cash_out=True)\ .order_by(AccountAccount.code) bank_in_accounts = session.query(AccountAccount)\ .filter_by(user_id=user_id, account_type='bank', is_cash_in=True)\ .order_by(AccountAccount.code) return render_template( 'new_cashout.html', single_bank_out=len([x for x in bank_out_accounts])==1, single_bank_in=len([x for x in bank_in_accounts])==1, bank_out_accounts=bank_out_accounts, bank_in_accounts=bank_in_accounts, )
def productoverzicht(): projecten = session.query(Project).all() return render_template('productoverzicht.html', projecten = projecten)
def index(): session = db_session.create_session() products = session.query(Products) return render_template("index.html", products=products)
def index(): jobs = session.query(Job).all() return render_template('jobs.html', jobs=jobs)
def register_verify(): if request.method == "GET": return make_response( jsonify({ "error": 0, "content": { "message": "/account/register/verify[get]" } })) timestamp = int(datetime.datetime.now().timestamp()) try: if session.query(Mail_verify).first().timestamp < timestamp - 1800: reflesh_mail_verify(timestamp) except AttributeError: pass invalid_id = 0 authenticated = 0 invalid_code = 0 request_json = request.get_json() if request_json["authenticated"]: authenticated = 1 verify = session.query(Mail_verify).filter( Mail_verify.id.in_([request_json["verify_id"]])).first() if not verify: invalid_id = 1 else: verify = session.query(Mail_verify).filter( Mail_verify.id.in_([request_json["verify_id"]]), Mail_verify.code.in_([request_json["code"]])).first() if not verify: invalid_code = 1 if invalid_code or authenticated or invalid_id: return make_response( jsonify({ "error": 1, "content": { "authenticated": authenticated, "invalid_verify_id": invalid_id, "invalid_code": invalid_code } })) user = User(user_id=verify.user_id, name=verify.name, password=verify.password, token=verify.token, email=verify.email) session.add(user) session.delete(verify) session.commit() return make_response( jsonify({ "error": 0, "content": { "logged_id": user.id, "logged_user_id": user.user_id, "logged_name": user.name, "token": user.token, "message": "successful registration" } }))
def load_user(id): quan_tri = session.query(NguoiDung).filter( NguoiDung.ma_nguoi_dung == id).first() return quan_tri
def todosJSON(): if request.method == 'POST': try: body = request.data body = json.loads(body.decode('utf-8')) user = session.query(User).filter_by( email=body['email']).one_or_none() if user: task = session.query(Task).filter_by(user_id=user.id).all() return jsonify(tasks=[r.serialize for r in task], count=len(task)) user = User(name=body['name'], email=body['email']) session.add(user) session.commit() return jsonify(tasks=[], count=0) except exceptions.SQLAlchemyError: sys.exit("Encountered general SQLAlchemyError. Call an adult!") if request.method == 'PUT': body = request.data body = json.loads(body.decode('utf-8')) user = session.query(User).filter_by(email=body['email']).one_or_none() if not user: user = User(name=body['name'], email=body['email']) session.add(user) session.commit() todo = Task(task=body['task'], user_id=user.id) session.add(todo) session.commit() return jsonify(todo.serialize) if request.method == 'DELETE': body = request.data body = json.loads(body.decode('utf-8')) user = session.query(User).filter_by(email=body['email']).one_or_none() if user: task = session.query(Task).filter_by(user_id=user.id, id=body['id']).one_or_none() if task: session.delete(task) session.commit() return jsonify(success=True) return jsonify(error="You are not authorized to this todo!") if request.method == 'PATCH': body = request.data body = json.loads(body.decode('utf-8')) user = session.query(User).filter_by(email=body['email']).one_or_none() if user: todo = session.query(Task).filter_by(user_id=user.id, id=body['id']).one_or_none() todo.task = body['task'] todo.status = body['status'] session.add(todo) session.commit() return jsonify(todo.serialize) return jsonify(error="You are not authorizedto this todo!") # return "GET HANDLER NOT DEFINED" task = session.query(Task).all() return jsonify(tasks=[r.serialize for r in task], count=len(task))
def profile(user_id=None): form = SignUpForm() form.submit.data = 'SAVE' session = db.session() if not user_id and current_user.is_authenticated(): user_id = current_user.get_id() account = current_user else: account = getAccount(user_id) if account.ZipCode: location = session.query(Location).filter_by( ZipCode=account.ZipCode).first() else: location = Location() #account = getAccount(user_id) #account = session.query(Accounts).filter_by(Id=user_id).first() if form.validate_on_submit(): account = session.query(Accounts).filter_by(Id=user_id).first() account.Customer = request.form.get('user_ssn') account.UserName = request.form.get('user_name') account.PassWord = request.form.get('user_password') account.Email = request.form.get('user_email') account.CreditCardNumber = request.form.get('credit_card') account.LastName = request.form.get('last_name') account.FirstName = request.form.get('first_name') account.Address = request.form.get('address') account.ZipCode = None if not request.form.get('zipcode') \ else int(request.form.get('zipcode')) account.Phone = None if not request.form.get('phone') \ else int(request.form.get('phone')) upType = 0 if account.is_admin(): form.account_type.data = account.Type else: upType = 1 if request.form.get( 'account_type') > account.Type else 0 account.Type = request.form.get('account_type') zipcode_check = session.query(Location).filter_by( ZipCode=account.ZipCode).first() if not zipcode_check: newLocation = Location() newLocation.ZipCode = account.ZipCode newLocation.City = request.form.get('city') newLocation.State = request.form.get('state') session.add(newLocation) session.commit() else: zipcode_check.City = request.form.get('city') zipcode_check.State = request.form.get('state') try: session.commit() except: flash("Database error!") traceback.print_exc(file=sys.stdout) session.rollback() render_template("profile.html", action=1, form=form) print('return pro') if upType: flash("Thanks for Your $$$!") else: flash("Saved successful!") return render_template( "profile.html", title="PROFILE", action=1, #profile form=form) form.user_name.data = account.UserName form.user_password.data = account.PassWord form.account_type.data = account.Type form.last_name.data = account.LastName form.first_name.data = account.FirstName form.address.data = account.Address form.zipcode.data = account.ZipCode form.phone.data = account.Phone form.credit_card.data = account.CreditCardNumber form.user_email.data = account.Email if account.ZipCode: localtion = session.query(Location).filter_by( ZipCode=account.ZipCode).first() form.city.data = location.City form.state.data = location.State return render_template("profile.html", form=form)
def clear_table(): session.query(Notes).delete() session.commit()
def notes(): Session = sessionmaker(bind=engine) session = Session() notes_list = session.query(Notes).order_by(Notes.unique_quantity.desc()) return render_template("notes.html", notes_list=notes_list)
def new(): session = db_session.create_session() news = session.query(News).all() image = url_for('static', filename='images/') logo = url_for('static', filename='images/logo.png') return render_template('news.html', news=news, image=image, logo=logo)
def message_follow(): data = {} id = [] user = [] text = [] time = [] comment = [] retrant = [] upvote = [] ifretrant = [] retrantposter = [] retranttext = [] avatar = [] ifphoto = [] photo1 = [] photo2 = [] photo3 = [] photo4 = [] photo5 = [] photo6 = [] photo7 = [] photo8 = [] photo9 = [] page = int(request.args.get('page_num')) minpage = 5 * page maxpage = 5 * (page + 1) db_engine = create_engine('mysql://*****:*****@localhost/my_message?charset=utf8') Session = sessionmaker(bind=db_engine) session = Session() number = session.query(func.count(input_message.post_id).label("page_num")).filter( input_message.poster == follows.followed).filter(follows.follower == current_user.username).first() profilephoto = personal.query.filter(personal.username == current_user.username).first() if profilephoto: if profilephoto.avatar is not None: current_avatar = profilephoto.avatar else: current_avatar = 'user.png' else: current_avatar = 'user.png' results = input_message.query.filter( input_message.poster == follows.followed).filter(follows.follower == current_user.username).order_by( input_message.post_id.desc()).all() number = len(results) if maxpage < number: for x in range(minpage + 4, minpage - 1, -1): name = results[x].poster myresult = personal.query.filter(personal.username == name).first() id.append(results[x].post_id) user.append(results[x].poster) text.append(results[x].post_text) time.append(results[x].post_time) comment.append(results[x].comment_num) retrant.append(results[x].retrant_num) upvote.append(results[x].upvote_num) ifretrant.append(results[x].if_retrant) retrantposter.append(results[x].retrant_poster) retranttext.append(results[x].retrant_text) photo1.append(results[x].photo1) photo2.append(results[x].photo2) photo3.append(results[x].photo3) photo4.append(results[x].photo4) photo5.append(results[x].photo5) photo6.append(results[x].photo6) photo7.append(results[x].photo7) photo8.append(results[x].photo8) photo9.append(results[x].photo9) ifphoto.append(results[x].if_photo) name = results[x].poster myresult = personal.query.filter(personal.username == name).first() if myresult: if myresult.avatar is not None: avatar.append(myresult.avatar) else: avatar.append('user.png') else: avatar.append('user.png') else: for x in range(number - 1, minpage - 1, -1): id.append(results[x].post_id) user.append(results[x].poster) text.append(results[x].post_text) time.append(results[x].post_time) comment.append(results[x].comment_num) retrant.append(results[x].retrant_num) upvote.append(results[x].upvote_num) ifretrant.append(results[x].if_retrant) retrantposter.append(results[x].retrant_poster) retranttext.append(results[x].retrant_text) photo1.append(results[x].photo1) photo2.append(results[x].photo2) photo3.append(results[x].photo3) photo4.append(results[x].photo4) photo5.append(results[x].photo5) photo6.append(results[x].photo6) photo7.append(results[x].photo7) photo8.append(results[x].photo8) photo9.append(results[x].photo9) ifphoto.append(results[x].if_photo) name = results[x].poster myresult = personal.query.filter(personal.username == name).first() if myresult: if myresult.avatar is not None: avatar.append(myresult.avatar) else: avatar.append('user.png') else: avatar.append('user.png') data['po_id'] = id data['po_user'] = user data['po_text'] = text data['po_time'] = time data['po_comment'] = comment data['po_retrant'] = retrant data['po_upvote'] = upvote data['po_ifretrant'] = ifretrant data['po_retrant_poster'] = retrantposter data['po_retrant_text'] = retranttext data['avatar'] = avatar data['current_user'] = current_avatar data['photo1'] = photo1 data['photo2'] = photo2 data['photo3'] = photo3 data['photo4'] = photo4 data['photo5'] = photo5 data['photo6'] = photo6 data['photo7'] = photo7 data['photo8'] = photo8 data['photo9'] = photo9 data['po_ifphoto'] = ifphoto return jsonify(data)
user4 = User(id=4, name='hamster', fullname='Song Wendy', password='******') user5 = User(id=5, name='turtle', fullname='Kim Yeri', password='******') user6 = User(id=6, name='duck', fullname='Choi Joy', password='******') session.add(user1) session.add(user2) session.add(user3) session.add(user4) session.add(user5) session.add(user6) session.commit() alldatabase = session.query(User) @app.route("/") def login_page(): return render_template('HTML.html') @app.route('/dologin/', methods=['POST']) def dologin(): yeslogin = False if request.method == 'POST': user = request.form['user'] passw = request.form['passw']
def projecten(): projecten = session.query(Project).all() print(projecten) return render_template('projecten.html', projecten = projecten)
def load_user(user_id): session = db_session.create_session() return session.query(User).get(user_id)
def show_targets(): targets = session.query(Target).all() print(targets) return (render_template('ssrf/targets.html', targets=targets))
def chat_get(): if request.method == "GET": return make_response( jsonify({ "error": 0, "content": { "message": "/chat/get[get]" } })) request_json = request.get_json() not_authenticated = 0 invalid_verify = 0 user = verify_token(request_json["id"], request_json["token"]) if not request_json["authenticated"]: not_authenticated = 1 if not user: invalid_verify = 1 if not_authenticated or invalid_verify: return make_response( jsonify({ "error": 1, "content": { "not_authenticated": not_authenticated, "invalid_verify": invalid_verify } })) if request_json["content"]["talk_all_need"]: return make_response( jsonify({ "error": 0, "content": { "talk": { str(talk.id): { "name": talk.name, "content": { "new": [{ "sent_user_id": cont.user_id, "sent_user_name": session.query(User).get(cont.user_id).name, "content_type": cont.type, "content_content": cont.content, "content_id": cont.id, "timestamp": cont.timestamp } for cont in talk.content.filter( Content.id > zero_or_go( request_json["content"]["talk_his"], talk)).all()] } } for talk in user.talk_groups } }, })) else: return make_response( jsonify({ "error": 0, "content": { "talk": { str(talk.id): { "name": talk.name, "content": { "new": [{ "sent_user_id": cont.user_id, "sent_user_name": session.query(User).get(cont.user_id).name, "content_type": cont.type, "content_content": cont.content, "content_id": cont.id } for cont in talk.content.filter( Content.id > zero_or_go( request_json["content"]["talk_his"], talk)).all()] } } for talk in user.talk_groups.filter( Talk_group.id.in_(request_json["content"] ["talk_his"].keys())).all() } }, }))
def all_fires(): fires = session.query(Fire).all() return (render_template('ssrf/fires.html', fires=fires))
def show_fires(target): target = session.query(Target).filter_by(name=target).first() fires = session.query(Fire).filter_by(target=target) return (render_template('ssrf/fires.html', target=target, fires=fires))
def discoverSettings(): """ Check whether a global settings database exists on supplied database server .. :quickref: Get DAQBroker settings; Get global DAQBroker settings :returns: JSON encoded list of session server objects with the following keys: | ``currentServer`` : (String) server address | ``currentEngine`` : (String) server database SQL engine | ``settingsExist`` : (Boolean) global settings database exists. Should only return False if a user has logged in for the first time to the engine | ``monActive`` : (Boolean) returns True if a server monitoring process is currently underway """ global servers try: # engineURL=current_user.engine+'://'+current_user.username+':'+current_user.password+"@"+current_user.server+"/daqbroker_settings" toReturn = { 'currentServer': current_user.server, 'currentEngine': current_user.engine, 'settingsExist': database_exists(current_user.uriSettings), 'adminExist': False } # newEngine=create_engine(engineURL) Session = sessionmaker(bind=current_user.engineObjSettings) session = Session() if database_exists(current_user.uriSettings): theUser = session.query(daqbrokerSettings.users).filter_by( username=current_user.username).first() foundServer = False for i, server in enumerate(current_app.config['servers']): temp = server #print(theUser) if server["server"] == current_user.server and server[ "engine"] == current_user.engine: toReturn['monActive'] = temp["monActive"] foundServer = True if theUser.type == 1: temp['username'] = current_user.username temp['password'] = current_user.password current_app.config['servers'][i] = temp toReturn['adminExist'] = True else: if server["username"] + server[ "password"] != "NONENONE": toReturn['adminExist'] = True break if not foundServer: serversTentative = { 'server': current_user.server, 'engine': current_user.engine, 'username': '******', 'password': '******', "monActive": False } if theUser.type == 1: serversTentative['username'] = current_user.username serversTentative['password'] = current_user.password serversTentative['monActive'] = True toReturn['adminExist'] = True current_app.config['servers'].append({ 'server': current_user.server, 'engine': current_user.engine, 'username': serversTentative['username'], 'password': serversTentative['password'], 'monActive': serversTentative['monActive'] }) toReturn['monActive'] = current_app.config['servers'][-1][ "monActive"] toReturn["username"] = current_user.username return jsonify(toReturn) except Exception as e: traceback.print_exc() raise InvalidUsage(str(e), status_code=500)
def get_viajeros(): session = db.getSession(engine) dbResponse = session.query(entities.Viajero) data = dbResponse[:] return Response(json.dumps(data, cls=connector.AlchemyEncoder), mimetype='application/json')
def edit_Item(): try: Pk = request.form.get("Pk", "null") field = request.form.get("name", "null") value = request.form.get("value", 'null') dropdownMenus = request.form.getlist('dropdownMenus[]') dropdownKey = request.form.get("dropDownKey", 'null') funItem = session.query(FunItem).filter_by(Pk=Pk).first() if (field == 'DerivedRuleDec'): funItem.DerivedRuleDec = value if (field == 'DropDownbox'): dropmenus = [] titles = [] itemlist = session.query(FunItemList).filter_by( DropDownboxKey=value).all() if (itemlist): #获取该key下面的所有下拉菜单 for item in itemlist: dropmenus.append(item.ItemValueCn) titles.append(item.ItemTitle) else: #如果该Key之前没绑定过下拉菜单,则默认将现有下拉菜单的内容赋值给该下拉菜单 for v in dropdownMenus: dropmenus.append(str(v).split('[')[0]) title = re.findall(r"(\[.*?\])", v, re.M) if (len(title) > 0): title = title[0] titles.append(title.replace('[', '').replace(']', '')) """删除所有的跟该PK相关的funItemList,对下来菜单进行重新赋值""" itemList = session.query(FunItemList).filter_by( FunItemsFk=Pk).all() for list in itemList: session.delete(list) session.commit() for i in range(0, len(dropmenus)): itemlist = FunItemList(FunItemsFk=Pk, ItemValueEn=None, ItemValueCn=unicode(dropmenus[i]), ItemTitle=unicode(titles[i]), ItemOrder=i + 1, CreatedTime=datetime.now(), DropDownboxKey=value) session.add(itemlist) session.commit() #给funItem这个字段绑定下拉菜单的值 funItem.DropDownbox = value if (field == 'FunItemValueCn'): funItem.FunItemValueCn = value if (field == 'OpenSelectKey'): funItem.OpenSelectKey = value if (field == 'dropdownMenus'): #当DropdownMenu不为空时,判断DropdownKey不能为空 if (value) and not (dropdownKey): return "KeyError" else: #删除现有绑定的下拉菜单 itemList = session.query(FunItemList).filter_by( DropDownboxKey=dropdownKey).all() for list in itemList: session.delete(list) session.commit() if (value): value = value.split('\n') i = 1 for v in value: dropMenu = v.split('[')[0] title = re.findall(r"(\[.*?\])", v, re.M) if (len(title) > 0): title = title[0] title = title.replace('[', '').replace(']', '') cur = datetime.now() itemlist = FunItemList(FunItemsFk=Pk, ItemValueEn=None, ItemValueCn=dropMenu, ItemTitle=title, ItemOrder=i, CreatedTime=cur, DropDownboxKey=dropdownKey) session.add(itemlist) session.commit() i = i + 1 session.add(funItem) session.commit() return 'success' except: session.rollback() return "error"
def __repr__(self): return "<User(name='%s', fullname='%s', password='******')>" % ( self.name, self.fullname, self.password) print(User.__table__) Base.metadata.create_all(engine) # table 생성 ed_user = User('simpson', 'homor simpson', '1234') print(ed_user.name) session = Session() session.add(ed_user) our_user = session.query(User).filter_by(name='simpson').first() print(our_user) print(ed_user is our_user) ed_user.password = '******' print(session.dirty) session.add_all([ User('wendy', 'Wendy Williams', 'foobar'), User('mary', 'Mary Contrary', 'xxg527'), User('fred', 'Fred Flinstone', 'blar') ]) print(session.new) session.commit()
def chat_join_other(): if request.method == "GET": return make_response( jsonify({ "error": 0, "content": { "message": "/chat/join/other[get]" } })) request_json = request.get_json() not_authenticated = 0 invalid_verify = 0 invalid_user_id = 0 invalid_talk_id = 0 user_not_joined = 0 already_joined = 0 user = verify_token(request_json["id"], request_json["token"]) if request_json["content"]["use_id"]: target_user = session.query(User).get( request_json["content"]["target_user_id"]) else: target_user = session.query(User).filter( User.user_id.in_([request_json["content"]["target_user_id"] ])).first() target_group = session.query(Talk_group).get( request_json["content"]["target_group"]) if not request_json["authenticated"]: not_authenticated = 1 if not user: invalid_verify = 1 else: if target_group not in user.talk_groups: user_not_joined = 1 if not target_user: invalid_user_id = 1 elif target_group in target_user.talk_groups: already_joined = 1 if not target_group: invalid_talk_id = 1 if not_authenticated or invalid_verify or already_joined or invalid_talk_id or \ invalid_user_id: return make_response( jsonify({ "error": 1, "content": { "not_authenticated": not_authenticated, "invalid_verify": invalid_verify, "invalid_user_id": invalid_user_id, "invalid_talk_id": invalid_talk_id, "user_not_joined": user_not_joined, "already_joined": already_joined } })) target_user.talk_groups.append(target_group) session.commit() return make_response( jsonify({ "error": 0, "content": { "message": "success" } }))
def reflesh_mail_verify(time): session.query(Mail_verify).filter( Mail_verify.timestamp < time - 1800).delete() session.commit()
def register(): if request.method == "GET": return make_response( jsonify({ "error": 0, "content": { "message": "/account/register/register[get]" } })) exist_id = 0 # アカウントの存在 authenticated = 0 # すでにログインしているか bad_id = 0 # idのよしあし bad_name = 0 # nameのよしあし bad_password = 0 # passwordのよしあし password_confirm_does_not_match = 0 # passwordのコンファームが合致しているかどうかです request_json = request.get_json() if request_json["authenticated"]: authenticated = 1 if session.query(User).filter(User.user_id.in_([request_json["user_id"] ])).first(): exist_id = 1 if not id_re.match(request_json["user_id"]): bad_id = 1 if not 0 < len(request_json["name"]) < 32: bad_name = 1 if not passw_re.match(request_json["password"]): bad_password = 1 if request_json["password"] != request_json["password_confirm"]: password_confirm_does_not_match = 1 if exist_id or authenticated or bad_id or bad_name or bad_password or password_confirm_does_not_match: return make_response( jsonify({ "error": 1, "content": { "authenticated": authenticated, "exist_id": exist_id, "bad_id": bad_id, "bad_name": bad_name, "bad_password": bad_password, "password_confirm_does_not_match": password_confirm_does_not_match } })) code = "%04d" % random.randint(0, 9999) send_mail(code=code, email=request_json["email"], name=request_json["name"]) token = secrets.token_hex() timestamp = int(datetime.datetime.now().timestamp()) user = Mail_verify( user_id=request_json["user_id"], name=request_json["name"], password=str( hashlib.sha256(b"%a" % str(request_json["password"])).digest()), token=token, code=code, email=request_json["email"], timestamp=timestamp) try: if session.query(Mail_verify).first().timestamp < timestamp - 1800: reflesh_mail_verify(timestamp) except AttributeError: pass session.add(user) session.commit() return make_response( jsonify({ "error": 0, "content": { "verify_id": user.id } }))
def showTask(task_id): task = session.query(Tasks).filter_by(id=task_id) return render_template('task.html', task=task)
def account_modify(): if request.method == "GET": return make_response( jsonify({ "error": 0, "content": { "message": "/account/modify[get]" } })) not_authenticated = 0 invalid_verify = 0 exist_id = 0 bad_id = 0 bad_name = 0 bad_password = 0 password_confirm_does_not_match = 0 request_json = request.get_json() user = valid_auth(request_json["user_id"], request_json["password"]) if not request_json["authenticated"]: not_authenticated = 1 if not user: invalid_verify = 1 if not (invalid_verify or not_authenticated): if session.query(User).filter( User.user_id.in_([request_json["modify"]["user_id"]])).first(): exist_id = 1 if not id_re.match(request_json["modify"]["user_id"] ) and request_json["modify"]["user_id"] != "": bad_id = 1 if not 0 < len(request_json["modify"]["name"]) < 32: bad_name = 1 if not passw_re.match(request_json["modify"]["password"] ) and request_json["modify"]["password"] != "": bad_password = 1 if request_json["modify"]["password"] != request_json["modify"][ "password_confirm"]: password_confirm_does_not_match = 1 if not (exist_id or bad_id or bad_name or bad_password or password_confirm_does_not_match or invalid_verify): if request_json["modify"]["user_id"]: user.user_id = request_json["modify"]["user_id"] if request_json["modify"]["password"]: user.password = str( hashlib.sha256( b"%a" % str(request_json["modify"]["password"])).digest()) if request_json["modify"]["name"]: user.name = request_json["modify"]["name"] session.commit() return make_response( jsonify({ "error": 0, "content": { "new_id": user.user_id, "new_name": user.name, "message": "modified successfully" } })) return make_response( jsonify({ "error": 1, "content": { "not_authenticated": not_authenticated, "invalid_verify": invalid_verify, "exist_id": exist_id, "bad_id": bad_id, "bad_name": bad_name, "bad_password": bad_password, "password_confirm_does_not_match": password_confirm_does_not_match } }))
def completed(task_id): task = session.query(Tasks).filter_by(id=task_id) return render_template('completed.html', task=task)
def chat_send(): if request.method == "GET": return make_response( jsonify({ "error": 0, "content": { "message": "/chat/send[get]" } })) request_json = request.get_json() not_authenticated = 0 invalid_talk_id = 0 invalid_verify = 0 too_long_text = 0 not_join = 0 meaningless_text = 0 user = verify_token(request_json["id"], request_json["token"]) if not request_json["authenticated"]: not_authenticated = 1 if not user: invalid_verify = 1 if request_json["content"]["content"] == 1: if len(request_json["content"]["content"]) > 1024: too_long_text = 1 if not request_json["content"]["content"].strip(): meaningless_text = 1 talk = session.query(Talk_group).get(request_json["content"]["talk_id"]) if not talk: invalid_talk_id = 1 else: if user not in talk.users: not_join = 1 if not_authenticated or invalid_verify or too_long_text or meaningless_text or invalid_talk_id or not_join: return make_response( jsonify({ "error": 1, "content": { "not_authenticated": not_authenticated, "invalid_verify": invalid_verify, "not_join": not_join, "invalid_talk_id": invalid_talk_id, "too_long_text": too_long_text, "meaningless_text": meaningless_text } })) cont = Content( user_id=user.id, talk_group_id=talk.id, type=request_json["content"]["type"], content=request_json["content"]["content"].strip(), timestamp=datetime.datetime.utcnow().strftime("%Y:%m:%d:%H:%M:%S")) session.add(cont) talk.content.append(cont) session.commit() return make_response( jsonify({ "error": 0, "content": { "talk_id": talk.id, "message": "sent successfully" } }))
def get_sheets(): sheets = session.query(models.Sheets).filter_by(user_id=1).all() contents = {} contents['names'] = [sheet.sheet_name for sheet in sheets] return jsonify(contents)