rqlite update

master
Alex 7 years ago
parent d0c8cb968e
commit d029e57c72

@ -11,7 +11,7 @@ basedir = os.path.abspath(os.path.dirname(__file__))
UPLOAD_FOLDER = os.path.join(basedir, 'uploads') UPLOAD_FOLDER = os.path.join(basedir, 'uploads')
UPLOAD_FOLDER_COVER = os.path.join(basedir, 'uploads/cover') UPLOAD_FOLDER_COVER = os.path.join(basedir, 'uploads/cover')
ALLOWED_EXTENSIONS = set(['txt', 'pdf', 'png', 'jpg', 'jpeg', 'gif']) #ALLOWED_EXTENSIONS = set(['txt', 'pdf', 'png', 'jpg', 'jpeg', 'gif'])
app = Flask(__name__) app = Flask(__name__)

@ -56,21 +56,6 @@ class Author(db.Model):
def __init__(self, author_name): def __init__(self, author_name):
self.author_name = author_name self.author_name = author_name
class AuthorSchema(Schema):
id = fields.Int(dump_only=True)
author_name = fields.Str()
class BookSchema(Schema):
id = fields.Int(dump_only=True)
title = fields.Str()
file = fields.Str()
authors = fields.Nested(AuthorSchema, many=True)
cover = fields.Str()
fileformat = fields.Str()
category = fields.Str()
stack = fields.Str()
class Stack(db.Model): class Stack(db.Model):
__tablename__ = 'stacks' __tablename__ = 'stacks'
id = db.Column(db.Integer, primary_key = True) id = db.Column(db.Integer, primary_key = True)
@ -87,11 +72,31 @@ class Stack(db.Model):
def get_id(self): def get_id(self):
return self.id return self.id
class AuthorSchema(Schema):
id = fields.Int(dump_only=True)
author_name = fields.Str()
class StackSchema(Schema): class StackSchema(Schema):
id = fields.Int(dump_only=True) id = fields.Int(dump_only=True)
stack_name = fields.Str() stack_name = fields.Str()
stack_description = fields.Str() stack_description = fields.Str()
class BookSchema(Schema):
id = fields.Int(dump_only=True)
title = fields.Str()
file = fields.Str()
authors = fields.Nested(AuthorSchema, many=True)
cover = fields.Str()
html = fields.Str()
fileformat = fields.Str()
category = fields.Str()
year_published = fields.Str()
stacks = fields.Nested(StackSchema, many=True)
def must_not_be_blank(data): def must_not_be_blank(data):
if not data: if not data:
raise ValidationError('You forgot to write stuff.') raise ValidationError('You forgot to write stuff.')

@ -103,6 +103,24 @@ $( function() {
} }
}); });
} ); } );
$( "#title" ).click(function() {
generateTitle(this);
});
$( document ).ready(function() {
generateTitle("#title");
});
function generateTitle(elem){
var x = ["XPERIMENTAL"]
var p1 = ["POTENTIAL", "PUBLIC", "POST", "PI", "PLATFORM FOR", "PRETENTIOUS"]
var p2 = ["PIRATE", "PERFORMATIVE", "PUBLIC", "PUBLISHING", "POTENTIAL"]
var l = ["LIBRARY", "LIAISON", "LAB", "LEGALITY", "LABOUR"]
$(elem).text(x[Math.floor(Math.random()*x.length)]+" "+p1[Math.floor(Math.random()*p1.length)]+" "+p2[Math.floor(Math.random()*p2.length)]+" "+l[Math.floor(Math.random()*l.length)]);
}
</script> </script>
</body> </body>
</html> </html>

@ -1,7 +1,7 @@
{% extends "base.html" %} {% extends "base.html" %}
{% block main %} {% block main %}
<h1 class="header">XPPL</h1> <h1 class="header" id="title">XPPL</h1>
<p class="lead">This is the awesome library of Experimental Publishing. <br> <p class="lead">This is the awesome library of Experimental Publishing. <br>
This might only be one interface to this library: This might only be one interface to this library:

@ -23,6 +23,8 @@ author_schema = AuthorSchema()
authors_schema = AuthorSchema(many=True) authors_schema = AuthorSchema(many=True)
book_schema = BookSchema() book_schema = BookSchema()
books_schema = BookSchema(many=True) books_schema = BookSchema(many=True)
stack_schema = StackSchema()
stacks_schema = StackSchema(many=True)
def allowed_file(filename): def allowed_file(filename):
return '.' in filename and \ return '.' in filename and \
@ -96,7 +98,7 @@ def remove_book_by_id(id):
book_to_edit = Book.query.filter_by(id=id).first() book_to_edit = Book.query.filter_by(id=id).first()
title = book_to_edit.title title = book_to_edit.title
Book.query.filter_by(id=id).delete() Book.query.filter_by(id=id).delete()
author_table = Author.query.filter_by(book_id=book_to_edit.id).delete() #author_table = Author.query.filter_by(book_id=book_to_edit.id).delete()
db.session.commit() db.session.commit()
flash("%s deleted from library" % (title)) flash("%s deleted from library" % (title))
return redirect(url_for('show_books')) return redirect(url_for('show_books'))
@ -120,20 +122,7 @@ def edit_book_by_id(id):
book.title = title book.title = title
book.category = category book.category = category
if(len(book.authors)==1):
book.authors[0].author_name = input_authors[0].get("author_name")
#book.authors.clear()
for i, author in enumerate(input_authors):
if i > 0:
author_name = author.get("author_name")
if author_name:
a = db.session.query(Author).filter_by(author_name=author_name).first()
if a == None:
a = Author(author_name=author_name)
db.session.add(a)
book.authors.append(a)
else:
book.authors.clear() book.authors.clear()
for i, author in enumerate(input_authors): for i, author in enumerate(input_authors):
author_name = author.get("author_name") author_name = author.get("author_name")
@ -304,8 +293,8 @@ def search_results(query):
@app.route('/api/books', methods=['GET']) @app.route('/api/books', methods=['GET'])
def get_books(): def get_books():
books = Book.query.all() books = Book.query.all()
data, errors = books_schema.dump(books) data = books_schema.dump(books)
print(errors) #print(errors)
return jsonify({'books': data}) return jsonify({'books': data})
@app.route('/api/books/<int:id>', methods=['GET']) @app.route('/api/books/<int:id>', methods=['GET'])

