Exemplo n.º 1
0
    return _internal


app = Starlette(routes=[
    Route("/", endpoint=simple("home")),
    Route("/publications", endpoint=simple("publications")),
    Route("/about", endpoint=simple("about")),
    Route("/publications/{name:str}", endpoint=advanced("publications")),
    Route("/writeups", endpoint=simple("writeups")),
    Route("/partners", endpoint=simple("partners")),
    #  Route("/writeups/{name:str}", endpoint=advanced("writeups")),

    # redirects outside
    Route(
        "/asktoask", lambda _: RedirectResponse(
            "https://www.youtube.com/watch?v=53zkBvL4ZB4")),

    # trolls
    Route("/teapot",
          lambda _: PlainTextResponse("I'm a teapot", status_code=418)),
    Route(
        "/admin.php", lambda _: RedirectResponse(
            "https://www.youtube.com/watch?v=dQw4w9WgXcQ")),

    # static files
    Mount("/",
          app=StaticFiles(
              directory=path.join(path.dirname(__file__), "static")))
])

if __name__ == "__main__":
    if len(argv) == 2:
Exemplo n.º 2
0
    return templates.TemplateResponse('index.html', {'request': request})

async def emit(data, websocket: WebSocket):
    for socket in sockets:
        if socket != websocket:
            await socket.send_json(data)

class WS(WebSocketEndpoint):
    encoding = 'json'

    async def on_connect(self, websocket: WebSocket):
        print('Client connected')
        sockets.append(websocket)
        await websocket.accept()

    async def on_receive(self, websocket: WebSocket, data):
        print(data)
        await emit(data, websocket)

    async def on_disconnect(self, websocket: WebSocket, close_code):
        print('Client disconnected')
        sockets.remove(websocket)

routes = [
    Route('/', endpoint=homepage),
    Mount('/static', StaticFiles(directory='static'), name='static'),
    WebSocketRoute('/ws', WS)
]

app = Starlette(routes=routes)
Exemplo n.º 3
0
from starlette.responses import JSONResponse
from starlette.routing import Mount, Route, Router
from starlette.staticfiles import StaticFiles
from starlette.templating import Jinja2Templates

# uvicorn
import uvicorn

from joplin_api import JoplinApi

templates = Jinja2Templates(directory="templates")

# load configuration
settings = Config('.env')

main_app = Starlette()
main_app.debug = settings('JW_DEBUG', default=False)

joplin = JoplinApi(token=settings('JOPLIN_WEBCLIPPER_TOKEN'))


async def tags_to_string(my_tags):
    """

    :param my_tags:
    :return:
    """
    tags = ''
    for tag in my_tags:
        tags += tag
        if len(my_tags) > 1:
Exemplo n.º 4
0
from classes import GraphqlInterceptor
from context import LND, REDIS, GINO
from resolvers.schema import SCHEMA
from helpers.mixins import LoggerMixin

_logger = LoggerMixin()

middleware = [
    Middleware(
        CORSMiddleware,
        allow_origins=[
            "http://127.0.0.1:3000",
            "http://localhost:3000",
            "https://featherlight.app",
            "chrome-extension://iolgemahcebdonemnjepfomopcgikklg",
        ],
        allow_methods=["*"],
        allow_headers=["*"],
        allow_credentials=True,
    )
]

APP = Starlette(
    debug=True,
    on_startup=[LND.initialize, REDIS.initialize, GINO.initialize],
    on_shutdown=[LND.destroy, REDIS.destroy, GINO.destroy],
    middleware=middleware,
)

APP.mount("/graphql", GraphqlInterceptor(SCHEMA, debug=True))
Exemplo n.º 5
0
import os

from starlette.applications import Starlette
from starlette.graphql import GraphQLApp
from starlette.middleware.cors import CORSMiddleware

from .schema import schema

BASE_DIR = os.path.dirname(os.path.abspath(__file__))

app = Starlette(debug=True)
# Note: without the second two options here, the OPTIONS call from Vue-Apollo client will fail for some reason!
app.add_middleware(CORSMiddleware,
                   allow_origins=["*"],
                   allow_methods=["*"],
                   allow_headers=["*"])

