예제 #1
0
def test_wsgi_exc_info():
    # Note that we're testing the WSGI app directly here.
    # The HTTP protocol implementations would catch this error and return 500.
    app = WSGIMiddleware(return_exc_info)
    client = TestClient(app)
    with pytest.raises(RuntimeError):
        response = client.get("/")

    app = WSGIMiddleware(return_exc_info)
    client = TestClient(app, raise_server_exceptions=False)
    response = client.get("/")
    assert response.status_code == 500
    assert response.text == "Internal Server Error"
예제 #2
0
    async def __call__(self, scope, receive, send):
        assert scope["type"] in ("http", "websocket", "lifespan")

        if scope["type"] == "lifespan":
            await self.lifespan(scope, receive, send)
            return

        path = scope["path"]
        root_path = scope.get("root_path", "")

        # Check "primary" mounted routes first (before submounted apps)
        route = self._resolve_route(scope)

        scope["before_requests"] = self.before_requests

        if route is not None:
            await route(scope, receive, send)
            return

        # Call into a submounted app, if one exists.
        for path_prefix, app in self.apps.items():
            if path.startswith(path_prefix):
                scope["path"] = path[len(path_prefix):]
                scope["root_path"] = root_path + path_prefix
                try:
                    await app(scope, receive, send)
                    return
                except TypeError:
                    app = WSGIMiddleware(app)
                    await app(scope, receive, send)
                    return

        await self.default_endpoint(scope, receive, send)
예제 #3
0
def test_wsgi_exception():
    # Note that we're testing the WSGI app directly here.
    # The HTTP protocol implementations would catch this error and return 500.
    app = WSGIMiddleware(raise_exception)
    client = TestClient(app)
    with pytest.raises(RuntimeError):
        client.get("/")
예제 #4
0
    def mount_wsgi_app(self,
                       app: WSGI_APP,
                       path: str = "/",
                       name: t.Optional[str] = None) -> None:
        from starlette.middleware.wsgi import WSGIMiddleware

        self.mount_apps.append(
            (WSGIMiddleware(app), path, name))  # type: ignore
예제 #5
0
 def start(self,
           dash_path="/",
           static_path="/static",
           static_directory="static"):
     grapp_server.mount(dash_path, WSGIMiddleware(self.app.server))
     grapp_server.mount(static_path,
                        StaticFiles(directory=static_directory),
                        name="static")
     browser(
         f'http://{"localhost" if self.host == "0.0.0.0" else self.host}:{self.port}'
     )
     uvicorn.run(grapp_server, host=self.host, port=self.port)
예제 #6
0
파일: api.py 프로젝트: mtcronin99/responder
    def __call__(self, scope):

        if scope["type"] == "lifespan":
            return self.lifespan_handler(scope)

        path = scope["path"]
        root_path = scope.get("root_path", "")

        # Call into a submounted app, if one exists.
        for path_prefix, app in self.apps.items():
            if path.startswith(path_prefix):
                scope["path"] = path[len(path_prefix):]
                scope["root_path"] = root_path + path_prefix
                try:
                    return app(scope)
                except TypeError:
                    app = WSGIMiddleware(app)
                    return app(scope)

        return self.app(scope)
예제 #7
0
def test_wsgi_post():
    app = WSGIMiddleware(echo_body)
    client = TestClient(app)
    response = client.post("/", json={"example": 123})
    assert response.status_code == 200
    assert response.text == '{"example": 123}'
예제 #8
0
def test_wsgi_get():
    app = WSGIMiddleware(hello_world)
    client = TestClient(app)
    response = client.get("/")
    assert response.status_code == 200
    assert response.text == "Hello World!\n"
예제 #9
0
)

app.layout = html.Div(children=[
    html.H1(children="Data Visualization with Dash"),
    html.Div(children="High/Low Temperatures Over Time"),
    dcc.Graph(id="temp-plot"),
    slider,
])


@app.callback(Output("temp-plot", "figure"), [Input("slider", "value")])
def add_graph(slider):
    print(type(slider))
    trace_high = obj.Scatter(x=df["Year"],
                             y=df["TempHigh"],
                             mode="markers",
                             name="High Temperatures")
    trace_low = obj.Scatter(x=df["Year"],
                            y=df["TempLow"],
                            mode="markers",
                            name="Low Temperatures")
    layout = obj.Layout(xaxis=dict(range=[slider[0], slider[1]]),
                        yaxis={"title": "Temperature"})
    figure = obj.Figure(data=[trace_high, trace_low], layout=layout)
    return figure


if __name__ == "__main__":
    server = FastAPI()
    server.mount("/dash", WSGIMiddleware(app.server))
    uvicorn.run(server)
예제 #10
0
파일: api.py 프로젝트: monkut/fastapi-zappa
from fastapi import FastAPI
from pydantic import BaseModel
from starlette.middleware.wsgi import WSGIMiddleware


class Item(BaseModel):
    name: str
    description: str = None
    price: float
    tax: float = None


app = FastAPI()


@app.post("/items/")
def create_item(item: Item):
    return item


