示例#1
0
# app.py
from fastapi import FastAPI
from fastapi.routing import Mount
from movies.tables import Director, Movie
from piccolo.engine import engine_finder

from piccolo_admin.endpoints import create_admin

app = FastAPI(
    routes=[
        Mount(
            "/admin/",
            create_admin(
                tables=[Director, Movie],
                # Specify a different site name in the
                # admin UI (default Piccolo Admin)
                site_name="My Site Admin",
                # Required when running under HTTPS:
                # allowed_hosts=['my_site.com']
            ),
        ),
    ], )


@app.on_event("startup")
async def open_database_connection_pool():
    engine = engine_finder()
    await engine.start_connnection_pool()


@app.on_event("shutdown")
async def close_database_connection_pool():
示例#2
0
import uvicorn
from movies.endpoints import HomeEndpoint
from movies.tables import Director, Movie
from starlette.routing import Mount, Route, Router

from piccolo_admin.endpoints import create_admin

# The `allowed_hosts` argument is required when running under HTTPS. It's
# used for additional CSRF defence.
admin = create_admin([Director, Movie], allowed_hosts=["my_site.com"])

router = Router([
    Route(path="/", endpoint=HomeEndpoint),
    Mount(path="/admin/", app=admin),
])

if __name__ == "__main__":
    uvicorn.run(router)
示例#3
0
# Security Headers are HTTP response headers that, when set,
# can enhance the security of your web application
# by enabling browser security policies.
# more on https://secure.readthedocs.io/en/latest/headers.html
secure_headers = SecureHeaders()

routes = [
    Route("/", HomeEndpoint, name="index"),
]

app = Starlette(debug=True, routes=routes)

app.mount(
    "/admin/",
    create_admin(tables=[Ad, Review, Image, Rent, Notification]),
)
app.mount("/static", StaticFiles(directory="static"), name="static")
app.mount("/accounts", accounts_routes)
app.mount("/ads", ads_routes)

app.add_middleware(AuthenticationMiddleware, backend=UserAuthentication())
app.add_middleware(SessionMiddleware, secret_key=SECRET_KEY)


# middleware for secure headers
@app.middleware("http")
async def set_secure_headers(request, call_next):
    response = await call_next(request)
    secure_headers.starlette(response)
    return response
