コード例 #1
0
    def setUp(self):
        self.client = APIClient()
        self.url = "/api/book/"
        authors = [Author(name=author['name']) for author in self.authors]
        Author.objects.bulk_create(authors)

        self.books = [
            {
                "name": "Book 1",
                "edition": 1,
                "publication_year": 2020,
                "authors": [1, 2]
            },
            {
                "name": "Book 2",
                "edition": 1,
                "publication_year": 2019,
                "authors": [2]
            },
            {
                "name": "Book 2",
                "edition": 2,
                "publication_year": 2021,
                "authors": [2]
            },
            {
                "name": "Book 3",
                "edition": 1,
                "publication_year": 2020,
                "authors": [1]
            },
        ]

        self.setup_books(self.books)
コード例 #2
0
def client():
    """
    Create a temporary db with some data in it for using in the tests.
    """
    app.config["TESTING"] = True
    app.testing = True

    app.config["SQLALCHEMY_DATABASE_URI"] = "sqlite:///test.db"

    client = app.test_client()
    with app.app_context():
        db.create_all()
        author1 = Author(name='Shakespeare', country='UK', year_of_birth=1800)
        author2 = Author(name='Stephen King',
                         country='USA',
                         year_of_birth=1945)
        db.session.add(author1)
        db.session.add(author2)
        db.session.commit()
    yield client
    os.remove('library_app/test.db')
コード例 #3
0
def authors_view():
    if request.method == 'GET':
        authors = author.get_all(filters=request.args)
        return jsonify(data=Author.serialize_list(authors))

    if request.method == 'POST':
        try:
            author.create(name=request.json['name'],
                          country=request.json.get('country'),
                          year_of_birth=request.json.get('year_of_birth'))
            return make_response(jsonify(response='OK'), 201)
        except sqlalchemy.exc.InvalidRequestError:
            return make_response(jsonify(error='Bad request'), 400)
コード例 #4
0
def add_data():
    """Add sample data to the database"""
    try:
        data_json = load_json_data('authors.json')
        for item in data_json:
            item['birth_date'] = datetime.strptime(item['birth_date'],
                                                   '%d-%m-%Y').date()
            author = Author(**item)
            db.session.add(author)

        data_json = load_json_data('books.json')
        for item in data_json:
            book = Book(**item)
            db.session.add(book)

        db.session.commit()
        print('Data has been added to database')

    except Exception as exc:
        print(f'Unexpected error: {exc}')
コード例 #5
0
def authors_view():
    if request.method == 'GET':
        authors = author.get_all(filters=request.args)
        return jsonify(data=Author.serialize_list(authors))

    if request.method == 'POST':
        try:
            allowed_fields = ['name', 'country', 'year_of_birth']
            extra_fields = {
                k: v
                for k, v in request.json.items() if k not in allowed_fields
            }
            if len(extra_fields) > 0:
                return make_response(
                    jsonify(
                        response=
                        "Only name, country and year_of_birth are allowed"),
                    400)
            author.create(name=request.json['name'],
                          country=request.json.get('country'),
                          year_of_birth=request.json.get('year_of_birth'))
            return make_response(jsonify(response='OK'), 201)
        except sqlalchemy.exc.InvalidRequestError:
            return make_response(jsonify(error='Bad request'), 400)
コード例 #6
0
ファイル: authors.py プロジェクト: gregzajac/Python-examples
def create_author(user_id: int, args: dict):
    author = Author(**args)
    db.session.add(author)
    db.session.commit()

    return jsonify({'success': True, 'data': author_schema.dump(author)}), 201
コード例 #7
0
def create(name, country=None, year_of_birth=None):
    new_author = Author(name=name, country=country, year_of_birth=year_of_birth)
    db.session.add(new_author)
    db.session.commit()
コード例 #8
0
 def setUp(self):
     self.client = APIClient()
     self.url = "/api/author/"
     authors = [Author(name=author['name']) for author in self.authors]
     Author.objects.bulk_create(authors)