app.add_route("/graph/", GraphQLApp(schema=schema))
Exemplo n.º 6
0
import os
import mongoengine
from starlette.applications import Starlette
from starlette.routing import Route
from starlette.middleware import Middleware
from starlette.middleware.cors import CORSMiddleware
from starlette.middleware.trustedhost import TrustedHostMiddleware
from starlette.graphql import GraphQLApp
from starlette.config import Config
from api.schema import schema

MONGO_URI = Config(os.path.join('config', '.mongo.env'))('MONGO_URI')

mongoengine.connect("tiny-graph", host=MONGO_URI, alias="default")

routes = [Route('/', GraphQLApp(schema=schema))]

middleware = [
    Middleware(TrustedHostMiddleware, allowed_hosts=['*']),
    Middleware(CORSMiddleware,
               allow_origins=['*'],
               allow_headers=['*'],
               allow_methods=['*'],
               allow_credentials=True)
]

app = Starlette(routes=routes, middleware=middleware)
Exemplo n.º 7
0
routes = [Mount('/static', StaticFiles(directory='app/static'), name='static')]

templates = Jinja2Templates(directory='app/templates')


async def startup():
    global conn
    print("connect")
    conn = await asyncpg.connect(
        "postgres://*****:*****@john.db.elephantsql.com:5432/mxqkomkc"
    )


app = Starlette(middleware=middleware,
                on_startup=[startup],
                routes=routes,
                debug=True)


@app.route("/")
async def proc_hom(request: Request):
    return templates.TemplateResponse('index.html', {'request': request})


@app.route("/villa", methods=['GET'])
async def proc_sen(request: Request):
    sentence: str = request.query_params['id']
    if not sentence:
        return JSONResponse({"error": "no id provided"}, status_code=400)
    else:
        try:
Exemplo n.º 8
0
def test_changelog_endpoint_with_file(tmpdir):
    changelog_file_path = os.path.join(tmpdir, "CHANGELOG.md")
    with open(changelog_file_path, "wt") as file:
        file.write("""# Changelog
All notable changes to this project will be documented in this file.

The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).

## [Unreleased]
### Changed
- Release note 1.
- Release note 2.

### Added
- Enhancement 1
- sub enhancement 1
- sub enhancement 2
- Enhancement 2

### Fixed
- Bug fix 1
- sub bug 1
- sub bug 2
- Bug fix 2

### Security
- Known issue 1
- Known issue 2

### Deprecated
- Deprecated feature 1
- Future removal 2

### Removed
- Deprecated feature 2
- Future removal 1

## [1.1.0] - 2018-05-31
### Changed
- Enhancement 1 (1.1.0)
- sub enhancement 1
- sub enhancement 2
- Enhancement 2 (1.1.0)

## [1.0.1] - 2018-05-31
### Fixed
- Bug fix 1 (1.0.1)
- sub bug 1
- sub bug 2
- Bug fix 2 (1.0.1)

## [1.0.0] - 2017-04-10
### Deprecated
- Known issue 1 (1.0.0)
- Known issue 2 (1.0.0)

[Unreleased]: https://github.test_url/test_project/compare/v1.1.0...HEAD
[1.1.0]: https://github.test_url/test_project/compare/v1.0.1...v1.1.0
[1.0.1]: https://github.test_url/test_project/compare/v1.0.0...v1.0.1
[1.0.0]: https://github.test_url/test_project/releases/tag/v1.0.0
""")

    app = Starlette()
    add_changelog_endpoint(app, changelog_file_path)
    with TestClient(app) as client:
        response = client.get("/changelog")
        assert response.status_code == 200
        assert response.json() == {
            "1.1.0": {
                "changed": [
                    "- Enhancement 1 (1.1.0)",
                    "- sub enhancement 1",
                    "- sub enhancement 2",
                    "- Enhancement 2 (1.1.0)",
                ],
                "release_date":
                "2018-05-31",
                "version":
                "1.1.0",
            },
            "1.0.1": {
                "fixed": [
                    "- Bug fix 1 (1.0.1)",
                    "- sub bug 1",
                    "- sub bug 2",
                    "- Bug fix 2 (1.0.1)",
                ],
                "release_date":
                "2018-05-31",
                "version":
                "1.0.1",
            },
            "1.0.0": {
                "deprecated":
                ["- Known issue 1 (1.0.0)", "- Known issue 2 (1.0.0)"],
                "release_date":
                "2017-04-10",
                "version":
                "1.0.0",
            },
        }
