def add_email(username="",value=""): current_contact = session.query(Contact).filter_by(username=f'{username}').first() if current_contact: current_contact.emails.append(ContactEmail(value=value)) session.commit() return jsonify(session.query(Contact).filter_by(id=current_contact.id).first().to_json()) else: return jsonify(dict(message="Record not found!"))
def __init__(self): super().__init__() self.setWindowTitle('detection_of_site_changes_Unistream') self.revision_list_widget = QListWidget() self.revision_list_widget.itemDoubleClicked.connect( self._show_last_diff) # Словарь в ключе содержит хеш ревизии, а в значении -- список элементов ревизий text_hash_by_group_revisions_dict = defaultdict(list) text_revisions = session.query(TextRevision).all() for rev in text_revisions: item = QListWidgetItem() item.setText(str(rev)) item.setData(Qt.UserRole, rev) text_hash_by_group_revisions_dict[rev.text_hash].append(item) self.revision_list_widget.addItem(item) # TODO: возможны коллизии по первым 6-символам # TODO: учитывать, что может получиться слишком светлый или темный фон for text_hash, items in text_hash_by_group_revisions_dict.items(): if len(items) > 1: for item in items: # Придаем элементу ревизии цвет, зависящий от первых 6-ти символов его хеша color = QColor('#' + text_hash[:6]) item.setBackground(color) self.setCentralWidget(self.revision_list_widget)
def post(self): data = request.json try: user = Users(data["login"], data["password"], data["name"], data["passport"], data["address"], data["email"], data["phone_number"], data["status"]) user.password = generate_password_hash(data['password']) checkuser = session.query(Users).filter( Users.login == user.login).all() if checkuser: return Response(response=json.dumps( {"message": "user with such login already exist"}), status=409, mimetype="application/json") session.add(user) session.flush() session.commit() token = user.get_token() return Response(response=json.dumps({"message": "Success"}), status=200, mimetype="application/json") except: return Response(response=json.dumps({"message": "Invalid input"}), status=405, mimetype="application/json")
def post(self): data = request.json user_id = get_jwt_identity() checkuser = session.query(Users).filter(Users.id == user_id).one() if checkuser.status == "admin": return Response(response=json.dumps( {"message": "Not allowed for admins"}), status=400, mimetype="application/json") try: credit = Credits(data["start_date"], data["end_date"], data["start_sum"], data["current_sum"], data["bank_id"], user_id) session.add(credit) session.commit() usercredit = UserCredit(credit.user_id, credit.id) session.add(usercredit) session.commit() return Response(response=json.dumps({"message": "Success"}), status=200, mimetype="application/json") except: return Response(response=json.dumps({"message": "Invalid input"}), status=405, mimetype="application/json")
def put(self): data = request.json user_id = get_jwt_identity() try: user = session.query(Users).get(user_id) if not user: return Response(response=json.dumps({"message": "invalid id"}), status=400, mimetype="application/json") if "login" in data: user.login = data["login"] if "password" in data: user.password = generate_password_hash(data['password']) if "name" in data: user.name = data["name"] if "passport" in data: user.passport = data["passport"] if "address" in data: user.address = data["address"] if "email" in data: user.email = data["email"] if "phone_number" in data: user.phone_number = data["phone_number"] session.commit() return Response(response=json.dumps({"message": "Success"}), status=200, mimetype="application/json") except Exception as e: return Response(response=json.dumps({"message": "Invalid input"}), status=405, mimetype="application/json")
def get(self, id): user_id = get_jwt_identity() checkuser = session.query(Users).filter(Users.id == user_id).one() if checkuser.status != "admin": return Response(response=json.dumps( {"message": "Not allowed for users"}), status=400, mimetype="application/json") user = session.query(Users).get(id) if user: return Response(response=json.dumps(user, cls=AlchemyEncoder), status=201, mimetype="application/json") return Response(response=json.dumps({"message": "Not found"}), status=400, mimetype="application/json")
def delete_contact(username=""): current_contact = session.query(Contact).filter_by(username=f'{username}', valid_till_date = None).first() if current_contact: current_contact.valid_till_date = func.now() session.commit() return jsonify(dict(message="Record deleted!")) else: return jsonify(dict(message="No record found!"))
def get(self, credit_id): credit = session.query(Credits).get(credit_id) if credit: return Response(response=json.dumps(credit, cls=AlchemyEncoder), status=201, mimetype="application/json") return Response(response=json.dumps({"message": "Not found"}), status=400, mimetype="application/json")
def get(self, id): bank = session.query(Banks).get(id) if bank: return Response(response=json.dumps(bank, cls=AlchemyEncoder), status=201, mimetype="application/json") return Response(response=json.dumps({"message": "Not found"}), status=400, mimetype="application/json")
def get(self, credit_id, transaction_id): transaction = session.query(Transactions).get(transaction_id) if transaction: return Response(response=json.dumps(transaction, cls=AlchemyEncoder), status=201, mimetype="application/json") return Response(response=json.dumps({"message": "Not found"}), status=400, mimetype="application/json")
def get(self): user_id = get_jwt_identity() user = session.query(Users).get(user_id) if user: return Response(response=json.dumps(user, cls=AlchemyEncoder), status=201, mimetype="application/json") return Response(response=json.dumps({"message": "Not found"}), status=400, mimetype="application/json")
def create_contact(username="",first_name="",last_name="",email=""): new_contact = Contact( username=username, first_name=ContactFirstName(value=first_name), last_name=ContactLastName(value=last_name), emails=[ContactEmail(value=email)] ) session.add(new_contact) session.commit() return jsonify([x.to_json() for x in session.query(Contact).filter_by(username=f'{username}')])
def put(self, credit_id): data = request.json user_id = get_jwt_identity() checkuser = session.query(Users).filter(Users.id == user_id).one() if checkuser.status == "admin": return Response(response=json.dumps( {"message": "Not allowed for admins"}), status=400, mimetype="application/json") try: credit = session.query(Credits).get(credit_id) if "current_sum" in data: credit.current_sum = data["current_sum"] session.commit() return Response(response=json.dumps({"message": "Success"}), status=200, mimetype="application/json") except Exception as e: return Response(response=json.dumps({"message": "Invalid input"}), status=405, mimetype="application/json")
def test_success_signup(self): response = self.test_app.post("/signup", json={ "username": "******", "password": "******", "name": "name2", "email": "*****@*****.**" }) self.assertEqual(201, response.status_code) user = session.query(UserModel).filter( UserModel.username == "user4", UserModel.password == "pw2", UserModel.name == "name2", UserModel.email == "*****@*****.**").one_or_none() self.assertIsNotNone(user)
def update_contact(username="", column="",value=""): current_contact = session.query(Contact).filter_by(username=f'{username}').first() if current_contact: if column == "first_name": session.query(ContactFirstName).filter_by(contact_id=current_contact.id, valid_till_date = None).first().valid_till_date = func.now() session.query(Contact).filter_by(id=current_contact.id).first().first_name = ContactFirstName(value=value) elif column == "last_name": session.query(ContactLastName).filter_by(contact_id=current_contact.id, valid_till_date = None).first().valid_till_date = func.now() session.query(Contact).filter_by(id=current_contact.id).first().last_name = ContactLastName(value=value) elif column == "email": for e in session.query(ContactEmail).filter_by(contact_id=current_contact.id, valid_till_date = None).all(): e.valid_till_date = func.now() session.query(Contact).filter_by(id=current_contact.id).first().emails = [ContactEmail(value=value)] else: return jsonify(dict(message="No record found!")) session.commit() return jsonify(session.query(Contact).filter_by(username=f'{username}').first().to_json())
def post(self): data = request.json user_id = get_jwt_identity() checkuser = session.query(Users).filter(Users.id == user_id).one() if checkuser.status != "admin": return Response(response=json.dumps( {"message": "Not allowed for users"}), status=400, mimetype="application/json") try: bank = Banks(data["all_money"], data["per_cent"]) session.add(bank) session.commit() return Response(response=json.dumps({"message": "Success"}), status=200, mimetype="application/json") except: return Response(response=json.dumps({"message": "Invalid input"}), status=405, mimetype="application/json")
def post(self, credit_id): data = request.json user_id = get_jwt_identity() checkuser = session.query(Users).filter(Users.id == user_id).one() if checkuser.status == "admin": return Response(response=json.dumps( {"message": "Not allowed for admins"}), status=400, mimetype="application/json") try: transaction = Transactions(data["date"], data["summ"], credit_id) session.add(transaction) session.commit() return Response(response=json.dumps({"message": "Success"}), status=200, mimetype="application/json") except: return Response(response=json.dumps({"message": "Invalid input"}), status=405, mimetype="application/json")
#!/usr/bin/env python3 # -*- coding: utf-8 -*- __author__ = 'ipetrash' """Скрипт для тренировки написания запросов.""" from main import session, Gist # # Получить все # for gist in session.query(Gist).all(): # print(gist) print(len(session.query(Gist).all())) # Поиск гистов у которых в заголовке есть строка "go" for gist in session.query(Gist).filter(Gist.description.like("%go%")).all(): print(gist)
#!/usr/bin/env python3 # -*- coding: utf-8 -*- __author__ = 'ipetrash' """Скрипт находит последние две ревизии, сохраняет их текст в файлы и сравнивает с помощью kdiff3.""" if __name__ == '__main__': from main import session, TextRevision # TODO: нет смысла запрашивать все, если нужны только 2 последнии text_revisions = session.query(TextRevision).all() if len(text_revisions) >= 2: file_a, file_b = text_revisions[-2:] file_name_a = 'file_a' file_name_b = 'file_b' with open(file_name_a, mode='w', encoding='utf-8') as f: f.write(file_a.text) with open(file_name_b, mode='w', encoding='utf-8') as f: f.write(file_b.text) import os os.system('kdiff3 {} {}'.format(file_name_a, file_name_b)) if os.path.exists(file_name_a): os.remove(file_name_a) if os.path.exists(file_name_b): os.remove(file_name_b)
def authenticate(cls, login, password): from main import session user = session.query(cls).filter(cls.login == login).one() if not check_password_hash(user.password, password): raise Exception('No user with this password') return user
#!/usr/bin/env python3 # -*- coding: utf-8 -*- __author__ = 'ipetrash' """Скрипт удаляет последнюю ревизию.""" if __name__ == '__main__': from main import session, TextRevision text_revision = session.query(TextRevision).order_by( TextRevision.id.desc()).first() print(text_revision) session.delete(text_revision) session.commit()
def search_contact(username=""): current_contact = session.query(Contact).filter_by(username=f'{username}', valid_till_date = None).first() if current_contact: return jsonify(current_contact.to_json()) else: return jsonify(dict(message="No record found!"))
def index(): return jsonify([x.to_json() for x in session.query(Contact).filter_by(valid_till_date = None).all()])