def add_book(): # 添加书籍 book1 = Book() book1.title = '深入理解计算机系统' book1.author = 'Randal E.Bryant' book1.summary = ''' 从程序员的视角,看计算机系统!\n 本书适用于那些想要写出更快、更可靠程序的程序员。 通过掌握程序是如何映射到系统上,以及程序是如何执行的,读者能够更好的理解程序的行为为什么是这样的,以及效率低下是如何造成的。 粗略来看,计算机系统包括处理器和存储器硬件、编译器、操作系统和网络互连环境。 而通过程序员的视角,读者可以清晰地明白学习计算机系统的内部工作原理会对他们今后作为计算机科学研究者和工程师的工作有进一步的帮助。 它还有助于为进一步学习计算机体系结构、操作系统、编译器和网络互连做好准备。\n 本书的主要论题包括:数据表示、C程序的机器级表示、处理器结构,程序优化、存储器层次结构、链接、异常控制流、虚拟存储器和存储器管理、系统级I/O、网络编程和并发编程。书中所覆盖的内容主要是这些方面是如何影响应用和系统程序员的。 ''' book1.image = 'https://img3.doubanio.com/lpic/s1470003.jpg' db.session.add(book1) book2 = Book() book2.title = 'C程序设计语言' book2.author = '(美)Brian W. Kernighan' book2.summary = ''' 在计算机发展的历史上,没有哪一种程序设计语言像C语言这样应用广泛。 本书原著即为C语言的设计者之一Dennis M.Ritchie和著名计算机科学家Brian W.Kernighan合著的一本介绍C语言的权威经典著作。 我们现在见到的大量论述C语言程序设计的教材和专著均以此书为蓝本。 原著第1版中介绍的C语言成为后来广泛使用的C语言版本——标准C的基础。 人们熟知的“hello,World"程序就是由本书首次引入的,现在,这一程序已经成为众多程序设计语言入门的第一课。\n 原著第2版根据1987年制定的ANSIC标准做了适当的修订.引入了最新的语言形式,并增加了新的示例,通过简洁的描述、典型的示例,作者全面、系统、准确地讲述了C语言的各个特性以及程序设计的基本方法。 对于计算机从业人员来说,《C程序设计语言》是一本必读的程序设计语 言方面的参考书。 ''' book2.image = 'https://img3.doubanio.com/lpic/s1106934.jpg' db.session.add(book2)
def two_saved_books(app): ocean_book = Book(title="Ocean Book", description="watr 4evr") mountain_book = Book(title="Mountain Book", description="i luv 2 climb rocks") db.session.add_all([ocean_book, mountain_book]) db.session.commit()
def two_saved_books(app): # Arrange ocean_book = Book(title="Ocean Book", description="watr 4evr") mountain_book = Book(title="Mountain Book", description="i luv 2 climb rocks") db.session.add_all([ocean_book, mountain_book]) # Alternatively, we could do # db.session.add(ocean_book) # db.session.add(mountain_book) db.session.commit()
def two_saved_books(app): #Arrange ocean_book = Book(title="Ocean Book", description="water forever") mountain_book = Book(title="Mountain Book", description="I love to climb mountains") db.session.add_all([ocean_book, mountain_book]) #Alternatively, we could do #db.session.add(ocean_book) #db.session.add(mountain_book) db.session.commit()
def two_saved_books(app): # This fixture needs to request the use of the app fixture, defined previously, so we know the test database has been initialized. # Arrange ocean_book = Book(title="Ocean Book", description="watr 4evr") mountain_book = Book(title="Mountain Book", description="i luv 2 climb rocks") db.session.add_all([ocean_book, mountain_book]) # Alternatively, we could do # db.session.add(ocean_book) # db.session.add(mountain_book) db.session.commit()
def init_book(): books = [ Book(title='java', author='李刚', price=20, isbn='35986547845', summery='概况'), Book(title='python', author='join', price=20, isbn='35983547845', summery='概况'), ] with db.auto_commit(): db.session.add_all(books)
def create(self): self.book = Book(self.input('book')) if self.book.save(): self.redirect_to(action="index") else: self.subjects = Subject.find("all") self.render("new")
def __save(data): """ 保存到数据库 :param data: :return: """ if 'books' not in data.keys(): data['books'] = [data] if data['books']: for item in data['books']: # 已存在的不需要插入 count = Book.query.filter_by(isbn=item['isbn']).count() if count == 0: book = Book() book.title = item['title'] book.author = '、'.join(item['author']) book.binding = item['binding'] book.publisher = item['publisher'] book.price = item['price'] book.pages = item['pages'] book.pubdate = item['pubdate'] book.isbn = item['isbn'] book.summary = item['summary'] book.image = item['image'] db.session.add(book) db.session.commit()
def handle_books(): if request.method == "GET": #gets query param called title from the request, returns value of query param title_query = request.args.get("title") if title_query: books = Book.query.filter_by( title=title_query ) #if we get query param, will filter the results else: #if we didnt get a query param, get all the books books = Book.query.all() #tells Book to query for all books books_response = [] for book in books: #iterate over all books in books to collect their data and format it into a response books_response.append({ "id": book.id, "title": book.title, "description": book.description }) #creates a list of dictionaries return jsonify(books_response ) #jsonfy turns books response into a response object elif request.method == "POST": #request body holds the body contents of the HTTP request in json form request_body = request.get_json() #print(request_body) #create an instance of Book using the data from request_body new_book = Book(title=request_body["title"], description=request_body["description"]) db.session.add(new_book) db.session.commit() return make_response(f"Book {new_book.title} successfully created", 201)
def handle_books(): if request.method == "GET": if request.method == "GET": title_query = request.args.get("title") if title_query: books = Book.query.filter_by(title=title_query) else: books = Book.query.all() books_response = [] for book in books: books_response.append({ "id": book.id, "title": book.title, "description": book.description }) return jsonify(books_response) elif request.method == "POST": request_body = request.get_json() new_book = Book(title=request_body["title"], description=request_body["description"]) db.session.add(new_book) db.session.commit() return make_response(f"Book {new_book.title} successfully created", 201)
def add_new_book(): name = request.form.get('name') author_id = request.form.get('author_id') category_id = request.form.get('category_id') isbn = request.form.get('isbn') content = request.form.get('content') file = request.files['image_url'] if file and allowed_file(file.filename): file_name = rename_for_upload(file.filename) # 注意:没有的文件夹一定要先创建,不然会提示没有该路径(一定要相对路径) upload_path = os.path.join('static/uploads/', file_name) file.save(upload_path) book = Book() book.name = name book.author_id = author_id book.category_id = category_id book.isbn = isbn book.content = content book.image_url = upload_path try: book.save() return CreateSuccess() except: return ParameterError() else: return ParameterError()
async def read_books(q: str = "Hobbit", published_date: Optional[str] = None, sort_by_date: Optional[bool] = False, newest_first: Optional[bool] = False): url = GOOGLE_BOOKS + f"?q={q}&fields=items/volumeInfo" async with httpx.AsyncClient() as client: response = await client.get(url) response.raise_for_status() data = response.json() books_list = data.get("items", {}) books_list = [book.get("volumeInfo", {}) for book in books_list] parsed_books = list(map(get_book_fields, books_list)) if published_date: parsed_books = [ book for book in parsed_books if published_date in book["published_date"] ] if sort_by_date: parsed_books.sort(key=lambda b: books_sort(b["published_date"])) if newest_first: parsed_books = parsed_books[::-1] return [Book(**book) for book in parsed_books]
def add_new(): # 使用form重写添加书籍函数,使用form可以直接验证数据字段是否提交 form = BookAddForm(request.form).validate_for_api() name = form.name.data author_id = form.author_id.data category_id = form.category_id.data isbn = form.isbn.data content = form.content.data # image_url 字段通过request获取 file = request.files['image_url'] if file and allowed_file(file.filename): file_name = rename_for_upload(file.filename) upload_path = os.path.join('static/uploads/', file_name) file.save(upload_path) book = Book() book.name = name book.author_id = author_id book.category_id = category_id book.isbn = isbn book.content = content book.image_url = upload_path book.save() return CreateSuccess() else: return ParameterError()
async def read_books_by_author(author: List[str] = Query(...)): all_books = [] for name in author: url = GOOGLE_BOOKS author_string = name.split() if len(author_string) > 1: author_string = "+".join(author_string) author_string = f'"{author_string}"' else: author_string = author_string[0] url += f"?q=inauthor:{author_string}&fields=items/volumeInfo" async with httpx.AsyncClient() as client: response = await client.get(url) response.raise_for_status() data = response.json() books_list = data.get("items", {}) books_list = [book.get("volumeInfo", {}) for book in books_list] parsed_books = list(map(get_book_fields, books_list)) all_books.extend(parsed_books) return [Book(**book) for book in all_books]
def handle_books( ): # this function will execute whenever a request that matches the decaorator is received if request.method == "GET": # each Model class has a query attribute; the object returned by this attribute has the functions we will use to retrieve model data from the database books = Book.query.all( ) # tells Book to query for all() books. This method returns a list of instances of Book. books_response = [] for book in books: books_response.append({ "id": book.id, "title": book.title, "description": book.description }) return jsonify(books_response) elif request.method == "POST": request_body = request.get_json( ) # we use the request object to get information about the HTTP request; this method "Pythonifies" the JSON HTTP request body by convertign it to a Python dictionary #create new instance of Book model new_book = Book(title=request_body["title"], description=request_body["description"]) # adds new instance to the database (staging) db.session.add(new_book) # commits the changes, make it happen (action itself) db.session.commit() return make_response(f"Book {new_book.title} has been created", 201) # instantiates a Response object
def create_book_model(json): model = Book(title=json['title'], author=json['author'], isbn=json['isbn'], price=json['price'], publisher=json['publisher'], image=json['image']) return model
def add_book(): form = BookForm(request.form) if request.method == 'POST' and form.validate(): with db.auto_commit(throw=False): book = Book() book.set_attrs(form.data) db.session.add(book) return render_template('book/add_book.html', form=form)
def persistence_book(cls, book): book_model = Book() book_model.set_attr(book['data']) # book_model.isbn = get_isbn(book['data']) # book_model.image = book['images']['large'] db.session.add(book_model) db.session.commit() return book_model
def create_book(): request_body = request.get_json() new_book = Book(title=request_body["title"], description=request_body["description"]) db.session.add(new_book) db.session.commit() return make_response(f"Book {new_book.title} successfully created")
def handle_books(): request_body = request.get_json() new_book = Book(title=request_body['title'], description=request_body['description']) db.session.add(new_book) db.session.commit() return { "success": True, "message": f'Book {new_book.title} has been created!!' }, 201
def add_book(title, author, genre, read): book = Book( title=title, author=author, genre=genre, read=read ) db.session.add(book) db.session.commit() return book.to_dict()
def post(): data = request.form book = Book(name=data['name'], summary=data['summary']) db.session.add(book) db.session.commit() for authors in data['author']: if authors is not '': details = Book.query.order_by(Book.id.desc()).first() db.session.add( AuthorBook(author_id=authors, book_id=details.id)) db.session.commit()
def add_book(): request_body = request.get_json() new_book = Book(title = request_body["title"], description = request_body["description"]) db.session.add(new_book) db.session.commit() return { "success": True, "message": f"Book {new_book.title} has been created." }, 201
async def read_book(book_id: str): url = GOOGLE_BOOKS + f"/{book_id}?fields=volumeInfo" async with httpx.AsyncClient() as client: response = await client.get(url) response.raise_for_status() data = response.json() current_book = data.get("volumeInfo", {}) parsed_book = get_book_fields(current_book) return Book(**parsed_book)
def add_book(): resp = {'code': 200, 'msg': '', 'data': {}} args = json.loads(str(request.data, encoding='utf-8')) isbn = args.get('isbn') openid = args.get('openid') # isbn 和openID存在 if isbn and openid: # 判断isbn是否存在 book = Book.query.filter_by(isbn=isbn).first() if not book: # 书不存在 book_info = get_book_info(isbn) if book_info: # 获取图书的字段 rate = book_info['rating'].get('average') title, image, alt, publisher, summary, price = book_info[ 'title'], book_info['image'], book_info['alt'], book_info[ 'publisher'], book_info['summary'], book_info['price'] tags = ','.join([tag['title'] for tag in book_info['tags']]) author = ','.join(book_info['author']) book = Book(isbn=isbn, rate=rate, title=title, image=image, alt=alt, publisher=publisher, summary=summary, price=price, tags=tags, author=author, openid=openid) db.session.add(book) db.session.commit() book_obj = book.__dict__ book_obj.pop('_sa_instance_state') resp['msg'] = '图书添加成功' resp['data'] = book_obj return jsonify(resp) resp['code'] = -1 resp['msg'] = '图书不存在' return jsonify(resp) else: book_obj = book.__dict__ book_obj.pop('_sa_instance_state') resp['code'] = -1 resp['data'] = book_obj resp['msg'] = '图书已存在' return jsonify(resp) flash('openid 或者isbn不存在') resp['code'] = -1 resp['msg'] = 'openid 或者isbn不存在' return jsonify(resp)
def persistence_yushu(cls, book): book_model = Book() book_model.set_attrs(book) # book_model.isbn = book['isbn13'] or book['isbn10'] book_model.isbn = get_isbn(book) book_model.image = book['images']['large'] # book_model.origin_url = book['url'] # book_model.score = book['rating']['average'] # book_model.tags = book['tags'] db.session.add(book_model) db.session.commit() return book_model
def search_by_isbn(self, isbn): isbn_url = self.isbn_url.format(isbn) result = Http.get(isbn_url) # 从数据库查询是否有该书,如果没有,执行保存数据库,有的话跳过 book = Book() res = Book.query.filter_by(isbn=result['isbn']).first() if res is None: book.set_attrs(result) db.session.add(book) db.session.commit() self.__fill_single(result)
def handle_books(): if request.method == "GET": title_query = request.args.get("title") if title_query: books = Book.query.filter_by(title=title_query) else: books = Book.query.all() books_response = [] for book in books: books_response.append({ "id": book.id, "title": book.title, "description": book.description }) return jsonify(books_response) elif request.method == "POST": request_body = request.get_json() new_book = Book(title=request_body["title"], description=request_body["description"]) db.session.add(new_book) db.session.commit() return make_response(f"Book {new_book.title} successfully created") # hello_world_bp = Blueprint("hello_world", __name__) # @hello_world_bp.route("/hello-world", methods=["GET"]) # def say_hello_world(): # my_beautiful_response_body = "Hello, World!" # return my_beautiful_response_body # @hello_world_bp.route("/hello/JSON", methods=["GET"]) # def say_hello_json(): # return { # "name": "Ada Lovelace", # "message": "Hello!", # "hobbies": ["Fishing", "Swimming", "Watching Reality Shows"] # } # @hello_world_bp.route("/broken-endpoint-with-broken-server-code") # def broken_endpoint(): # response_body = { # "name": "Ada Lovelace", # "message": "Hello!", # "hobbies": ["Fishing", "Swimming", "Watching Reality Shows"] # } # new_hobby = "Surfing" # response_body["hobbies"].append(new_hobby) # return response_body
def handle_books(): # # One way we can break this route is to return a response with a status # # code 418 before doing anything else in the function. # return Response("I'm a teapot!", status=418) if request.method == "GET": # Finding Books by Title title_query = request.args.get("title") if title_query: books = Book.query.filter_by(title=title_query) else: # This SQLAlchemy syntax tells Book to query for all() books. This # method returns a list of instances of Book. books = Book.query.all() books_response = [] for book in books: books_response.append({ "id": book.id, "title": book.title, "description": book.description }) # books_response contains a list of book dictionaries. To turn it into # a Response object, we pass it into jsonify(). This will be our common # practice when returning a list of something because the make_response # function does not handle lists. return jsonify(books_response) elif request.method == "POST": request_body = request.get_json() new_book = Book(title=request_body["title"], description=request_body["description"]) # db.session is the database's way of collecting changes that need to be # made. Here, we are saying we want the database to add new_book. db.session.add(new_book) # Here, we are saying we want the database to save and commit the # collected changes. db.session.commit() # For each endpoint, we must return the HTTP response # make_response: This function instantiates a Response object. A Response # object is generally what we want to return from Flask endpoint # functions. return make_response( f"Book {new_book.title} successfully created", 201)
def save_to_mysql(q, page=1): yushu_book.search_by_keyword(q, page) books = yushu_book.books for item in books: if not Book.query.filter_by(isbn=item["isbn"]).first(): del item["id"] item["author"] = "、".join(item["author"]) item["translator"] = "、".join(item["translator"]) print(item["title"]) with db.auto_commit(): db.session.add(Book(**item)) print(q, item["title"] + "-----------入库成功 ok...") else: print(q, item["title"] + " ------------已存在")