Exemplo n.º 9
0
import uvicorn

users = []


class User(typesystem.Schema):
    username = typesystem.String(max_length=100)
    is_admin = typesystem.Boolean(default=False)


async def list_users(request):
    return JSONResponse({"users": [dict(user) for user in users]})


async def add_user(request):
    data = await request.json()
    user, errors = User.validate_or_error(data)
    if errors:
        return JSONResponse(dict(errors), status_code=400)
    users.append(user)
    return JSONResponse(dict(user))


app = Starlette(routes=[
    Route('/', list_users, methods=["GET"]),
    Route('/', add_user, methods=["POST"]),
])

if __name__ == "__main__":
    uvicorn.run(app)
Exemplo n.º 10
0
from starlette.routing import Mount, Route
from starlette.middleware import Middleware
from starlette.middleware.cors import CORSMiddleware
import httpx
from os import path

from service_bus.schema import Query
from service_bus.config import STATIC_DIR

middleware = [
    Middleware(CORSMiddleware, allow_origins=['*'])
]
routes = [Route('/graphql', GraphQLApp(schema=graphene.Schema(query=Query)))]

# we create the ASGI for the app
app = Starlette(routes=routes, middleware=middleware)

# we create the ASGI for the frontend
frontend = Starlette(
    routes=[Mount("/", StaticFiles(directory=STATIC_DIR), name="app")])


@frontend.middleware("http")
async def default_page(request, call_next):
    response = await call_next(request)
    if response.status_code == 404:
        if STATIC_DIR:
            return FileResponse(path.join(STATIC_DIR, "index.html"))
        else:
            async with httpx.AsyncClient() as client:
                remote_resp = await client.get(
Exemplo n.º 11
0
def client(schema):
    app = Starlette()
    app.mount("/", GraphQLApp(schema))
    return TestClient(app)
Exemplo n.º 12
0
          endpoints.tree_artifacts,
          name="list_artifacts",
          methods=["GET"]),
    Route(URLS_RUNS_EVENTS,
          endpoints.get_run_events,
          name="events",
          methods=["GET"]),
    Route("/500", endpoints.error),
    Route("/healthz", endpoints.health),
]

middleware = []

if has_raven:  # pragma: nocover
    middleware += [Middleware(SentryAsgiMiddleware)]

if settings.CLIENT_CONFIG.verify_ssl:  # pragma: nocover
    middleware += [Middleware(HTTPSRedirectMiddleware)]

exception_handlers = {
    404: endpoints.not_found,
    500: endpoints.server_error,
}

app = Starlette(
    debug=settings.CLIENT_CONFIG.debug,
    routes=routes,
    middleware=middleware,
    exception_handlers=exception_handlers,
)
Exemplo n.º 13
0
from starlette.routing import Route

from app import settings

from . import endpoints

database = Database(settings.DATABASE_URL, force_rollback=settings.TESTING)

routes = [
    Route('/', endpoints.Home),
    Route('/urls', endpoints.Urls),
    Route('/urls/{url_id}', endpoints.Url),
]


async def on_startup():
    app.database = database
    await app.database.connect()


async def on_shutdown():
    await app.database.disconnect()


app = Starlette(
    routes=routes,
    debug=settings.DEBUG,
    on_startup=[on_startup],
    on_shutdown=[on_shutdown],
)
Exemplo n.º 14
0
            algorithm='HS256')

        return RedirectResponse("https://healthy.adds.md/login/" +
                                encoded_jwt.decode("utf-8"))