示例#4
0
    {data.content}
    """

    try:
        smtpObj = smtplib.SMTP("localhost:1025")
        smtpObj.sendmail(sender, receivers, message)
        print("Successfully sent email")
    except smtplib.SMTPException:
        print("Error: unable to send email")

    return "Email sent"


app = FastAPI(routes=[
    Mount(
        "/admin/",
        create_admin(
            tables=[Task],
            forms=[
                FormConfig(
                    name="Business Email Form",
                    pydantic_model=EmailFormModel,
                    endpoint=email_endpoint,
                ),
            ],
        ),
    ),
], )

# For Starlette it is identical, just `app = Starlette(...)`
示例#5
0
from piccolo_api.fastapi.endpoints import FastAPIKwargs, FastAPIWrapper
from starlette.routing import Mount, Route

from accounts.endpoints import oauth2_scheme, router
from forum.tables import Category, Reply, Topic
from home.endpoints import HomeEndpoint

app = FastAPI(
    title="Simple headless forum",
    routes=[
        Route("/", HomeEndpoint),
        Mount(
            "/admin/",
            create_admin(
                tables=[Category, Reply, Topic],
                # Required when running under HTTPS:
                # allowed_hosts=['my_site.com']
            ),
        ),
    ],
)

origins = [
    "http://localhost:8080",
]

app.add_middleware(
    CORSMiddleware,
    allow_origins=origins,
    allow_credentials=True,
    allow_methods=["*"],
示例#6
0
    def get_readable(cls):
        return Readable(template="%s", columns=[cls.name])


class Movie(Table, db=DB):
    name = Varchar(length=300)
    rating = Real()
    duration = Integer()
    director = ForeignKey(references=Director)
    won_oscar = Boolean()
    description = Text()
    release_date = Timestamp()
    box_office = Numeric(digits=(5, 1))


APP = create_admin([Director, Movie], auth_table=User, session_table=Sessions)


def populate_data():
    # Recreate the database
    if os.path.exists(DB_PATH):
        os.unlink(DB_PATH)
    Director.create_table().run_sync()
    Movie.create_table().run_sync()
    User.create_table().run_sync()
    Sessions.create_table().run_sync()

    # Add some rows
    Director.insert(*[Director(**d) for d in DIRECTORS]).run_sync()
    Movie.insert(*[Movie(**m) for m in MOVIES]).run_sync()
示例#7
0
from piccolo_api.crud.serializers import create_pydantic_model
from piccolo_api.csrf.middleware import CSRFMiddleware
from piccolo_api.openapi.endpoints import swagger_ui
from piccolo_api.session_auth.endpoints import session_login, session_logout
from piccolo_api.session_auth.middleware import SessionsAuthBackend

# The main app with public endpoints, which will be served by Uvicorn
app = FastAPI(
    routes=[
        # If we want to use Piccolo admin:
        Mount(
            "/admin/",
            create_admin(
                tables=[Task],
                # Required when running under HTTPS:
                # allowed_hosts=['my_site.com']
            ),
        ),
        # Session Auth login:
        Mount(
            "/login/",
            session_login(redirect_to="/private/docs/"),
        ),
    ],
    docs_url=None,
    redoc_url=None,
)

# The private app with SessionAuth protected endpoints
private_app = FastAPI(
示例#8
0
from piccolo_admin.endpoints import create_admin
from piccolo_api.crud.endpoints import PiccoloCRUD
from piccolo_api.fastapi.endpoints import FastAPIWrapper
from piccolo.engine import engine_finder
from starlette.routing import Mount
from fastapi import FastAPI

from blog.tables import Post
from blog.piccolo_app import APP_CONFIG

app = FastAPI(routes=[
    Mount("/admin/", create_admin(tables=APP_CONFIG.table_classes)),
], )

FastAPIWrapper(
    root_url="/posts/",
    fastapi_app=app,
    piccolo_crud=PiccoloCRUD(
        table=Post,
        read_only=True,
    ),
)


@app.on_event("startup")
async def open_database_connection_pool():
    engine = engine_finder()
    await engine.start_connnection_pool()


@app.on_event("shutdown")
示例#9
0
# Security Headers are HTTP response headers that, when set,
# can enhance the security of your web application
# by enabling browser security policies.
# more on https://secure.readthedocs.io/en/latest/headers.html
secure_headers = SecureHeaders()

routes = [
    Route("/", HomeEndpoint, name="index"),
]

app = Starlette(debug=True, routes=routes)

app.mount(
    "/admin/",
    create_admin(tables=[Category, Question, Answer]),
)
app.mount("/static", StaticFiles(directory="static"), name="static")
app.mount("/accounts", accounts_routes)
app.mount("/questions", questions_routes)

app.add_middleware(AuthenticationMiddleware, backend=UserAuthentication())
app.add_middleware(SessionMiddleware, secret_key=SECRET_KEY)


# middleware for secure headers
@app.middleware("http")
async def set_secure_headers(request, call_next):
    response = await call_next(request)
    secure_headers.starlette(response)
    return response
示例#10
0
        Director._meta.primary_key,
        Director.name,
        Director.gender,
    ],
)

APP = create_admin(
    [movie_config, director_config, Studio],
    forms=[
        FormConfig(
            name="Business email form",
            pydantic_model=BusinessEmailModel,
            endpoint=business_email_endpoint,
            description="Send an email to a business associate.",
        ),
        FormConfig(
            name="Booking form",
            pydantic_model=BookingModel,
            endpoint=booking_endpoint,
            description="Make a booking for a customer.",
        ),
    ],
    auth_table=User,
    session_table=Sessions,
)


def set_engine(engine: str = "sqlite"):
    if engine == "postgres":
        db = PostgresEngine(config={"database": "piccolo_admin"})
    else: