def put(self, id=None): #Если запрос неправильный, то возвращаем 400 Bad Request if not request.json: abort(400) return '' json = request.json #Создаем новый объект bill = Bill() bill.init_of_dict(json) if not bill.id: #Если id не был дан, то возвращаем ошибку res = {'status': 'error', 'message': 'Не найден обязательный параметр: id'} return jsonify(res) else: if not int(bill.id) in list(map(lambda item: int(item.id), current_user.bills)): return jsonify({'status': 'error', 'message': 'У вас нет прав на изменение этой задачи!'}) #Находим задачу и обновляем данные if Bill.query.filter_by(id = bill.id).first() != None: Bill.query.filter_by(id = bill.id).update(bill.to_dict()) db.session.commit() res = {'status': 'done', 'message': 'Данные обновлены'} return jsonify(res) else: #Если задача не найдена, то возвращаем ошибку res = {'status': 'error', 'message': 'Данные с таким id не найдены'} return jsonify(res)
def test_bill_creation(self): # create users u1 = User(username='******', email='*****@*****.**') u2 = User(username='******', email='*****@*****.**') u3 = User(username='******', email='*****@*****.**') u4 = User(username='******', email='*****@*****.**') db.session.add_all([u1, u2, u3, u4]) db.session.commit() # create a bill to split b = Bill(title='New Bill', desc='some description', amount=250, payer=u3) db.session.add(b) db.session.commit() self.assertTrue(len(b.bill_details) == 1) self.assertTrue(b.bill_details[0].user == u3) participants = [u1, u2, u3, u4] shares = [50, 100, 75, 25] for participant, share in zip(participants, shares): b.add_participant(participant, share) db.session.commit() self.assertTrue(len(b.bill_details) == 4)
def post(self): # Если запрос неправильный, то возвращаем 400 Bad Request if not request.json: abort(400) # Если пользователь не авторизован или он студент, то он не имеет право создавать задачи if not current_user.is_authenticated: abort(401) if current_user.activity == 'Студент': abort(403) json = request.json # Проверка наличие обязательних данных if not json['title'] or not json['description'] or not json['sum']: res = {'status': 'error', 'message': 'Не заполнены обязательних поля'} return jsonify(res); #Создаем новый объект bill = Bill() bill.init_of_dict(json) # current_user.bills.append(bill) try: #Пытаемся добавить полученные данные в БД db.session.add(bill) db.session.commit() except: #Если не получилось, то возвращаем ошибку res = {'status': 'error', 'message': 'Такие данные уже существуют'} return jsonify(res) res = {'status': 'done', 'message': 'Данные добавлены'} return jsonify(res)
def put_bill(doctor_id, patient_id, orderlist_id): data = request.get_json() or {} bill = Bill(doctor_id=doctor_id, patient_id=patient_id, orderlist_id=orderlist_id) bill.from_dict(data) db.session.add(bill) db.session.commit() return jsonify({'code': 200})
def reply_handler(bot, update): tg_user = update.message.from_user text = update.message.text raw = Redis.get(tg_user.username) if raw is None: Redis.set( tg_user.username, json.dumps({ 'category': text, 'type': 'out' if text != IN_KEYWORD else 'in' })) update.message.reply_text(f'账单类别:{text},请输入账单金额\n若想取消本次操作,请输入 /cancel') else: bill = json.loads(raw) user = User.query.filter_by(username=tg_user.username).first() splited_text = text.split(' ') if len(splited_text) == 2: amount, name = splited_text bill.update({ 'amount': Decimal(amount), 'name': name, 'user_id': user.id }) else: amount = text bill.update({'amount': Decimal(amount), 'user_id': user.id}) if bill['type'] == 'out': reply = f'支出:{amount}元,类别:{bill["category"]}' user.balance -= Decimal(amount) elif bill['type'] == 'in': reply = f'收入:{amount}元' + f'{bill["name"]}' if bill.get( 'name') else '' user.balance += Decimal(amount) db.session.add(Bill(**bill)) db.session.commit() Redis.delete(tg_user.username) update.message.reply_text(reply + f'\n当前余额:{str(user.balance)}元')
def create_new_bill(user_id, amount: str, category: str, type: str, name: str = None): with app.app_context(): user: User = User.query.filter_by(id=user_id).first() # new bill bill: Bill = Bill(user_id=user_id, type=type, amount=Decimal(amount), category=category, name=name) db.session.add(bill) # update user balance if type == 'out': reply = f'支出:{amount}元,类别:{category}' user.balance -= Decimal(amount) else: reply = f'收入:{amount}元' + f'{name}' if name else '' user.balance += Decimal(amount) db.session.commit() # send message callback_data = { 'msg_type': 'periodic', 'bill_id': bill.id, } inline_keyboard = InlineKeyboardMarkup([[InlineKeyboardButton('撤销', callback_data=json.dumps(callback_data))]]) bot.send_message(user.chat_id, f'{reply}\n当前余额:{str(user.balance)}元', reply_markup=inline_keyboard, disable_notification=True)
def userinfo(): user = current_user person_form = UpdatePersonForm() if request.method == "POST": if request.form.get('update'): original_ID = request.form.get('old_name') update_name = request.form.get('name') update_email = request.form.get('email') if original_ID != '': original_bill = Bill.query.filter_by(ID=original_ID).first() if update_name == original_bill.name and update_email == original_bill.email: flash('Get same bill information, please modify the bill information for update') else: original_bill.name = update_name original_bill.email = update_email db.session.commit() flash('Update bill information successfully') else: new_biller = Bill(name=update_name, email=update_email, user_id=current_user.ID) db.session.add(new_biller) db.session.commit() flash('New biller information added') return redirect(url_for('user.userinfo')) elif request.form.get('delete'): original_ID = request.form.get('old_name') if original_ID != '': original_bill = Bill.query.filter_by(ID=original_ID).first() if original_bill: db.session.delete(original_bill) db.session.commit() flash('Bill information removed') else: flash('No biller information found, please check the biller information is entered correctly.') else: flash('No biller information found, please check the biller information is entered correctly.') return redirect(url_for('user.userinfo')) if person_form.validate_on_submit(): if not person_form.validate_username(person_form.username) and user.name != person_form.username.data: flash('Username has been registered, please choose another name.') return redirect(url_for('user.userinfo')) flag = False if person_form.username.data and user.name != person_form.username.data: user.name = person_form.username.data flag = True if person_form.email.data and user.email != person_form.email.data: user.email = person_form.email.data flag = True if person_form.password.data and not user.check_password(person_form.password.data): user.set_password(person_form.password.data) flag = True if person_form.homeaddress.data and user.address != person_form.homeaddress.data: user.address = person_form.homeaddress.data flag = True if person_form.contactnumber.data and user.contact != person_form.contactnumber.data: user.contact = person_form.contactnumber.data flag = True if person_form.extrainfo.data and user.extra_info != person_form.extrainfo.data: user.extra_info = person_form.extrainfo.data flag = True db.session.commit() if flag: flash("Information updated successfully!") return redirect(url_for('user.userinfo')) current_biller = Bill.query.filter_by(user_id=current_user.ID).all() return render_template('userinfo.html', user=user, person_form=person_form, current_biller=current_biller)
def fully_populate_bill(cls, jsondata, xmldata, bill_num, bill_type): # idempotent function, will not corrupt if called even if bill is fully populated if jsondata["short_title"] is None: if jsondata["popular_title"] is None: title = jsondata["official_title"] else: title = jsondata["popular_title"] else: title = jsondata["short_title"] title = title if len(title) <= 256 else title[:256] cong = jsondata["congress"] num = jsondata["number"] active = jsondata["history"]["active"] sig = jsondata["history"]["awaiting_signature"] enact = jsondata["history"]["enacted"] veto = jsondata["history"]["vetoed"] try: comm = jsondata["committees"][0]["committee"] except IndexError: comm = None intro_date = jsondata["introduced_at"] intro_date = datetime.strptime(intro_date, "%Y-%m-%d").date() bills = Bill.query.filter((Bill.bill_type == bill_type) & (Bill.bill_num == num) & (Bill.congress == cong)).all() if bills: # if the bill has been instantiated, # check if bill has been fully populated bill = bills[0] populated = bool(bill.title) if not populated: # if not populated, instantiate key identifying info (title, origin date) bill.congress = cong bill.title = title bill.introduced_date = intro_date # overwrite with most recent status info bill.active = active bill.awaiting_sig = sig bill.enacted = enact bill.vetoed = veto bill.committee = comm else: # if bill has NOT been instantiated, # create instantiation and add to db populated = False bill = Bill( title=title, congress=cong, bill_type=bill_type, bill_num=num, introduced_date=intro_date, committee=comm, active=active, awaiting_sig=sig, enacted=enact, vetoed=veto, ) db.session.add(bill) # delete old statuses bill.statuses = [] # clears all actions attached to this bill statuses = BillStatus.query.filter(BillStatus.bill_id == bill.id).all() for bs in statuses: db.session.delete(bs) # bill statuses and actions actions = jsondata["actions"] for act in actions: stat = BillStatus() d = act["acted_at"][:10] d = datetime.strptime(d, "%Y-%m-%d").date() text = act["text"] text = text if len(text) < 128 else text[:128] act_type = act["type"] stat.date = d stat.text = text stat.action_type = act_type bill.statuses.append(stat) if not populated: # set and link legislative subjects subjects = jsondata["subjects"] for subj in subjects: subj_q = LegislativeSubjects.query.filter( func.lower(LegislativeSubjects.subject) == subj.lower()) loaded_subjects = subj_q.all() if loaded_subjects: for sub in loaded_subjects: bill.leg_subjects.append(sub) else: new_sub = LegislativeSubjects() new_sub.subject = subj bill.leg_subjects.append(new_sub) # sponsors spon = xmldata[0].findall("sponsors") spon = spon[0] bio_id = spon[0].find("bioguideId").text lname = spon[0].find("lastName").text fname = spon[0].find("firstName").text state = spon[0].find("state").text party = spon[0].find("party").text if bill_type < 5: # Bill originated in the House of Representatives # Search for reps using bioguide_id rep_q = Representative.query.filter( Representative.bioguide_id == bio_id) else: # Bill originated in the Senate # Search for reps using state + party lastname rep_q = (Representative.query.filter( Representative.state == state).filter( Representative.party == party).filter( func.lower(Representative.lname) == lname.lower())) reps = rep_q.all() if reps: # representative exists in the database # add them as a sponsor to this bill. rep = reps[0] else: rep = Representative() rep.bioguide_id = bio_id rep.fname = fname.title() rep.lname = lname.title() mname = spon[0].find("middleName").text if mname is not None: rep.mname = mname.title() rep.state = state rep.party = party rep.active = True bill.sponsor = rep # end of not-populated clause # cosponsors bill.cosponsors = [] # clears all actions attached to this bill cospon = xmldata[0].findall("cosponsors") cospon = cospon[0] for c in cospon: bio_id = c.find("bioguideId").text lname = c.find("lastName").text fname = c.find("firstName").text state = c.find("state").text party = c.find("party").text if bill_type < 5: # Bill originated in the House of Representatives # Search for reps using bioguide_id rep_q = Representative.query.filter( Representative.bioguide_id == bio_id) else: # Bill originated in the Senate # Search for reps using state + party lastname rep_q = Representative.query.filter( (Representative.state == state) & (Representative.party == party) & (func.lower(Representative.lname) == lname.lower())) reps = rep_q.all() if reps: # representative exists in the database # add them as a cosponsor to this bill. rep = reps[0] else: rep = Representative() rep.bioguide_id = bio_id rep.fname = fname.title() rep.lname = lname.title() mname = c.find("middleName").text if mname is not None: rep.mname = mname.title() rep.state = state rep.party = party rep.active = True bill.cosponsors.append(rep) # end of cosponsor iteration db.session.commit()
def read_voting_data(session, state_abbr, datasets): bills_created = 0 votes_created = 0 for xlsx_path in datasets: df = pd.read_excel(xlsx_path, sheet_name=None) bills_sheet = df["Votes"] bills = {} for _, row in bills_sheet.iterrows(): bill_id = row[VK.BILL] bill_no = row[VK.BILL_NO] bill_title = row[VK.BILL_TITLE] bill_pro_env = VotingAction.fuzzy_cast(row[VK.BILL_PRO_ENV]) bill_details = row[VK.BILL_DETAILS] bill_outcome = row.get(VK.BILL_OUTCOME, None) b = Bill(state=state_abbr, pro_environment_decision=bill_pro_env, title=bill_title, code=bill_no, description=bill_details, outcome=bill_outcome) bills[bill_id] = b # For use in this function only session.add(b) # Save to db bills_created += 1 print("Voting records created: %d Bill records created: %d" % ( votes_created, bills_created), end="\r") session.commit() for sheet_name, district_type in VOTING_CHAMBERS: sheet_content = df[sheet_name] for _, row in sheet_content.iterrows(): state = row[VK.STATE] year = int(row[VK.YEAR]) district_number = int(row[VK.DISTRICT]) legislator_name = row[VK.LEGISLATOR_NAME] party = safe_cast(Party, row[VK.PARTY]) year_score = safe_cast(float, row[VK.YEAR_SCORE % year]) lifetime_score = safe_cast(float, row.get(VK.LIFETIME_SCORE)) district_shortcode = District.to_shortcode(state_abbr, district_type, district_number) for key in row.keys(): if key and re.match(VK.BILL_ID, str(key)): # This column is a vote raw_classification = row[key] try: c = VotingClassification(raw_classification) except ValueError: # print("Invalid vote classification: '%s'%s" % ( # raw_classification, ' ' * 20)) c = VotingClassification.UNKNOWN v = Vote(district_shortcode=district_shortcode, legislator_name=legislator_name, classification=c, party=party, year=year, year_score=year_score, lifetime_score=lifetime_score, bill_id=bills[key].id) votes_created += 1 session.add(v) print("Voting records created: %d Bill records created: %d" % ( votes_created, bills_created), end="\r") session.commit() print()
def load_votes_into_mysql(cls): """Read all json data saved, and push it into mysql db""" for dir_name in os.listdir(VOTES_PATH): with open(os.path.join(VOTES_PATH, dir_name, JSON_FILE), "r") as f: data = json.load(f) c = data["chamber"] n = data["number"] cong = data["congress"] d = data["date"] d = d[:19] # strip off the timezone offset dt = datetime.strptime(d, "%Y-%m-%dT%H:%M:%S").date() y = dt.year entries = Vote.query.filter( (Vote.vote_num == n) & (Vote.chamber == c) & (Vote.year == y) & (Vote.congress == cong) ).all() if entries: # If vote already exists in the database, skip adding it continue q = data["question"] r = data["result"] req = data["requires"] t = data["type"] try: nays = data["votes"]["Nay"] except KeyError: try: nays = data["votes"]["No"] except KeyError: nays = [] try: yeas = data["votes"]["Yea"] except KeyError: try: yeas = data["votes"]["Aye"] except KeyError: yeas = [] try: abstains = data["votes"]["Not Voting"] except KeyError: abstains = [] num_nays = len(nays) num_yeas = len(yeas) num_abstains = len(abstains) v = Vote( chamber=c, year=y, congress=cong, vote_num=n, date=dt, vote_result=r if len(r) <= 64 else r[:64], num_yeas=num_yeas, num_nays=num_nays, num_abstains=num_abstains, required=req, vote_type=t if len(t) <= 32 else t[:32], question=q if len(q) <= 512 else q[:512], ) for rep_data in yeas: # iterate over yea representatives. # link the appropriate rep with this yea vote. # create the rep if bioguide not in the database if c == "h": rep_q = Representative.query.filter( Representative.bioguide_id == rep_data["id"] ) else: try: rep_q = Representative.query.filter( Representative.lis_id == rep_data["id"] ) except TypeError: print("{}{}".format(c, n)) print(rep_data) continue reps = rep_q.all() if reps: # the rep exists in the database # link that rep with this yea vote r = reps[0] else: # the rep doesn't exist # create the rep and then link if c == "h": r = Representative(bioguide_id=rep_data["id"]) else: r = Representative(lis_id=rep_data["id"]) r.fname = rep_data["first_name"].title() r.lname = rep_data["last_name"].title() r.state = rep_data["state"] r.party = rep_data["party"] r.active = True r.chamber = c v.yea_voters.append(r) for rep_data in nays: # iterate over nay representatives. # link the appropriate rep with this nay vote. # create the rep if bioguide not in the database if c == "h": rep_q = Representative.query.filter( Representative.bioguide_id == rep_data["id"] ) else: rep_q = Representative.query.filter( Representative.lis_id == rep_data["id"] ) reps = rep_q.all() if reps: # the rep exists in the database # link that rep with this yea vote r = reps[0] else: # the rep doesn't exist # create the rep and then link if c == "h": r = Representative(bioguide_id=rep_data["id"]) else: r = Representative(lis_id=rep_data["id"]) r.fname = rep_data["first_name"].title() r.lname = rep_data["last_name"].title() r.state = rep_data["state"] r.party = rep_data["party"] r.active = True r.chamber = c v.nay_voters.append(r) for rep_data in abstains: # iterate over not voting representatives. # link the appropriate rep with this not vote. # create the rep if bioguide not in the database if c == "h": rep_q = Representative.query.filter( Representative.bioguide_id == rep_data["id"] ) else: rep_q = Representative.query.filter( Representative.lis_id == rep_data["id"] ) reps = rep_q.all() if reps: # the rep exists in the database # link that rep with this yea vote r = reps[0] else: # the rep doesn't exist # create the rep and then link if c == "h": r = Representative(bioguide_id=rep_data["id"]) else: r = Representative(lis_id=rep_data["id"]) r.fname = rep_data["first_name"].title() r.lname = rep_data["last_name"].title() r.state = rep_data["state"] r.party = rep_data["party"] r.active = True r.chamber = c v.not_voters.append(r) try: bill = data["bill"] bills = Bill.query.filter( (Bill.bill_type == getattr(BillType, bill["type"].upper())) & (Bill.bill_num == bill["number"]) & (Bill.congress == bill["congress"]) ).all() if len(bills) == 1: # if bill being voted on exists in the database (TYPE, NUM, CONGRESS), # then link the bill to this vote v.bill = bills[0] elif not bills: # if there is no matching bill in database (TYPE, NUM, CONGRESS), # then create the bill, and link to this vote ad_hoc_bill = Bill( congress=bill["congress"], bill_type=getattr(BillType, bill["type"].upper()), bill_num=bill["number"], ) v.bill = ad_hoc_bill except KeyError: # The vote is not related to any bill pass db.session.add(v) db.session.commit()