def put_book(): book_code = request.form.get("book_code") title = request.form.get("title") author = request.form.get("author") year = request.form.get("year") if not book_code and not title and not author and not year: return make_response(jsonify({"code": 403, "msg": "Cannot put book. Missing mandatory fields."}), 403) book_id = request.form.get("id") if not book_id: p = models.Book(book_code=book_code, title=title, author=author, year=year) else: p = models.Book(id=book_id, book_code=book_code, title=title, author=author, year=year) models.db.session.add(p) try: models.db.session.commit() except sqlalchemy.exc.SQLAlchemyError as e: error = "Cannot put book. " print(app.config.get("DEBUG")) if app.config.get("DEBUG"): error += str(e) return make_response(jsonify({"code": 404, "msg": error}), 404) return jsonify({"code": 200, "msg": "Successfully added book."})
def init(): db.drop_all() db.create_all() book = models.Book() book.BookId = 10000 book.Title = "python" book.AuthorId = 20000 db.session.add(book) book = models.Book() book.BookId = 10001 book.Title = "html" book.AuthorId = 20000 db.session.add(book) book = models.Book() book.BookId = 10002 book.Title = "javascript" book.AuthorId = 20001 db.session.add(book) db.session.commit() return "initdb ok"
def book(request): if request.method == 'POST': print(request.POST) book_name = request.POST.get('name') publisher_id = request.POST.get('publisher_id') print('==>', request.POST.get('author_ids')) author_ids = request.POST.getlist('author_ids') #print(dir( request.POST)) print(book_name, publisher_id, author_ids) new_book = models.Book(name=book_name, publisher_id=publisher_id, publish_date='2016-05-22') new_book.save() new_book.authors.add(*author_ids) #new_book.authors.add(1,2,3,4) books = models.Book.objects.all() publisher_list = models.Publisher.objects.all() author_list = models.Author.objects.all() return render(request, 'app01/book.html', { 'books': books, 'publishers': publisher_list, 'authors': author_list })
def edit_book(id_book): book = db.session.query( models.Book).filter(models.Book.id == id_book).first() authors = set(string_to_list_process(request.form['authors'].split(','))) name_book = request.form['name'] if not name_book and not authors: flash(u'Changes have not been applied', 'error') return redirect(url_for('books')) if not name_book.strip(): name_book = book.name else: q = db.session.query(models.Book).filter(models.Book.name == name_book) if db.session.query(q.exists()).scalar() and name_book != book.name: flash(u'This name is already exists', 'error') return redirect(url_for('books')) db.session.delete(book) db.session.commit() book = models.Book(name=name_book, authors=get_checked_authors(authors)) db.session.add(book) db.session.commit() return redirect(url_for('books'))
def submit(): app.logger.debug(request.form.getlist('bookType')) app.logger.debug(request.form.getlist('genre')) app.logger.debug(request.form.getlist('itpStatus')) # get new books items form from models.py book_form = models.BookForm(request.form) if request.method == "POST" and book_form.validate(): # get form data - create new book book = models.Book() book.title = request.form.get('title', 'no title') book.slug = slugify(book.title) book.author = request.form.get('author', 'anonymous') book.bookType = request.form.getlist('bookType') book.genre = request.form.getlist('genre') book.description = request.form.get('description', '') book.owner = request.form.get('owner') book.email = request.form.get('email') book.itpStatus = request.form.getlist('itpStatus') book.save() return redirect('/books/%s' % book.slug) else: # for form management, checkboxes are weird (in wtforms) # prepare checklist items for form # you'll need to take the form checkboxes submitted # and book_form.bookType, book_form.genre and book_form.itpStatus list needs to be populated. if request.form.getlist('bookType'): for b in request.form.getlist('bookType'): idea_form.bookType.append_entry(b) if request.form.getlist('genre'): for g in request.form.getlist('genre'): idea_form.genre.append_entry(g) if request.form.getlist('itpStatus'): for i in request.form.getlist('itpStatus'): idea_form.itpStatus.append_entry(i) # render the template templateData = { 'books': models.Book.objects(), 'bookType': bookType, 'genre': genre, 'itpStatus': itpStatus, 'form': book_form } return render_template("submit.html", **templateData)
def add_book(title, year, plot, language, authors): book = models.Book(title, year, plot, language) for author_id in authors: author = models.Author.query.filter_by(id=author_id).first() book.written_by.append(author) models.db.session.add(book) models.db.session.commit() return book.id
def _getInstance(cls): """ create an instance of class and init its params """ import models sig = signature(getattr(models.__dict__.get(cls), "__init__")) if len(sig.parameters) == 2: obj = models.__dict__.get(cls)("") else: obj = models.__dict__.get(cls)(models.Book(""), models.Author("")) return obj
def create_book(db: Session, book: schemas.BookCreate): db_book = models.Book(nameBook=book.nameBook, avtor=book.avtor, genre=book.genre, kindOf=book.kindOf, year=book.year, code=book.code) db.add(db_book) db.commit() db.refresh(db_book) return db_book
def post(self): ''' Add a book to the library :return: A Json format of new book ''' body = request.get_json() new_book = models.Book() new_book.parse_body(body) db.session.add(new_book) db.session.commit() return new_book.serialize(), 201
def add_path(path): if path in [book.input_path for book in conversion_queue]: raise FileAlreadyAddedError elif filetype_not_supported(path): raise FiletypeNotSupportedError elif not os.path.exists(path): raise FileNotFoundError book = models.Book(input_path=path) conversion_queue.append(book) return book
def new_book(): form = forms.BookForm() if form.validate_on_submit(): flash('Great, you added a new book.', 'success') book = models.Book( title=form.title.data.strip(), status=form.status.data, user_id=g.user._get_current_object().id, ) db.session.add(book) db.session.commit() return redirect(url_for('books_page', username=current_user.username)) return render_template('create_book.html', form=form)
def testDeleteWithNormal(self): author = models.Author.objects.get(vid=1) author_id = author.pk author.publish() cartoon = models.Cartoon.objects.get(vid=1) self.assertEqual(cartoon.author, author) cartoon.publish() book = models.Book.objects.get(vid=1) book.publish() book2 = models.Book(name='test', author_id=2) book2.save() with manager.SwitchSchema('public'): self.assertEqual( models.Author.normal.filter(associates__pk=2).count(), 2) self.assertEqual( models.Cartoon.normal.filter(author=author).count(), 2) self.assertEqual( models.Cartoon.normal.filter(author__isnull=True).count(), 0) # Switch to draft mode to restrict what the ORM # will normally see with manager.SwitchSchema('draft'): self.assertEqual( models.Book.objects.filter(author=author).count(), 1) self.assertEqual( models.Gallery.objects.filter(book__author=author).count(), 2) self.assertEqual( models.Review.objects.filter(book__author=author).count(), 2) book = models.Book.objects.get(vid=1) self.assertEqual(book.author, author) author.delete() with manager.SwitchSchema('public'): self.assertEqual( models.Author.normal.filter(associates__pk=2).count(), 0) self.assertFalse( models.Author.normal.filter(pk=author_id).exists()) self.assertEqual( models.Cartoon.normal.filter(author_id=author_id).count(), 0) self.assertEqual( models.Cartoon.normal.filter(author__isnull=True).count(), 2) self.assertEqual(models.Book.normal.all().count(), 1) self.assertEqual(models.Review.objects.all().count(), 0) self.assertEqual(models.Gallery.objects.all().count(), 0)
def create_new_book(book_dto, creator): book = models.Book() try: new_book = BookUtils.convert_new_book_request_object_for_persistence( book_dto, book) if isinstance(new_book, str): return {'error': new_book}, 404 new_book.created_by = creator.get('id') new_book.last_updated_by = creator.get('id') new_book.save() return { 'response': dataStateAccess.BookDTO.book_dto(new_book) }, 201 except Exception as e: return {'error': f"Exception, {e}, occurred."}, 500
def buildObjects(db): u1 = models.User(name="Meghana", email="*****@*****.**") u1.set_password('admin') a1 = models.Author(name='John Williams') b1 = models.Book(title="Once upon a time", description="Great book") b2 = models.Book(title="Second upon a time", description="Another classic") l = models.Library() b1.author = a1 b2.author = a1 l.user = u1 assoc = models.AssociationBookLibrary(library=l) assoc.book = b2 db.session.add(a1) db.session.add(b1) db.session.add(b2) db.session.add(u1) db.session.add(l) db.session.commit()
def create_metadata_sql(catalog): session = models.get_session() for book in catalog: b = models.Book() b.lang = book.lang b.mdate = book.mdate b.bookid = book.bookid b.author = book.author b.title = book.title b.subj = unicode(book.subj) b.loc = unicode(book.loc) b.pgcat = book.pgcat b.desc = book.desc b.toc = book.toc b.alttitle = unicode(book.alttitle) b.friendlytitle = book.friendlytitle session.add(b) session.commit()
def get_book_info(url): text = data.spider.get_html_text(url) soup = BeautifulSoup(text, "html.parser") infos = soup.select_one('#info') book = models.Book() for info in infos.find_all('span'): attr = info.text.replace(' ', '').replace('\n', '') \ .split(':') # 获取书籍属性值 if attr[0] == '作者': book.authors = attr[1] elif attr[0] == 'ISBN': book.isbn = attr[1] elif attr[0] == '页数': book.pages = attr[1] elif attr[0] == '定价': book.price = attr[1] # 插入数据库 book
def add(self, bookdata): book = models.Book() book = self.parse(book, bookdata) # check if author is real author = self.detect_author(bookdata['author']) book.author = author # check if series is real series_name = bookdata.setdefault('series_name', "") if (series_name is not None and len(series_name) > 0): ctrl = SeriesController() series = ctrl.setdefault(bookdata['series_name']) book.series = series book.series_nr = bookdata.setdefault('series_nr') self.session.add(book) return book
def post(self): bid = self.get_safe_argument('bid', int) form = self.get_form(f.edit_book_form) error, form_error_message = self.validate(form, f.edit_book_form) if error: args = { 'form': form, 'form_error_message': form_error_message, } self.jinja_render('dev_edit_book.html', **args) return None if bid is not None: book = db.query(m.Book).filter_by(id=bid).first() book.update(**form) logging.debug("main->BookEditorHandler->post" ":update") else: logging.debug("main->BookEditorHandler->post" ":add") book = m.Book(**form) db.add(book) db.commit() self.redirect('/book/%s' % (book.id))
def test(): models.User.query.delete() models.Book.query.delete() models.Review.query.delete() models.Author.query.delete() # Adding users user1 = models.User( 'admin', '*****@*****.**', 'Sweden', 'Send me an email if a book is missing in the database.', str(datetime.date.today()), True) models.db.session.add(user1) models.db.session.commit() user1 = models.User('Pelle Nordfors', '*****@*****.**', 'Sweden', 'hi everyone!', str(datetime.date.today()), False) models.db.session.add(user1) models.db.session.commit() user2 = models.User( 'mrs. Lovett', '*****@*****.**', 'England', '''A great fan of fiction. Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. ''', str(datetime.date.today()), False) models.db.session.add(user2) models.db.session.commit() user3 = models.User('Elphaba Thropp', '*****@*****.**', 'Oz', 'I like books. Especially The Grimmerie!', str(datetime.date.today()), False) models.db.session.add(user3) models.db.session.commit() user4 = models.User('George Banks', '*****@*****.**', 'England', 'Hi! Mary Poppins in my favorite book!', str(datetime.date.today()), False) models.db.session.add(user4) models.db.session.commit() user5 = models.User('Magda Keller', '*****@*****.**', 'Hungary', 'Umm... I rarely read at all.', str(datetime.date.today()), False) models.db.session.add(user5) models.db.session.commit() # Adding Lolita by Nabokov author = models.Author('Vladimir Nabokov', 'Russia', 1899) book = models.Book( 'Lolita', 1955, 'A man marries his landlady so he can take advantage of her daughter.', 'English') book.written_by.append(author) models.db.session.add(author) models.db.session.commit() review = models.Review('Awesome!', 'blabla', 9, 'Swedish', str(datetime.date.today()), user1, book) models.db.session.add(review) review = models.Review('This is filth!', 'blablabla', 2, 'English', str(datetime.date.today()), user2, book) models.db.session.add(review) models.db.session.commit() database_helper.update_avg_score(book.id) # Adding It by King author = models.Author('Stephen King', 'USA', 1947) book = models.Book( 'It', 1986, 'In 1960, seven outcast kids known as "The Loser Club" fight an evil demon.', 'English') book.written_by.append(author) models.db.session.add(author) models.db.session.commit() database_helper.update_avg_score(book.id) # Adding The Shining by King book = models.Book( 'The Shining', 1977, 'A recovering alcoholic and his family move into a haunted hotel as caretakers.', 'English') book.written_by.append(author) models.db.session.add(author) models.db.session.commit() database_helper.update_avg_score(book.id) # Adding Carrie by King book = models.Book( 'Carrie', 1974, 'A classic horror tale about Carrie White, a shy girl.', 'English') book.written_by.append(author) models.db.session.add(author) models.db.session.commit() database_helper.update_avg_score(book.id) # Adding Misery by King book = models.Book( 'Misery', 1987, 'Paul Sheldon, a successful novelist, is rescued after a snow storm by his "Number One Fan".', 'English') book.written_by.append(author) models.db.session.add(author) models.db.session.commit() database_helper.update_avg_score(book.id)
from datetime import datetime engine = create_engine(config.DATABASE_URI) #engine def recreate_database(): #db create and recreate models.Base.metadata.drop_all(engine) models.Base.metadata.create_all(engine) from sqlalchemy.orm import sessionmaker # session Session = sessionmaker(bind=engine) recreate_database() book = models.Book( #first entry to table title='Deep Learning', author='Ian Goodfellow', pages=775, published=datetime(2016, 11, 18) ) s = Session() s.add(book) #add and commit to db table s.commit() q1 = s.query(models.Book).first() print(q1) s.close_all() # ending session to avoid dupication in entries recreate_database() s = Session() import yaml # table entries to table from a yml file
import models import csv db = models.create("postgresql://*****:*****@127.0.0.1:5432/books") session = db.session_factory() books = csv.reader(open('./books.csv')) lines = 0 dbBooks = [] for book in books: if lines == 0: lines = 1 else: lines += 1 dbBooks.append( models.Book(isbn=book[0], title=book[1], author=book[2], year=book[3])) session.add_all(dbBooks) session.commit()
douban_id = "" book = None try: book = json.loads(dc.get_book_by_isbn(isbn)) except Exception, e: pass if book == None: return None title = book['title']['$t'] if book.has_key('title') else "" author = book['author'][0]['name']['$t'] if book.has_key('author') else "" cover = book['link'][2]['@href'] if book.has_key('link') else "" douban_id = book['link'][0]['@href'].split('/')[-1] b = models.Book(isbn=isbn, title=title, author=author, cover=cover, douban_id=douban_id) b.save() if book.has_key('db:tag'): try: b.tags = ','.join([i['@name'] for i in book['db:tag']]) except IntegrityError: pass return b def get_random_books(num): cnt = models.Book.objects.count() idx = random.randint(0, cnt) return models.Book.objects.order_by('-id')[idx:idx + num]
def index(): isbn_form = ISBNSearchForm() alt_form = AltSearchForm() base_book = 'https://api.isbndb.com/book/' base_kw = 'https://api.isbndb.com/books/' base_auth = 'https://api.isbndb.com/author/' headers = {'X-API-KEY': isbn_key} max_return = '?pageSize=25' if request.method == 'POST': if request.form.get('search') == 'Search': isbn = str(request.form['isbn']) response = requests.get(base_book + isbn, headers=headers) if response.status_code == 403: flash('There was an issue locating that ISBN...idiot', 'warning') else: json_resp = json.loads(response.text) session['isbndb_results'] = json_resp signal = 'isbn' flash('Info for that shit below...', 'info') return render_template('index.html', data=json_resp, isbn_form=isbn_form, alt_form=alt_form, signal=signal) elif request.form.get('alt-search') == 'Alt-Search': signal = '' # json_resp = None if alt_form.keywords.data: kw = str(alt_form.keywords.data) response = requests.get(base_kw + kw + max_return, headers=headers) json_resp = json.loads(response.text) session['isbndb_results'] = json_resp signal = 'alt-search' print(json_resp) if 'errorMessage' in json_resp: flash('The keyword there was shit, no returned results', 'warning') else: flash('I got you baby...', 'info') elif alt_form.author.data: auth = str(alt_form.author.data) response = requests.get(base_auth + auth + max_return, headers=headers) json_resp = json.loads(response.text) session['isbndb_results'] = json_resp signal = 'alt-search' if 'errorMessage' in json_resp: flash('Don"t know that guy, or gal', 'warning') else: flash('There he/she is', 'info') return render_template('index.html', data=json_resp, alt_form=alt_form, isbn_form=isbn_form, signal=signal) elif request.form.get('add') == 'Add': pub_date_parsed = parse( session['isbndb_results']['book']['date_published']) bad_chars = '[]{}\"\'' s = str(session['isbndb_results']['book']['authors']) auth = "".join(c for c in s if c not in bad_chars) book = models.Book( author=auth, isbn=session['isbndb_results']['book']['isbn13'], date_published=pub_date_parsed, title=session['isbndb_results']['book']['title'], ) db.session.add(book) db.session.commit() flash('That shit got added yo...', 'info') return redirect(url_for('index')) return render_template('index.html', isbn_form=isbn_form, alt_form=alt_form, signal=None)
def addbook(): name = request.form['name'] genre = request.form['book'] db.session.add(models.Book(name, genre))