def new(request): a = AddressBook(first_name=request.POST['first_name'], last_name=request.POST['last_name'], phone=request.POST['phone'], address=request.POST['address'], city=request.POST['city'], state=request.POST['state'], country=request.POST['country'], zipcode=request.POST['zipcode'], email=request.POST['email']) a.save() return HttpResponseRedirect(request.META.get('HTTP_REFERER'))
def get(self): id_edit = self.request.get("id_edit") if id_edit: temp = {} addressbook = AddressBook.get_by_id(int(id_edit)) if addressbook: temp["id"] = addressbook.key.id() temp["fullname"] = addressbook.fullname temp["email"] = addressbook.email temp["phone"] = addressbook.phone temp["address"] = addressbook.address self.response.out.write(simplejson.dumps(temp)) return id_delete = self.request.get("id_delete") if id_delete: temp = {} addressbook = AddressBook.get_by_id(int(id_delete)) if addressbook: addressbook.key.delete() temp["message"] = "Success" self.response.out.write(simplejson.dumps(temp)) return addressbooks = AddressBook.query().order(-AddressBook.created).fetch(100) if addressbooks: datas = [] for ab in addressbooks: temp = {} temp["id"] = ab.key.id() temp["fullname"] = ab.fullname temp["email"] = ab.email temp["phone"] = ab.phone temp["address"] = ab.address datas.append(temp) self.response.out.write(simplejson.dumps(datas))
def address_book(item_type): """Add a person or group to the address book.""" data = json.loads(request.data) address_book = AddressBook.query.first() if not address_book: address_book = AddressBook() address_book.save() if item_type == "person": person_obj = Person(**data) try: person_obj.save() address_book.person_list.append(person_obj) except MissingValueException as e: return jsonify({ "saved": False, "type": "person", "data": data, "message": "Missing {}".format(e) }) except Exception as e: raise e elif item_type == "group": data['persons'] = [Person.query.get(x) for x in data['persons']] try: group_obj = Group(**data) group_obj.save() address_book.group_list.append(group_obj) except MissingValueException as e: return jsonify({ "saved": False, "type": "person", "message": "Missing {}".format(e) }) except BadValueException as e: return jsonify({ "saved": False, "type": "person", "message": "One of the Ids provided is not in Database" }) except Exception as e: raise e else: return jsonify( {"message": "The url has to be address_book/[person|group]"}), 404 address_book.save() return jsonify({ "message": "saved {} to Address Book".format(item_type), "data": json.loads(dumps(address_book.wrap())) })
def get(self, *args, **kwargs): temp = {} search = kwargs["value"] if search: addressbooks = AddressBook.query(AddressBook.fullname == search.title()).fetch(100) if addressbooks: datas = [] for ab in addressbooks: temp["id"] = ab.key.id() temp["fullname"] = ab.fullname temp["email"] = ab.email temp["phone"] = ab.phone temp["address"] = ab.address datas.append(temp) self.response.out.write(simplejson.dumps(datas))
def crud(): if request.method == 'POST': if request.is_json: req = request.get_json() data = AddressBook(**req).save() return jsonify(data), 200 else: return "Request was not JSON", 400 if request.method == 'DELETE': if request.is_json: req = request.get_json() if 'id' in req: data = AddressBook.objects(id=req['id']).delete() return '', 200 else: return 'Not Found', 404 else: return "Request was not JSON", 400 if request.method == 'GET': args = request.args if 'q' in args: q = args['q'] return jsonify( AddressBook.objects( Q(name__icontains=q) | Q(address__icontains=q) | Q(city__icontains=q) | Q(state__icontains=q) | Q(country__icontains=q))) else: return jsonify(AddressBook.objects(**args)) if request.method == 'PATCH': if request.is_json: req = request.get_json() if 'id' in req: AddressBook.objects(id=req['id']).update_one(**req) data = AddressBook.objects(id=req['id']) return jsonify(data), 200 else: return 'Not Found', 404 else: return "Request was not JSON", 400 return '', 400
def put(self, *args, **kwargs): temp = {} id = kwargs["id"] details = self.request.body if id and details: newmessage = simplejson.loads(details) addressbook = AddressBook.get_by_id(int(id)) addressbook.fullname = newmessage["fullname"] addressbook.email = newmessage["email"] addressbook.phone = newmessage["phone"] addressbook.address = newmessage["address"] addressbook.put() temp["id"] = addressbook.key.id() temp["fullname"] = newmessage["fullname"] temp["email"] = newmessage["email"] temp["phone"] = newmessage["phone"] temp["address"] = newmessage["address"] self.response.out.write(simplejson.dumps(temp))
def post(self): details = self.request.body temp = {} if details: newmessage = simplejson.loads(details) addressbook = AddressBook() addressbook.fullname = newmessage["fullname"] addressbook.email = newmessage["email"] addressbook.phone = newmessage["phone"] addressbook.address = newmessage["address"] addressbook.put() temp = {} temp["id"] = addressbook.key.id() temp["fullname"] = newmessage["fullname"] temp["email"] = newmessage["email"] temp["phone"] = newmessage["phone"] temp["address"] = newmessage["address"] self.response.out.write(simplejson.dumps(temp))
def __init__(self): super().__init__() self.addressbook = AddressBook() self.addressbook.load(self.config)
class AddressBookApp(Application): def __init__(self): super().__init__() self.addressbook = AddressBook() self.addressbook.load(self.config) def create_menu(self, menu): # 메뉴를 구성해야합니다. # super().create_menu(menu) menu.add('목록', self.print_book) menu.add('상세보기', self.print_detail) menu.add('검색', self.search) menu.add('추가', self.add) menu.add('수정', self.update) menu.add('삭제', self.delete) menu.add('종료', self.exit) # 검색방법: 키워드 검색... '길동' --> [홍길동, 고길동] def search(self): keyword = input('검색어: ') result = self.addressbook.search(keyword) print('=' * 50) print(f'검색 ({len(result)}건)') print('=' * 50) for index, entry in enumerate(result, 1): print( f'{index:02d}] {entry.name}: {entry.phone}, {entry.email}, {entry.addr}' ) print('-' * 50) def print_book(self): print('=' * 50) print('주소록') print('=' * 50) for index, entry in enumerate(self.addressbook.book, 1): print( f'{index:02d}] {entry.name}: {entry.phone}, {entry.email}, {entry.addr}' ) print('-' * 50) def print_detail(self): index = int(input('대상 선택(번호): ')) # 검색 entry = self.addressbook.book[index - 1] # entry 포멧팅 해서 출력 print(f'이름: {entry.name}') print(f'전화번호: {entry.phone}') print(f'email: {entry.email}') print(f'주소: {entry.addr}') def add(self): print('새 주소록 항목 추가') name = input('이름:') phone = input('전화번호:') email = input('이메일:') addr = input('주소:') self.addressbook.add(name, phone, email, addr) def update(self): index = int(input('대상 선택(번호): ')) # 검색 entry = self.addressbook.book[index - 1] print('주소록 항목 수정') name = input(f'이름({entry.name}):') if name.strip() == '': name = entry.name phone = input(f'전화번호({entry.phone}):') if phone.strip() == '': phone = entry.phone email = input(f'이메일({entry.email}):') if email.strip() == '': email = entry.email addr = input(f'주소({entry.addr}):') if addr.strip() == '': addr = entry.addr self.addressbook.update(index - 1, name, phone, email, addr) def delete(self): index = int(input('대상 선택(번호):')) entry = self.addressbook.book[index - 1] ans = input(f'{entry.name}을 삭제할까요?(Y/N)') if ans == 'Y': self.addressbook.delete(index - 1) def destroyed(self): self.addressbook.save(self.config)
from models import Contact, AddressBook ab = AddressBook() class BaseView: def __init__(self): self.prefix = '\n\t=== > ' self.value_length = 1 def _input_data(self, value_name, value_length): """ Control for input data length """ while True: print(self.prefix, value_name, ' (min length - {})'.format(value_length)) value = input(' ?') if len(value) >= value_length: return value class ContactView(BaseView): def add_contact(self): first_name = self._input_data('Enter First Name', 3) last_name = self._input_data('Enter Last Name', 3) phone = self._input_data('Enter Phone ', 3) contact = Contact(first_name, last_name, phone) return contact class AddressBookView(BaseView):
class AddressBookApp(Application): def __init__(self): super().__init__() self.addressbook = AddressBook() self.addressbook.load(self.config) def create_menu(self, menu): self.menu.add('목록', self.print_book) # print_book() 이라고 쓰면 이 메서드의 리턴값을 넘겨주기 때문에 괄호를 쓰면 안됨 self.menu.add('상세보기', self.print_detail) self.menu.add('검색', self.search) self.menu.add('추가', self.add) self.menu.add('수정', self.update) self.menu.add('삭제', self.delete) self.menu.add('종료', self.exit) def print_book(self): print('='*50) print('주소록') print('='*50) for ix, entry in enumerate(self.addressbook.book): print(f'{ix+1:02d}. {entry.name} : {entry.phone}, {entry.email}, {entry.addr}') def print_detail(self): index = int(input('대상 선택 (번호): ')) entry = self.addressbook.book[index-1] print() print(f'이름 : {entry.name}') print(f'전화번호 : {entry.phone}') print(f'이메일 : {entry.email}') print(f'주소 : {entry.addr}') def search(self): # 부분 일치 검색 (키워드 검색) keyword = input('검색어 : ') result = self.addressbook.search(keyword) print('='*50) print(f'검색 결과 ({len(result)}건)') print('='*50) for index, entry in enumerate(result): print(f'{index+1:02d}) {entry.name} : {entry.phone}, {entry.email}, {entry.addr}') def add(self): print('\n<새 주소록 항목 추가>\n') name = input('이름 : ') phone = input('전화번호 : ') email = input('이메일 : ') addr = input('주소 : ') self.addressbook.add(name, phone, email, addr) print('\n등록이 완료되었습니다.') def update(self): index = int(input('대상 선택 (번호): ')) entry = self.addressbook.book[index-1] print('주소록 항목 수정') name = input(f'이름({entry.name}) -> ') if name.strip() == '': name = entry.name phone = input(f'전화번호({entry.phone}) -> ') if phone.strip() == '': phone = entry.phone email = input(f'이메일({entry.email}) -> ') if email.strip() == '': email = entry.email addr = input(f'주소({entry.addr}) -> ') if addr.strip() == '': addr = entry.addr self.addressbook.update(index-1, name, phone, email, addr) def delete(self): index = int(input('대상 선택 (번호): ')) entry = self.addressbook.book[index-1] if input(f'{entry.name}님을 정말로 삭제할까요? (y/n) ') == 'y': self.addressbook.delete(index-1) def destroyed(self): self.addressbook.save(self.config)
from models import AddressBook from dao import AddressBookDAO dao = AddressBookDAO() new = AddressBook('KCTZ Style', 'Korea', '010-1111-2222', '*****@*****.**') dao.add(new)