app = WSGIMiddleware(app)
예제 #11
0
from fastapi import FastAPI
from idash import createApp  #app as idash
from uvicorn import run
from starlette.middleware.wsgi import WSGIMiddleware
from starlette.routing import Mount, Route, Router

app = FastAPI()  #openapi_prefix='/f')
d = createApp(requests_pathname_prefix='/app/')
app.mount('/app', WSGIMiddleware(app=d.server))
# app = Router([
#     Mount('/f', f ),
#     # Route('/', endpoint=f, methods=['GET']),
#     Mount('/app', WSGIMiddleware(app=d.server))
# ])

# f.mount('/app', WSGIMiddleware(idash.server))
if __name__ == '__main__':
    run(app, host='0.0.0.0', port=8888, debug=True)
예제 #12
0
import database.database_helper as dbh
from .patterns import patterns
from .dashfigs import *
from frontend.router import dashboard, dash_graph

from fastapi import Request, FastAPI
from fastapi.templating import Jinja2Templates
import json
from starlette.middleware.wsgi import WSGIMiddleware

templates = Jinja2Templates(directory="template")
app = FastAPI()
app.include_router(iris_classifier_router.router, prefix='/frontend')
app.include_router(dashboard.router)
app.mount("/dash", WSGIMiddleware(dash_graph.dashapp.server))


@app.get("/")
async def home(request: Request):
    last, today, symbols = get_time_and_symbols()
    is_potential = ["Ha", "na"]
    for symb in symbols[:20]:
        df = get_stock_data_from_db(last, symbs=symb)
        _, _is_potential = dbh.add_bands(df)
        if _is_potential:
            is_potential.append(symb)
            print(symb)

    df = get_stock_data_from_db(last, "MSFT")
    return templates.TemplateResponse(
예제 #13
0
파일: http.py 프로젝트: xoe-labs/dodoo
def routes(prod):
    app = WSGIMiddleware(odoo.WSGI().app, workers=1)
    return ([Route("/metrics", endpoint=metrics)]
            if prod else []) + [Mount("/", app)]
예제 #14
0
 async def __call__(self, scope, receive, send):
     try:
         await self.app(scope, receive, send)
     except TypeError:
         app = WSGIMiddleware(self.app)
         await app(scope, receive, send)
예제 #15
0
import os
from starlette.applications import Starlette
from starlette.exceptions import ExceptionMiddleware
from starlette.middleware.wsgi import WSGIMiddleware
from starlette.routing import Router, Path, PathPrefix
import uvicorn
from wsgi import application
from .asgi_app import app as asgi_app

app = Router([
    PathPrefix("/v2", app=asgi_app),
    PathPrefix("", app=WSGIMiddleware(application)),
])
DEBUG = os.getenv("DJANGO_DEBUG", "True")

if DEBUG == "True":
    app = ExceptionMiddleware(app, debug=True)

if __name__ == "__main__":
    uvicorn.run(app, host="0.0.0.0", port=8000)
예제 #16
0
from fastapi import FastAPI
from starlette.middleware.wsgi import WSGIMiddleware
from modules.dashboard import app as dashboard_app
from modules.api import router
from starlette.responses import RedirectResponse
import uvicorn
from modules.db import db
import os
from fast_pony_crud import create_crud_routes

server = FastAPI()
server.include_router(router, prefix="/api", tags=["Device IO"])
create_crud_routes(db, server, "/db", os.environ.get("API_KEY"))

server.mount("/dash", WSGIMiddleware(dashboard_app.server))


@server.get("/", include_in_schema=False)
async def redirect():
    return RedirectResponse(url="/dash/")


if __name__ == "__main__":
    uvicorn.run(server, port=5000, host="0.0.0.0")
예제 #17
0
    return file_list


templates = Jinja2Templates(directory=TEMPLATES_DIRECTORY)

component_file_list = create_component_file_list()

template_options = {'tailwind': TAILWIND, 'quasar': QUASAR, 'quasar_version': QUASAR_VERSION, 'highcharts': HIGHCHARTS, 'aggrid': AGGRID, 'aggrid_enterprise': AGGRID_ENTERPRISE,
                    'static_name': STATIC_NAME, 'component_file_list': component_file_list, 'no_internet': NO_INTERNET}
logging.basicConfig(level=LOGGING_LEVEL, format='%(levelname)s %(module)s: %(message)s')


app = Starlette(debug=DEBUG)
app.mount(STATIC_ROUTE, StaticFiles(directory=STATIC_DIRECTORY), name=STATIC_NAME)
app.mount('/templates', StaticFiles(directory=current_dir + '/templates'), name='templates')
app.mount("/flask", WSGIMiddleware(flask_app.wsgi_app)) # added
app.mount("/dash", WSGIMiddleware(dash_app.server)) # added
app.add_middleware(GZipMiddleware)
if SSL_KEYFILE and SSL_CERTFILE:
    app.add_middleware(HTTPSRedirectMiddleware)


def initial_func(request):
    wp = WebPage()
    Div(text='JustPy says: Page not found', classes='inline-block text-5xl m-3 p-3 text-white bg-blue-600', a=wp)
    return wp

func_to_run = initial_func
startup_func = None