app = Starlette(debug=True,
                routes=[
                    Route('/login/{provider}', endpoint=login),
                    Route('/auth/{provider}', endpoint=auth),
                ],
                on_startup=[database.connect],
                on_shutdown=[database.disconnect],
                middleware=[
                    Middleware(CORSMiddleware,
                               allow_origins=['*'],
                               allow_methods=['*'],
                               allow_headers=['*'],
                               allow_credentials=True),
                    Middleware(SessionMiddleware,
                               secret_key=config('SESSION_SECRET')),
                    Middleware(AuthenticationMiddleware,
                               backend=JWTAuthenticationBackend(
                                   secret_key=config("JWT_KEY"), prefix='JWT'))
                ])


@app.route("/profile", ["GET"])
@requires('authenticated')
async def profile(request):
    user = await database.fetch_one(
Exemplo n.º 15
0
from starlette.templating import Jinja2Templates

from resume_builder.config import DEBUG, RESUMES_PATH, TEMPLATES_PATH
from resume_builder.exceptions import ResumeDoesNotExist, ResumeInvalidYaml
from resume_builder.utils import load_resume, template_exists

routes = [
    Mount("/static/resumes",
          app=StaticFiles(directory=RESUMES_PATH),
          name="resumes"),
    Mount("/static/templates",
          app=StaticFiles(directory=TEMPLATES_PATH),
          name="templates"),
]

app = Starlette(routes=routes, debug=DEBUG)
templates = Jinja2Templates(directory=TEMPLATES_PATH)


@app.route("/{resume}", methods=("GET", ))
def view_resume(request):
    resume = request.path_params["resume"]
    try:
        context = load_resume(resume)
    except ResumeDoesNotExist:
        raise HTTPException(404, "Not found")
    except ResumeInvalidYaml:
        raise HTTPException(500, "YAML file error")
    try:
        template = context.pop("template")
    except KeyError:
Exemplo n.º 16
0
#!/usr/bin/env python3
from pathlib import Path
import secrets
import asyncio
import subprocess

from starlette.applications import Starlette
from starlette.responses import HTMLResponse
from starlette.background import BackgroundTask

import config
import powser

server = Starlette(debug=config.debug)
powser = powser.Powser(db_path='./pow/pow.sqlite3',
                       difficulty=config.difficulty)


async def remove_sandbox(sandbox_name):
    await asyncio.sleep(config.recycle_t)
    subprocess.run(['sudo', '/usr/bin/remove_sandbox.sh', sandbox_name])


def create_sandbox(sandbox_name):
    subprocess.run(['sudo', '/usr/bin/create_sandbox.sh', sandbox_name])


@server.route('/')
async def index(request):
    ip = request.headers['X-Real-IP']
    answer = request.query_params.get('answer')
Exemplo n.º 17
0
import json
from starlette.applications import Starlette
from starlette.requests import Request
from starlette.responses import JSONResponse, PlainTextResponse, Response
from typing import Tuple, Optional

import arrow
import uvicorn

from .channel_stats import get_stats
from . import config
from .lock import get_lock, Lock, remove_lock, set_lock
from .slackbot import channel_message, react_message

app = Starlette(debug=False)

client = config.get_redis()


def get_request_duration(params: list) -> int:
    """
    return timestamp when the lock will expiry
    """
    try:
        duration = abs(int(params[0]))
    except Exception:
        duration = config.LOCK_DURATION

    return arrow.now().shift(minutes=+duration).timestamp

Exemplo n.º 18
0
@router.route("/post", methods=["POST"])
async def post(request: HTTPConnection):
    form = await request.form()
    form = PostForm(form)

    name = form.name.data
    message = form.message.data

    posts = request.session.get("posts")
    if posts is None:
        posts = []
        request.session["posts"] = posts

    posts.append((name, message))

    return templates.TemplateResponse(
        "main.j2",
        {
            "request": request,
            "form": form,
            "posts": posts,
            "post_create": request.url_for("post"),
        },
    )


app = Starlette(routes=[Mount("/ssti", app=router)])

app.add_middleware(SessionMiddleware, secret_key="doesntmatter")
Exemplo n.º 19
0
    405: method_not_allowed,
    HTTPException: http_exception,
}

