示例#1
0
from starlette.applications import Starlette
from starlette.endpoints import HTTPEndpoint
from starlette.routing import Mount, Route, WebSocketRoute
from starlette.schemas import SchemaGenerator

schemas = SchemaGenerator(
    {"openapi": "3.0.0", "info": {"title": "Example API", "version": "1.0"}}
)


def ws(session):
    """ws"""
    pass  # pragma: no cover


def list_users(request):
    """
    responses:
      200:
        description: A list of users.
        examples:
          [{"username": "******"}, {"username": "******"}]
    """
    pass  # pragma: no cover


def create_user(request):
    """
    responses:
      200:
        description: A user.
示例#2
0
schemas = SchemaGenerator({
    "openapi": "3.0.0",
    "info": {
        "title": "RSS XML URL Substitution API",
        "version": "1.0"
    },
    "paths": {
        "/api/": {
            "get": {
                "summary":
                "substitue from remote xml file",
                "parameters": [
                    {
                        "in": "query",
                        "name": "rss",
                        "required": True,
                        "schema": {
                            "type": str
                        },
                        "description": "remote xml file url"
                    },
                    {
                        "in":
                        "query",
                        "name":
                        "tags",
                        "schema": {
                            "type": str
                        },
                        "description":
                        "tags whose src/herf attr need to be replaced, default: `tags=img|a`"
                    },
                ],
                "responses": {
                    200: {
                        "description": "Success",
                    },
                    400: {
                        "description":
                        "Failed, short of query parameter `rss`",
                    }
                }
            },
            "post": {
                "summary": "substitue from local xml file",
                "requestBody": "string representation of an XML element. ",
                "required": True,
                "content": "application/xml",
                "responses": {
                    200: {
                        "description": "Success"
                    }
                }
            },
        },
    },
})
示例#3
0
from starlette.requests import Request
from starlette.responses import JSONResponse
from starlette.routing import Route
from starlette.endpoints import HTTPEndpoint
from starlette.schemas import SchemaGenerator

from v1 import inputs, models


schemas = SchemaGenerator(
    {"openapi": "3.0.0", "info": {"title": "Routes", "version": "1.0"}}
)


class RouteCreateView(HTTPEndpoint):
    async def put(cls, request):
        data = inputs.CreateUserRouteInput(**await request.json())

        # gathering does not work with asyncpg pool
        created_route = await models.UserRoutes.create(
            data.user_id, data.route_id)
        await models.UserStats.add_user_route(
            data.user_id, data.route_length)

        return JSONResponse({'id': created_route[0]['id']})


class UsersStatsView(HTTPEndpoint):
    async def get(cls, request: Request):
        limit = int(request.query_params.get('limit', 15))
        offset = int(request.query_params.get('offset', 0))
示例#4
0
    config,
)

# Constants
OAUTH = OAuth()
OAUTH.register(
    name='google',
    client_id=config.GOOGLE_OAUTH_CLIENT_ID_SERVER,
    client_secret=config.GOOGLE_OAUTH_SECRET_SERVER,
    server_metadata_url=(
        'https://accounts.google.com/.well-known/openid-configuration'),
    client_kwargs={'scope': 'email'},
)
SCHEMA = SchemaGenerator({
    "openapi": "3.0.0",
    "info": {
        "title": "Four Shells",
    },
})


async def on_shutdown() -> None:
    """Server shutdown script."""


async def on_startup() -> None:
    """Server startup script."""


def cachipfs(request: Request) -> Response:
    return config.TPL.TemplateResponse(
        'react.html', {
示例#5
0
from fastai.vision import *

import factory
from utilities import *

# Define the valid classifiers and create the relative models.
global VALID_CLASSIFIERS
VALID_CLASSIFIERS = {
    "RNN":factory.create_rnn(),
    "CNN":factory.create_cnn(),
    "SVM":factory.create_svm(),
    "RF" :factory.create_rf(),
    "KNN":factory.create_knn()
}

schemas = SchemaGenerator({"openapi": "3.0.0", "info": {"title": "ML classifier API", "version": "0.1"}})
app = Starlette()

@app.route("/api/v1/classify/digits", methods=["POST"])
async def classify_numbers(request):
    """
    responses:
      200:
        description: Returns JSON ordered list of class predictions for input image.
        parameters:
          ["classifier": "RNN|CNN|SVM|RF|KNN", "url", "b64"]
        example_requests:
          [[{"classifier": "RNN"}, {"url": "http://datawrangling.s3.amazonaws.com/sample_digit.png"}], or,
          [{"classifier": "RNN"}, {"b64": "AAAN4AAADfCAYAAACZO20SAAAABmJLR0QA/wD/AP+..."}]]
        example_response: |
          {"predictions": [["4", 0.9999681711196899], ["6", 2.6835603421204723e-05], ["1", 2.648422423590091e-06], ["7", 1.2625563385881833e-06], ["2", 4.2422348656145914e-07], ["9", 2.9029823167547875e-07], ["0", 1.704291605619801e-07], ["8", 1.5085298343819886e-07], ["3", 3.132079839929247e-08], ["5", 4.936829611779103e-09]]}  