@ -1,58 +1,76 @@
from sqlalchemy import create_engine #!/usr/bin/env python
from sqlalchemy import Table, Column, Integer, String, ForeignKey, Sequence
import argparse
import functools
import logging
import pyrqlite.dbapi2 as dbapi2
#import sqlite3 as dbapi2
from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker, relationship from sqlalchemy.orm import sessionmaker, relationship
from sqlalchemy.orm import Session
from sqlalchemy import Table, Column, Integer, String, ForeignKey, Sequence, create_engine
from sqlalchemy.dialects import registry
registry.register("rqlite.pyrqlite", "sqlalchemy_rqlite.pyrqlite", "dialect")
Base = declarative_base() Base = declarative_base()
books_authors = Table(
teachers_lessons = Table( "books_authors",
"teachers_lessons",
Base.metadata, Base.metadata,
Column("fk_teacher", Integer, ForeignKey("teachers.id")), Column("book", Integer, ForeignKey("books.id")),
Column("fk_lesson", Integer, ForeignKey("lessons.id")), Column("author", Integer, ForeignKey("authors.id")),
) )
class Book(Base):
class Teacher(Base): __tablename__ = 'books'
__tablename__ = "teachers" id = Column(Integer, primary_key=True)
title = Column("title", String(50), nullable=False)
id = Column("id", Integer, Sequence("teachers_id_seq"), primary_key=True) authors = relationship(
name = Column("name", String(50), nullable=False) "Author",
backref="books",
lessons = relationship( secondary=books_authors
"Lesson",
backref="teachers",
secondary=teachers_lessons
) )
def __init__(self, title):
self.title = title
class Lesson(Base): class Author(Base):
__tablename__ = "lessons" __tablename__ = "authors"
id = Column("id", Integer, Sequence("authors_id_seq"), primary_key=True)
id = Column("id", Integer, Sequence("lessons_id_seq"), primary_key=True)
name = Column("name", String(50), nullable=False) name = Column("name", String(50), nullable=False)
def __init__(self, title):
self.name = name
engine = create_engine('rqlite+pyrqlite://localhost:4001/', echo=True) def main():
Base.metadata.create_all(engine) parser = argparse.ArgumentParser()
Session = sessionmaker(bind=engine) parser.add_argument('-v', '--verbose', action='store_true', default=False)
args = parser.parse_args()
if args.verbose:
logging.basicConfig()
logging.getLogger().setLevel(logging.DEBUG)
if __name__ == "__main__": engine = create_engine('rqlite+pyrqlite://localhost:4001/', echo=args.verbose)
s = Session()
t1 = Teacher(name="NEWNEW") Base.metadata.create_all(engine)
t1.lessons = [ session = Session(engine)
Lesson(name="fpro"),
Lesson(name="math")
]
s.add(t1)
s.commit()
t2 = s.query(Teacher).filter_by(name='NEWNEW').first() #insert
t2.lessons.clear() # for i in range(1):
s.commit() # book = Book("book about dbs2")
# author = Author("footurist")
# book.authors.append(author)
# session.add(book)
# session.commit()
#delete
desired_book = session.query(Book).filter_by(id=3).delete()
#desired_author = session.query(Author).filter_by(id=2).first()
#desired_book.authors.clear()
#desired_book.authors.append(desired_author)
session.commit()
if __name__ == '__main__':
main()

@ -0,0 +1,49 @@
from sqlalchemy import create_engine
from sqlalchemy import Table, Column, Integer, String, ForeignKey, Sequence
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker, relationship
Base = declarative_base()
teachers_lessons = Table(
"teachers_lessons",
Base.metadata,
Column("fk_teacher", Integer, ForeignKey("teachers.id")),
Column("fk_lesson", Integer, ForeignKey("lessons.id")),
)
class Teacher(Base):
__tablename__ = "teachers"
id = Column("id", Integer, Sequence("teachers_id_seq"), primary_key=True)
name = Column("name", String(50), nullable=False)
lessons = relationship(
"Lesson",
backref="teachers",
secondary=teachers_lessons
)
class Lesson(Base):
__tablename__ = "lessons"
id = Column("id", Integer, Sequence("lessons_id_seq"), primary_key=True)
name = Column("name", String(50), nullable=False)
engine = create_engine('rqlite+pyrqlite://localhost:4001/', echo=True)
Base.metadata.create_all(engine)
Session = sessionmaker(bind=engine)
if __name__ == "__main__":
t2 = s.query(Teacher).filter_by(name='NEWNEW').first()
t2.lessons.clear()
s.commit()
Loading…
Cancel
Save