middleware = [
    Middleware(TrustedHostMiddleware,
               allowed_hosts=["testserver", "*.example.org"])
]

app = Starlette(
    routes=[
        Route("/func", endpoint=func_homepage),
        Route("/async", endpoint=async_homepage),
        Route("/class", endpoint=Homepage),
        Route("/500", endpoint=runtime_error),
        WebSocketRoute("/ws", endpoint=websocket_endpoint),
        Mount("/users", app=users),
        Host("{subdomain}.example.org", app=subdomain),
    ],
    exception_handlers=exception_handlers,
    middleware=middleware,
)


@pytest.fixture
def client(test_client_factory):
    with test_client_factory(app) as client:
        yield client


def test_url_path_for():
Exemplo n.º 20
0
from starlette.responses import JSONResponse
from starlette.routing import Route
from starlette.templating import Jinja2Templates
from starlette.routing import Mount
from starlette.staticfiles import StaticFiles
from api.api import api_routes
from runner import Runner

r = Runner(b'FLAG_[\w]+')

templates = Jinja2Templates(directory='website/templates')


async def homepage(request):
    return templates.TemplateResponse('index.html', {'request': request})


async def flags(request):
    return templates.TemplateResponse('flags.html', {'request': request})


website_routes = [
    Mount('/static', app=StaticFiles(directory='website/static')),
    Route("/", endpoint=homepage),
    Route("/flags", endpoint=flags)
]

app = Starlette(debug=True, routes=api_routes + website_routes)

r.do_round()
Exemplo n.º 21
0
def feature_with_count(feature, count):
    feature['results'] = count[feature['properties']['wd18cd']]
    return feature


def wards_with_count():
    geojson = relevant_wards_geojson()
    wards_count = count_by_wards()
    features = list(
        map(lambda x: feature_with_count(x, wards_count),
            geojson['features']))  # noqa: E501
    geojson['features'] = features
    return geojson


app = Starlette(debug=DEBUG)
app.mount('/static', StaticFiles(directory='static'), name='static')


@app.route('/')
async def index(request):
    return FileResponse('static/dev.html')


@app.route('/api/wards')
async def list_wards(request):
    return JSONResponse(wards_with_count())


if __name__ == '__main__':
    if len(sys.argv) > 1 and sys.argv[1] == 'generate':
Exemplo n.º 22
0
        x = x + 1
    return f"Done counting to {x}"


async def processing(request):
    result = await _process_request_async()
    return PlainTextResponse(result)


async def processing_fixed(request):
    loop = asyncio.get_event_loop()
    result = await loop.run_in_executor(None, _process_request_sync)
    return PlainTextResponse(result)


async def processing_busy(request):
    loop = asyncio.get_event_loop()
    result = await loop.run_in_executor(None, _process_request_sync_busy)
    return PlainTextResponse(result)


app = Starlette(
    debug=True,
    routes=[
        Route("/health", healthcheck),
        Route("/processing", processing),
        Route("/processing_fixed", processing_fixed),
        Route("/processing_busy", processing_busy),
    ],
)
Exemplo n.º 23
0
]


async def on_startup():
    pass
    # global trader_database
    # trader_database = get_client(asyncio.get_running_loop()).trader
    # client = get_client(asyncio.get_running_loop())
    # app.__dict__['mongo'] = client
    # logger = Logger(name='coin_gecko', client=client, database='logs', collection='trader', log_to_console=True)
    # await logger.info('Set all loops to stopped')
    # await logger.info('Started tasks')


def on_shutdown():
    pass
    # coin_gecko = CoinGecko.object().first()
    # coin_gecko.loop_state = 'stopped'
    # coin_gecko.save()


app = Starlette(debug=True,
                routes=routes,
                middleware=middleware,
                on_startup=[on_startup],
                on_shutdown=[on_shutdown])

print('started')

if __name__ == '__main__':
    uvicorn.run(app, host="127.0.0.1", port=8003)