示例#6
0
from starlette.applications import Starlette
from starlette.schemas import SchemaGenerator
from starlette.responses import JSONResponse
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from sqlalchemy import Column, String, BigInteger, Integer
from sqlalchemy.ext.declarative import declarative_base
import sqlalchemy
import requests
import settings
import uvicorn

schemas = SchemaGenerator({
    "openapi": "3.0.0",
    "info": {
        "title": "Tweeter Test App",
        "version": "1.0"
    }
})
app = Starlette()

app.debug = settings.DEBUG

base = declarative_base()
db_string = settings.DATABASE_URL
db = create_engine(db_string)


class ResultsTwitter(base):

    __tablename__ = 'results_tweet'
示例#7
0
import logging
from typing import Dict, List, Tuple

from starlette.middleware import Middleware
from starlette.middleware.cors import CORSMiddleware
from starlette.requests import Request
from starlette.routing import Route
from starlette.responses import JSONResponse, Response, PlainTextResponse
from api.controllers import get_top_users, get_top_hashtags, tweet_amount, get_all_tweets
from starlette.schemas import SchemaGenerator

schemas = SchemaGenerator({
    "openapi": "3.0.0",
    "info": {
        "title": "Sapient twitor API",
        "version": "0.0.0.1"
    }
})


async def tweets(request: Request) -> Response:
    """Tweets.

    ---
    description:
        Return last 500 tweets.
        Optionally use `offset` query param.
    tags:
    - All unique tweets
    produces:
    - application/json
示例#8
0
base_typesystem_api = Router(
    [
        Route("/authors", endpoint=base_typesystem.Authors, methods=["GET", "POST"]),
        Route(
            "/authors/{id}",
            endpoint=base_typesystem.Author,
            methods=["GET", "PUT", "DELETE"],
        ),
    ]
)


base_pydantic_schemas = SchemaGenerator(
    {
        "openapi": "3.0.0",
        "info": {"title": "Example API with Pydantic schemas", "version": "0.1.0"},
    }
)

app = Starlette()

app.mount("/base_pydantic_api", app=base_pydantic_api)
app.mount("/base_typesystem_api", app=base_typesystem_api)


@app.on_event("startup")
async def startup() -> None:
    """
    Sets environment vars and creates db connections on the server start up.
    """
    await database.connect()
示例#9
0
def openapi_schema(request: Request) -> Response:
    path = Path(__file__).parent / 'openapi.yml'
    with path.open() as file:
        schema = SchemaGenerator(yaml.safe_load(file))

    return schema.OpenAPIResponse(request)
示例#10
0
schemas = SchemaGenerator({
    "openapi":
    "3.0.0",
    "info": {
        "title": "App",
        "version": "1.0"
    },
    "servers": [{
        "url": "http://localhost:{port}",
        "variables": {
            "port": {
                "default": "8000"
            }
        }
    }],
    "schemas": {
        "Classify": {
            "type": "object",
            "properties": {
                "classified": {
                    "type": "array",
                    "items": {
                        "type": "string"
                    }
                },
                "probability": {
                    "type": "array",
                    "items": {
                        "type": "integer"
                    }
                }
            }
        },
        "ErrorMessage": {
            "type": "object",
            "properties": {
                "message": {
                    "type": "string"
                }
            }
        },
        "Errors": {
            "type": "array",
            "items": {
                "$ref": "#/schemas/ErrorMessage"
            }
        },
        "ImageData": {
            "type": "object",
            "properties": {
                "image_data": {
                    "type": "string"
                }
            }
        }
    }
})