-
Notifications
You must be signed in to change notification settings - Fork 72
/
demo_http_get.py
executable file
·62 lines (53 loc) · 1.89 KB
/
demo_http_get.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
#!/usr/bin/env python3
import sys
import logging
import builtins
from flask import Flask, redirect
from flask_sqlalchemy import SQLAlchemy
from flask_swagger_ui import get_swaggerui_blueprint
from flask_cors import CORS
from safrs import SAFRSBase, SafrsApi, jsonapi_rpc
db = SQLAlchemy()
# Example sqla database object
class User(SAFRSBase, db.Model):
"""
description: User description
"""
__tablename__ = "Users"
http_methods = ["get"]
exclude_rels = ["books"]
id = db.Column(db.String, primary_key=True)
name = db.Column(db.String, default="")
email = db.Column(db.String, default="")
books = db.relationship("Book", back_populates="user", lazy="dynamic")
class Book(SAFRSBase, db.Model):
"""
description: Book description
"""
__tablename__ = "Books"
id = db.Column(db.String, primary_key=True)
name = db.Column(db.String, default="")
user_id = db.Column(db.String, db.ForeignKey("Users.id"))
user = db.relationship("User", back_populates="books")
if __name__ == "__main__":
HOST = sys.argv[1] if len(sys.argv) > 1 else "0.0.0.0"
PORT = 5000
app = Flask("SAFRS Demo Application")
app.config.update(SQLALCHEMY_DATABASE_URI="sqlite://", DEBUG=True)
db.init_app(app)
db.app = app
API_PREFIX = ""
with app.app_context():
# Create the database
db.create_all()
api = SafrsApi(app, host=f"{HOST}", port=PORT, prefix=API_PREFIX)
# Create a user and a book and add the book to the user.books relationship
user = User(name="thomas", email="em@il")
book = Book(name="test_book")
user.books.append(book)
# Expose the database objects as REST API endpoints
api.expose_object(User)
api.expose_object(Book)
# Register the API at /api/docs
print(f"Starting API: http://{HOST}:{PORT}{API_PREFIX}")
app.run(host=HOST, port=PORT)