Exemplo n.º 24
0
from starlette.applications import Starlette

from learn.settings.routes import routes

app = Starlette(debug=True, routes=routes)
Exemplo n.º 25
0
from starlette.applications import Starlette
from starlette.routing import Route
from strawberry.asgi import GraphQL

from schema import schema

app = Starlette(
    debug=True,
    routes=[
        Route("/graphql", GraphQL(schema)),
    ],
)
Exemplo n.º 26
0
    return JSONResponse({"error": err}, status_code=code)


async def joke_request(request):
    category = request.path_params.get("category", "oneliner")
    if category not in JOKES or not JOKES[category]:
        return error(f"category {category} not found or empty", 404)
    return JSONResponse({
        "category": category,
        "content": random.choice(JOKES[category])["text"]
    })


async def categories_request(request):
    categories = list(JOKES.keys())
    del categories[0]
    return JSONResponse(categories)


app = Starlette(
    debug=True,
    routes=[
        Route("/", joke_request),
        Route("/categories", categories_request),
        Route("/{category}", joke_request),
    ],
)

if __name__ == "__main__":
    uvicorn.run("index:app", host="0.0.0.0", port=8081, log_level="info")
Exemplo n.º 27
0
from .config import STATIC_DIR
from .database import SessionLocal
from .extensions import configure_extensions
from .logging import configure_logging
from .metrics import provider as metric_provider

log = logging.getLogger(__name__)

# we configure the logging level and format
configure_logging()

# we configure the extensions such as Sentry
configure_extensions()

# we create the ASGI for the app
app = Starlette()

# we create the ASGI for the frontend
frontend = Starlette()

# we create the Web API framework
api = FastAPI(docs_url=None, redoc_url=None, openapi_url=None)


def get_path_template(request: Request) -> str:
    if hasattr(request, "path"):
        return ",".join(request.path.split("/")[1:4])
    return ".".join(request.url.path.split("/")[1:4])


@frontend.middleware("http")
Exemplo n.º 28
0
def get_app():
    app = Starlette(routes=routes)
    db.init_app(app)
    return app
Exemplo n.º 29
0
import uvicorn
from fastai import *
from fastai.vision import *
from io import BytesIO
from starlette.applications import Starlette
from starlette.middleware.cors import CORSMiddleware
from starlette.responses import HTMLResponse, JSONResponse
from starlette.staticfiles import StaticFiles

export_file_url = 'https://drive.google.com/uc?export=download&id=1FTGV-5eOBrdGDUv2bh2x2o-zoYsJ0UiA'
export_file_name = 'export.pkl'

classes = ['cardboard', 'glass', 'metal', 'paper', 'plastic', 'trash']
path = Path(__file__).parent

app = Starlette()
app.add_middleware(CORSMiddleware,
                   allow_origins=['*'],
                   allow_headers=['X-Requested-With', 'Content-Type'])
app.mount('/static', StaticFiles(directory='app/static'))


async def download_file(url, dest):
    if dest.exists(): return
    async with aiohttp.ClientSession() as session:
        async with session.get(url) as response:
            data = await response.read()
            with open(dest, 'wb') as f:
                f.write(data)

Exemplo n.º 30
0
        "Number of bankrupt investers": user_bk
    })),background=task)

'''
globals
'''
async def setup():
    await db.connect()
    await db.init_user_table()
    await db.create_user(config.ponzi_uid, config.ponzi_init_balance)
    await db.init_stat_table()
    await db.create_stat()

db = Database('sqlite:///' + config.db_path)
powser = powser.Powser(
    db_path=config.powser_path,
    difficulty=config.powser_diffculty,
    min_refresh_time=config.powser_min_refresh_time,
    default_expired_time=config.powser_default_expired_time
)

app = Starlette(
    debug=config.debug,
    routes=[
        Route('/', endpoint=index, methods=['GET'], name='index'),
        Route('/{uid:str}', endpoint=home, methods=['GET', 'POST'], name='home'),
    ],
    on_startup=[setup],
    on_shutdown=[db.disconnect]
)