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))
from io import BytesIO from PIL import Image from tensorflow.keras.models import load_model import cv2 import pathlib import numpy as np export_file_url = 'https://www.dropbox.com/s/kupg33j3ygn4o0r/covid-19_2x2.model?dl=1' export_file_name = 'covid-19_2x2.model' classes = ['Infected', 'Normal'] path = pathlib.Path().parent.absolute() 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) async def setup_learner(): await download_file(export_file_url, str(path/export_file_name)) try: learn = load_model(str(path/export_file_name)) return learn
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))
import os from starlette.applications import Starlette from starlette.datastructures import Headers from starlette.endpoints import HTTPEndpoint from starlette.exceptions import HTTPException from starlette.middleware.trustedhost import TrustedHostMiddleware from starlette.responses import JSONResponse, PlainTextResponse from starlette.routing import Host, Mount, Route, Router, WebSocketRoute from starlette.staticfiles import StaticFiles from starlette.testclient import TestClient app = Starlette() app.add_middleware(TrustedHostMiddleware, allowed_hosts=["testserver", "*.example.org"]) @app.exception_handler(500) async def error_500(request, exc): return JSONResponse({"detail": "Server Error"}, status_code=500) @app.exception_handler(405) async def method_not_allowed(request, exc): return JSONResponse({"detail": "Custom message"}, status_code=405) @app.exception_handler(HTTPException) async def http_exception(request, exc): return JSONResponse({"detail": exc.detail}, status_code=exc.status_code)
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():
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':
@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")
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
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)
#!/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')
from starlette.applications import Starlette from starlette.graphql import GraphQLApp from starlette.middleware.authentication import AuthenticationMiddleware from graphql.execution.executors.asyncio import AsyncioExecutor from .models import schema from .utils.authentication import JWTAuthenticationBackend from config.settings import ( DEBUG, DATABASE_URL, SECRET_KEY, JWT_ALGORITHM, DatabaseMiddleware, ) app = Starlette() app.debug = DEBUG app.add_middleware( AuthenticationMiddleware, backend=JWTAuthenticationBackend(SECRET_KEY, JWT_ALGORITHM), ) app.add_middleware(DatabaseMiddleware, database_url=DATABASE_URL) app.add_route("/query", GraphQLApp(schema=schema, executor=AsyncioExecutor()))
#! python3 import pathlib from starlette.applications import Starlette from starlette.staticfiles import StaticFiles from starlette.templating import Jinja2Templates from .config import init_db, global_configs from .loggers import logger static_dir = pathlib.Path(__file__).parent / 'static' templates_dir = pathlib.Path(__file__).parent / 'templates' app = Starlette() app.mount('/static', StaticFiles(directory=str(static_dir)), name='static') app.config = global_configs app.logger = logger app.db = init_db() app.templates = Jinja2Templates(directory=str(templates_dir)) @app.on_event('startup') async def _ensure_article_table_exists(): await app.db._ensure_article_table_exists()
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", }, }
from starlette.templating import Jinja2Templates import session from api import api PORT = os.getenv('PORT', '8081') STATIC = os.path.join(os.getcwd(), 'static') USE_MOCKS = bool(os.getenv('USE_MOCKS', False)) CURRENT_DIR = os.path.abspath(os.path.dirname(__file__)) logging.basicConfig(level=logging.DEBUG) templates = Jinja2Templates(directory='templates') LOG = logging.getLogger('application') app = Starlette(debug=True) app.mount('/static', StaticFiles(directory='static'), name='static') @app.route('/dashboard') async def dashboard(request): LOG.info(request.headers) if 'xhr' in request.query_params: results = await api.call( api.load_query('dashboard'), variables={'region': 'us-east'}, request=request ) resp = { 'errors': cannula.format_errors(results.errors),
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()
def client(schema): app = Starlette() app.mount("/", GraphQLApp(schema)) return TestClient(app)
import os import sys import traceback import time import aiohttp import asyncio import uvicorn from starlette.applications import Starlette from starlette.middleware.cors import CORSMiddleware from starlette.responses import JSONResponse import json from fastai_inference import Inferencer app = Starlette() app.add_middleware(CORSMiddleware, allow_origins=['*'], allow_headers=['X-Requested-With', 'Content-Type']) def setup_learner(): inf = Inferencer('model.pkl', input_type=None) return inf inf = setup_learner() @app.route('/analyze:predict', methods=['POST']) async def analyze(request):
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)
from starlette.applications import Starlette from starlette.responses import PlainTextResponse from caffeine.common.settings import Settings from caffeine.rest.bootstrap import RestBootstrap app = Starlette() settings = Settings() settings.read_env() web = RestBootstrap(app, settings) app.add_event_handler("startup", web.init) app.add_event_handler("shutdown", web.shutdown) @app.route("/") async def homepage(request): return PlainTextResponse("This is messeeks, look at me!") if __name__ == "__main__": import uvicorn uvicorn.run(app, host="localhost", port=8000)
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:
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), ], )
def test_not_active(): app = Starlette() app.add_middleware(SessionMiddleware, secret_key="example") app.add_middleware(AuthenticationMiddleware, backend=InactiveBackend()) app.add_route("/", homepage) app.add_route("/dashboard", dashboard) app.add_route("/admin", admin) app.add_route("/unauthenticated", unauthenticated) with TestClient(app) as client: response = client.get("/") assert response.status_code == 200 assert response.json() == {"authenticated": False, "user": ""} response = client.get("/dashboard") assert response.status_code == 403 response = client.get("/admin") assert response.status_code == 200 assert response.json() == {"authenticated": False, "user": ""} response = client.get("/unauthenticated") assert response.status_code == 200 assert response.json() == {"authenticated": False, "user": ""}
from starlette.applications import Starlette from learn.settings.routes import routes app = Starlette(debug=True, routes=routes)
] 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)
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")
# star_app.py import ssl import uvicorn from starlette.applications import Starlette from starlette.responses import JSONResponse app = Starlette() @app.route("/") async def homepage(request): return JSONResponse({"hello": "world"}) if __name__ == "__main__": uvicorn.run( app, host="0.0.0.0", port=8000, ssl_version=ssl.PROTOCOL_SSLv23, cert_reqs=ssl.CERT_OPTIONAL, ssl_certfile= "/home/buho/example.com+4.pem", # Note that the generated certificates ssl_keyfile="/home/buho/example.com+4-key.pem", # are used here )
def get_app(): app = Starlette(routes=routes) db.init_app(app) return app
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)), ], )
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:
def init(): app = Starlette() @app.on_event("startup") async def async_setup(): await pg_init() @app.exception_handler(JSONDecodeError) async def bad_json(request, exc): return JSONResponse({'reason': 'invalid json', 'details': str(exc)}, status_code=400) @app.exception_handler(InsufficientPermissionsError) async def handle_permissions(request, exc): return JSONResponse({'reason': 'you are not authorized to do that dave'}, status_code=403) # auth stuff auth = GoogleAuthBackend(GOOGLE_ID, GOOGLE_SECRET, GOOGLE_ORG) app.add_middleware(AuthenticationMiddleware, backend=auth, on_error=auth.on_error) app.add_middleware(SessionMiddleware, session_cookie=COOKIE_NAME, secret_key=COOKIE_KEY, https_only=not LOCAL_DEV, max_age=2 * 24 * 60 * 60) # 2 days # sentry stuff sentry_sdk.init(dsn=SENTRY_URL, environment=ENV_NAME) app.add_middleware(SentryMiddleware) async def index_html(request): static = pathlib.Path('tmeister/static/index.html') return HTMLResponse(static.read_text()) app.add_route('/api/envs/{name}/toggles', toggles.get_toggle_states_for_env, methods=['GET']) app.add_route('/api/toggles', toggles.get_all_toggle_states, methods=['GET']) app.add_route('/api/toggles', toggles.set_toggle_state, methods=['PATCH']) app.add_route('/api/features', features.get_features) app.add_route('/api/features', features.create_feature, methods=['POST']) app.add_route('/api/features/{name}', features.delete_feature, methods=['DELETE']) app.add_route('/api/envs', environments.get_envs) app.add_route('/api/envs', environments.add_env, methods=['POST']) app.add_route('/api/envs/{name}', environments.delete_env, methods=['DELETE']) app.add_route('/api/auditlog', auditing.get_audit_events) app.add_route('/heartbeat', health.get_health) app.add_route('/', index_html) app.mount('/', app=StaticFiles(directory='tmeister/static'), name='static') return app
sdl = load_schema_from_path(Path(__file__).parents[2] / "graphql" / "schema") schema = make_executable_schema(sdl, query, mutation, *scalars.resolvers) path = prefect_server.config.services.graphql.path or "/" if not path.endswith("/"): path += "/" # The interaction of how Starlette mounts the GraphQL app appears to result in # 404's when the path doesn't end in a trailing slash. This means GraphQL queries # must have a trailing slash if not path.endswith("/"): raise ValueError("GraphQL path must end with '/'") app = Starlette() app.router.redirect_slashes = False app.mount( path, GraphQL( schema, debug=prefect_server.config.services.graphql.debug, extensions=[extensions.PrefectHeader], ), ) app_version = os.environ.get("PREFECT_SERVER_VERSION") or "UNKNOWN" @app.route("/health", methods=["GET"]) def health(request: Request) -> JSONResponse:
from starlette.responses import HTMLResponse, JSONResponse from starlette.staticfiles import StaticFiles from starlette.middleware.cors import CORSMiddleware import uvicorn, aiohttp, asyncio from io import BytesIO from fastai.vision import ImageDataBunch, create_cnn, open_image, get_transforms, imagenet_stats, models from fastai import Path model_file_url = 'https://www.dropbox.com/s/y4kl2gv1akv7y4i/stage-2.pth?raw=1' model_file_name = 'model' classes = ['black', 'grizzly', 'teddys'] 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) async def setup_learner(): await download_file(model_file_url, path/'models'/f'{model_file_name}.pth') data_bunch = ImageDataBunch.single_from_classes(path, classes, tfms=get_transforms(), size=224).normalize(imagenet_stats) learn = create_cnn(data_bunch, models.resnet34, pretrained=False)
async def subscribe_raiseError1(root, info): raise ValueError async def subscribe_raiseError2(root, info): yield 0 raise ValueError @pytest.fixture def schema(): return graphene.Schema(query=Query, mutation=Mutation, subscription=Subscription) @pytest.fixture def client(schema): app = Starlette() app.mount("/", GraphQLApp(schema)) return TestClient(app) app = Starlette() app.mount( "/", GraphQLApp( graphene.Schema(query=Query, mutation=Mutation, subscription=Subscription)), )