Ejemplo n.º 1
0
from rio_tiler.utils import render
from rio_tiler.colormap import get_colormap
from rio_tiler.profiles import img_profiles

from starlette.requests import Request
from starlette.responses import Response, HTMLResponse
from starlette.templating import Jinja2Templates
from starlette.middleware.cors import CORSMiddleware
from starlette.middleware.gzip import GZipMiddleware

from fastapi import FastAPI, Query
import uvicorn

dir = os.path.dirname(__file__)
templates = Jinja2Templates(directory=f"{dir}/templates")

_postprocess_tile = partial(run_in_threadpool, postprocess_tile)
_render = partial(run_in_threadpool, render)


class viz(object):
    """Creates a very minimal slippy map tile server using fastAPI + Uvicorn."""
    def __init__(
        self,
        raster,
        token: str = None,
        port: int = 8080,
        host: str = "127.0.0.1",
        style: str = "satellite",
    ):
Ejemplo n.º 2
0
import os
from urllib.parse import urlencode

import httpbin
from asgiref.wsgi import WsgiToAsgi
from starlette.applications import Starlette
from starlette.responses import PlainTextResponse, Response
from starlette.staticfiles import StaticFiles
from starlette.templating import Jinja2Templates
from starlette.websockets import WebSocketDisconnect

ROOT = os.path.dirname(__file__)
LOGS_PATH = os.path.join(ROOT, "htdocs", "logs")
QVIS_URL = "https://qvis.edm.uhasselt.be/"

templates = Jinja2Templates(directory=os.path.join(ROOT, "templates"))
app = Starlette()

# list of all connections established over the runtime
list_of_connections = []

@app.websocket_route("/ws")
async def ws(websocket):
    """
    WebSocket echo endpoint.
    """
    if "chat" in websocket.scope["subprotocols"]:
        subprotocol = "chat"
    else:
        subprotocol = None
    await websocket.accept(subprotocol=subprotocol)
Ejemplo n.º 3
0
from typing import Any, Dict

from covid_api import version
from covid_api.api.api_v1.api import api_router
from covid_api.core import config
from covid_api.db.memcache import CacheLayer

from fastapi import FastAPI

from starlette.middleware.cors import CORSMiddleware
from starlette.middleware.gzip import GZipMiddleware
from starlette.requests import Request
from starlette.responses import HTMLResponse
from starlette.templating import Jinja2Templates

templates = Jinja2Templates(directory="covid_api/templates")

if config.MEMCACHE_HOST and not config.DISABLE_CACHE:
    kwargs: Dict[str, Any] = {
        k: v
        for k, v in zip(
            ["port", "user", "password"],
            [
                config.MEMCACHE_PORT, config.MEMCACHE_USERNAME,
                config.MEMCACHE_PASSWORD
            ],
        ) if v
    }
    cache = CacheLayer(config.MEMCACHE_HOST, **kwargs)
else:
    cache = None
Ejemplo n.º 4
0
from starlette.requests import Request
from starlette.templating import Jinja2Templates
from services.report_service import get_reports

import fastapi
router = fastapi.APIRouter()
templates = Jinja2Templates('templates')


@router.get('/', include_in_schema=False)
async def index(request: Request):
    events = await get_reports()
    data = {'request': request, 'events': events}
    return templates.TemplateResponse('home/index.html', data)


@router.get('/favicon.ico', include_in_schema=False)
def favicon():
    return fastapi.responses.RedirectResponse(url='/static/img/favicon.ico')
Ejemplo n.º 5
0
from pathlib import Path

from aopi_index_builder import get_context
from starlette.templating import Jinja2Templates

context = get_context()
plugin_dir = Path(__file__).parent
templates_dir = plugin_dir / "templates"
templates = Jinja2Templates(directory=templates_dir)
Ejemplo n.º 6
0
Archivo: app.py Proyecto: pgtuk/la_task
import asyncio
import os

from starlette.applications import Starlette
from starlette.templating import Jinja2Templates
import uvicorn

import processor
from video import Video


app = Starlette()
templates = Jinja2Templates(directory='src/templates')
VIDEOS_DIR = 'videos'


@app.route('/')
def homepage(request):

    return templates.TemplateResponse(
        'index.html',
        {
            'request': request,
            'videos': os.listdir(VIDEOS_DIR)
        }
    )


@app.websocket_route("/ws")
async def video_stream(ws):
Ejemplo n.º 7
0
import fastai
from fastai.vision import *
from fastai.callbacks import *
from fastai.utils.mem import *

import asyncio, aiohttp

from starlette.applications import Starlette
from starlette.responses import HTMLResponse
from starlette.staticfiles import StaticFiles
from starlette.middleware.cors import CORSMiddleware
from starlette.templating import Jinja2Templates

## INITIALIZING SERVER

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

## INITIALIZING UNET

path = Path(__file__).parent  #app/

export_file_url = 'https://www.dropbox.com/s/gkjx36g2sbd0x6v/export.pkl?raw=1'
export_file_name = 'export.pkl'


async def download_file(url, dest):
Ejemplo n.º 8
0
import uvicorn
from starlette.applications import Starlette
from starlette.responses import JSONResponse, RedirectResponse
from starlette.routing import Route, Mount
from starlette.templating import Jinja2Templates
from starlette.staticfiles import StaticFiles

from fastai.vision import *

# Cell
ON_JUPY = os.environ['_'].split('/')[-1].lower() == 'jupyter'
static_dir = Path('pokedexr/static') if ON_JUPY else Path('static')

# Cell
templates = Jinja2Templates(directory=static_dir / 'templates')
static_files = StaticFiles(directory=static_dir)
data_files = pathlib.Path(static_dir / 'data')

# Cell
print('Initialising Learner...')
learn = load_learner(data_files, 'export.pkl')
with open(data_files / 'cards.pkl', 'rb') as f:
    cards = pickle.load(f)

# Cell


# Cell
async def home(request):
    return templates.TemplateResponse('index.html', {'request': request})
Ejemplo n.º 9
0
from pathlib import Path
from typing import Any

from fastapi import APIRouter, Request
from starlette.responses import FileResponse
from starlette.templating import Jinja2Templates
from trees.url import base_url

router = APIRouter()
templetes = Jinja2Templates(directory='trees/templates')


@router.get('/')
async def get_main_page(req: Request):
    return templetes.TemplateResponse("main-page.html", {
        "request": req,
        "base_url": base_url
    })


@router.get('/report')
async def get_report_page(req: Request):
    return templetes.TemplateResponse("report.html", {
        "request": req,
        "base_url": base_url
    })


@router.get('/volunteers')
async def get_volunteers_page(req: Request):
    return templetes.TemplateResponse("volunteers.html", {
from fastapi import Request
from sqlalchemy.orm import Session
from starlette.templating import Jinja2Templates

from repository import crud
from repository.crud import db_breaker, get_order_by_id
from repository.database import get_db

from service.order_creation_service import create_and_save_order

from repository.crud import get_paid_order_by_user_and_product
from service.service_models import Order

order_router = APIRouter()

templates = Jinja2Templates(directory="frontend")


@order_router.get("/orders",
                  response_model=List[Order],
                  summary="Fetch all orders",
                  description="Fetches all of the orders.")
def get_orders(db: Session = Depends(get_db)):
    return crud.get_orders(db, limit=100)


@order_router.get("/create-order")
def create_order(product_id: str,
                 quantity: int,
                 request: Request,
                 db: Session = Depends(get_db)):
Ejemplo n.º 11
0
from fastapi_users import FastAPIUsers
from fastapi_users.authentication import JWTAuthentication, CookieAuthentication
from fastapi_users import models
from starlette.templating import Jinja2Templates

from src.models import user_db, UserDB, User


SECRET_KEY = "^-r+qb5+fs7c#7%7j7_6)tvf%nnd4a41_2jm3gg9zp4v%x+h-@"
templates = Jinja2Templates(directory="src/templates")

auth_backends = [
    JWTAuthentication(secret=SECRET_KEY, lifetime_seconds=6000),
    CookieAuthentication(secret=SECRET_KEY, lifetime_seconds=6000),
]


fastapi_users = FastAPIUsers(
    user_db,
    auth_backends,
    User,
    models.BaseUserCreate,
    models.BaseUserUpdate,
    UserDB,
    SECRET_KEY
)
Ejemplo n.º 12
0
pattern = re.compile(r'\w{4,20}')  # 任意の4~20の英数字を示す正規表現
pattern_pw = re.compile(r'\w{6,20}')  # 任意の6~20の英数字を示す正規表現
pattern_mail = re.compile(
    r'^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$')  # e-mailの正規表現

app = FastAPI(
    title="FastAPIでつくるtoDoアプリケーション",
    description="FastAPIチュートリアル:FastAPI(とstarlette)でシンプルなtoDoアプリを作りましょう.",
    version="0.9 beta",
)

security = HTTPBasic()

# new テンプレート関連の設定 (jinja2)
templates = Jinja2Templates(directory="app/templates")
jinja_env = templates.env  # Jinja2.Environment : filterやglobalの設定用


def index(request: Request):
    return templates.TemplateResponse("index.html", {"request": request})


def admin(request: Request,
          credentials: HTTPBasicCredentials = Depends(security)):
    # Basic認証で受け取った情報
    username = auth(credentials)
    password = hashlib.md5(credentials.password.encode()).hexdigest()

    # データベースからユーザ名が一致するデータを取得
    user = db.session.query(User).filter(User.username == username).first()
Ejemplo n.º 13
0
        result_dict['stocks_pct_chg_min'] = stocks_pct_chg_min
        result_dict['stocks_pct_chg_avg'] = stocks_pct_chg_avg
        result_dict['stocks_limit_count'] = stocks_limit_count
        df_groupby_industry_result = df_groupby_industry_result.append(
            result_dict, ignore_index=True)
        #print (index_code,len(df_groupby_industry_result))
        index_code += 1
    return df_groupby_industry_result


#df =   get_realtime_analysis_category_industry()

#模板渲染
#app = FastAPI()
# 挂载模版文件夹
tmp = Jinja2Templates(directory='./api/templates')

#主面板

#行业


#三大产业分类数据
@router.get('/industry/three')
async def get_three(request: Request):  # async加了就支持异步  把Request赋值给request
    js_res = INLINE.render_js()
    css_res = INLINE.render_css()
    industry_dict = get_col_df('industry_three').to_dict('records')
    return tmp.TemplateResponse(
        'industry_three.html', {
            'request': request,
Ejemplo n.º 14
0
from starlette.responses import JSONResponse
from starlette.templating import Jinja2Templates

from operator import itemgetter
from pathlib import Path
from ydl_server.config import app_config, get_finished_path
from ydl_server.logdb import JobsDB, Job, Actions, JobType
from datetime import datetime
import os
import shutil

templates = Jinja2Templates(directory=str(Path(__file__).parent / "templates"))


async def front_index(request):
    context = {
        'request': request,
        'ydl_version': request.app.state.ydlhandler.get_ydl_version(),
        'ydl_name': request.app.state.ydlhandler.ydl_module_name,
        'ydl_website': request.app.state.ydlhandler.ydl_website,
    }
    return templates.TemplateResponse('index.html', context=context)


async def front_logs(request):
    context = {
        'request': request,
        'ydl_version': request.app.state.ydlhandler.get_ydl_version(),
        'ydl_name': request.app.state.ydlhandler.ydl_module_name,
        'ydl_website': request.app.state.ydlhandler.ydl_website,
    }
Ejemplo n.º 15
0
from fastapi_admin.schemas import BulkIn
from fastapi_admin.site import Site

TORTOISE_ORM = {
    "connections": {
        "default": os.getenv("DATABASE_URL")
    },
    "apps": {
        "models": {
            "models": ["examples.models"],
            "default_connection": "default"
        }
    },
}

templates = Jinja2Templates(directory="examples/templates")


@admin_app.post("/rest/{resource}/bulk/test_bulk")
async def test_bulk(bulk_in: BulkIn, model=Depends(get_model)):
    qs = model.filter(pk__in=bulk_in.pk_list)
    pydantic = pydantic_queryset_creator(model)
    ret = await pydantic.from_queryset(qs)
    return ret.dict()


@admin_app.get(
    "/home", )
async def home():
    return {"html": templates.get_template("home.html").render()}
Ejemplo n.º 16
0
from fastapi import FastAPI
from starlette.staticfiles import StaticFiles
from starlette.templating import Jinja2Templates
import logmuse
import sys
import uvicorn
from ubiquerg import parse_registry_path

app = FastAPI(
    title=PKG_NAME,
    description="a web interface and RESTful API for reference genome assets",
    version=server_v
)

app.mount("/" + STATIC_DIRNAME, StaticFiles(directory=STATIC_PATH), name=STATIC_DIRNAME)
templates = Jinja2Templates(directory=TEMPLATES_PATH)


def main():
    global rgc, _LOGGER
    parser = build_parser()
    args = parser.parse_args()
    if not args.command:
        parser.print_help()
        print("No subcommand given")
        sys.exit(1)
    logger_args = dict(name=PKG_NAME, fmt=LOG_FORMAT, level=5) if args.debug else dict(name=PKG_NAME, fmt=LOG_FORMAT)
    _LOGGER = logmuse.setup_logger(**logger_args)
    selected_cfg = select_genome_config(args.config)
    assert selected_cfg is not None, "You must provide a config file or set the {} environment variable".\
        format("or ".join(CFG_ENV_VARS))
Ejemplo n.º 17
0
def create_application(
    database_url: str,
    secret_key: str,
    jwt_key: typing.Union[None, bytes, JWKRepr] = None,
    jwt_signature_algorithm: str = "RS256",
    jwt_signature_params: typing.Dict[str, str] = {},
    jwt_encryption_algorithm: str = "RS256",
    jwt_encryption_params: typing.Dict[str, str] = {},
    debug: bool = False,
    max_pool_workers: int = 10,
    jwt_ttl: timedelta = timedelta(seconds=3600),
    region: str = "ap-northeast-1",
    prepended_routes: typing.Iterable[BaseRoute] = [],
):
    from .views import admin as admin_views
    from .views import index as index_views
    from .views import oauth2 as oauth2_views
    from .views import pools as pools_views

    logging.basicConfig(
        level=logging.DEBUG if debug else logging.INFO,
        force=True,
    )
    if max_pool_workers > 0:
        executor.executor = concurrent.futures.ThreadPoolExecutor(
            max_workers=max_pool_workers
        )
    session_factory.configure(
        bind=sa.create_engine(database_url),
    )

    if jwt_key is None:
        jwt_key = generate_jwk(jwt_encryption_algorithm)

    jwt_public_key = jwt_key

    if isinstance(jwt_key, dict):
        if "kid" not in jwt_key:
            jwt_key = dict(jwt_key)
            jwt_key["kid"] = generate_key(16)
        jwt_public_key = build_jwt_public_key_from_private_key(jwt_key)

    jwt_config = JWTConfiguration(
        key=jwt_key,
        public_key=jwt_public_key,
        signature_algorithm=jwt_signature_algorithm,
        signature_params=jwt_signature_params,
        encryption_algorithm=jwt_encryption_algorithm,
        encryption_params=jwt_encryption_params,
        issuer="",
        ttl=jwt_ttl,
    )

    routes: typing.List[BaseRoute] = list(prepended_routes)
    routes += [
        Mount(
            "/static",
            app=StaticFiles(directory=str(basedir / "static")),
            name="static",
        ),
        Mount(
            "/admin",
            name="admin",
            app=admin_views.routes,
        ),
        Mount(
            "/oauth2",
            name="oauth2",
            app=oauth2_views.routes,
        ),
        Route(
            "/logout",
            oauth2_views.LogoutEndpoint,
        ),
        Mount(
            "/{pool}",
            name="pools",
            app=apply_middlewares(
                pools_views.routes,
                middleware=[
                    Middleware(PoolDetectionMiddleware),
                    Middleware(
                        AuthenticationMiddleware, backend=SessionAuthenticationBackend()
                    ),
                ],
            ),
        ),
        Mount("/", index_views.routes),
    ]

    app = Starlette(
        debug=debug,
        routes=routes,
        middleware=[
            Middleware(RequestTimeMiddleware),
            Middleware(SQLAlchemyMiddleware),
            Middleware(SessionMiddleware, secret_key=secret_key),
            Middleware(TemplateShortcutMiddleware),
        ],
        on_shutdown=[
            lambda: (
                executor.executor.shutdown(wait=True)
                if executor.executor is not None
                else None
            ),
        ],
    )
    app.state.jwt_config = jwt_config
    app.state.region = region
    app.state.templates = Jinja2Templates(directory=str(basedir / "templates"))
    app.state.kdf = PasswordHasher()
    app.state.uuidgen = lambda: str(uuid.uuid4())
    return app
Ejemplo n.º 18
0
from fastai2.vision.all 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
from starlette.templating import Jinja2Templates
from starlette.routing import Route
import logging

from app_utils import *

classes = ['Saab_9000', 'Saab_900', 'Saab_9-3', 'Saab_9-5']

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

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

logger = logging.getLogger()
logger.setLevel(logging.DEBUG)

loop = asyncio.get_event_loop()
tasks = [asyncio.ensure_future(setup_learner())]
learn = loop.run_until_complete(asyncio.gather(*tasks))[0]
loop.close()
Ejemplo n.º 19
0
import logging
from fastapi import FastAPI
from starlette.requests import Request
from starlette.websockets import WebSocket
from starlette.responses import HTMLResponse
from starlette.templating import Jinja2Templates

import asyncio

from database.db import Database
from database.models import WikiMap
from utils.wikigraph import WikipediaGraph

app = FastAPI()

TEMPLATES = Jinja2Templates(directory="../static/templates")
"""
          var simulation = d3.forceSimulation(nodes)
                .force("charge", d3.forceManyBody())
                .force("link", d3.forceLink(links))
                .force("center", d3.forceCenter());     



try {
                    Graph.graphData({
                        nodes: [...nodes, ...newNodes],
                        links: [...links, ...newLinks]
                        });
                } catch(ReferenceError) {
                    Graph.graphData({
Ejemplo n.º 20
0
from helpdesk.config import (
    NOTIFICATION_TITLE_PREFIX,
    WEBHOOK_URL,
    ADMIN_EMAIL_ADDRS,
    FROM_EMAIL_ADDR,
    SMTP_SERVER,
    SMTP_SERVER_PORT,
    SMTP_SSL,
    SMTP_CREDENTIALS,
    get_user_email,
)

logger = logging.getLogger(__name__)

_templates = Jinja2Templates(directory='templates/notification')


class Notification:
    method = None

    def __init__(self, phase, ticket):
        self.phase = phase
        self.ticket = ticket

    async def send(self):
        raise NotImplementedError

    def render(self):
        import xml.etree.ElementTree as ET
Ejemplo n.º 21
0
from starlette.applications import Starlette
from starlette.responses import JSONResponse, HTMLResponse
from starlette.routing import Route, Mount
from starlette.templating import Jinja2Templates
from starlette.staticfiles import StaticFiles

from products_data import products_data


templates = Jinja2Templates(directory='templates')

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

async def products(request):
    return JSONResponse(products_data)

app = Starlette(debug=True, routes=[
    Route('/', homepage), 
    Route('/products', products), 
    Mount('/static', StaticFiles(directory='static'), name='static')
])

Ejemplo n.º 22
0
import fastapi
from starlette.requests import Request
from starlette.templating import Jinja2Templates

router = fastapi.APIRouter()
templates = Jinja2Templates("templates")


@router.get("/")
def index(request: Request):
    return templates.TemplateResponse("home/index.html", {"request": request})


@router.get("/favicon.ico")
def favicon():
    return fastapi.responses.RedirectResponse(url="/static/img/favicon.ico")
Ejemplo n.º 23
0
AGGRID_ENTERPRISE = config('AGGRID_ENTERPRISE', cast=bool, default=False)

NO_INTERNET = config('NO_INTERNET', cast=bool, default=True)


def create_component_file_list():
    file_list = []
    component_dir = os.path.join(STATIC_DIRECTORY, 'components')
    if os.path.isdir(component_dir):
        for file in os.listdir(component_dir):
            if fnmatch.fnmatch(file, '*.js'):
                file_list.append(f'/components/{file}')
    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,
Ejemplo n.º 24
0
from morecantile import tms
from morecantile.models import TileMatrixSet
from rasterio.crs import CRS
from rio_tiler.colormap import cmap, parse_color

from fastapi import HTTPException, Query

from starlette.templating import Jinja2Templates

try:
    from importlib.resources import files as resources_files  # type: ignore
except ImportError:
    # Try backported to PY<39 `importlib_resources`.
    from importlib_resources import files as resources_files  # type: ignore

templates = Jinja2Templates(
    directory=str(resources_files(__package__) / "templates"))

# colors from https://daac.ornl.gov/ABOVE/guides/Annual_Landcover_ABoVE.html
above_cmap = {
    1: [58, 102, 24, 255],  # Evergreen Forest
    2: [100, 177, 41, 255],  # Deciduous Forest
    3: [177, 177, 41, 255],  # Shrubland
    4: [221, 203, 154, 255],  # Herbaceous
    5: [218, 203, 47, 255],  # Sparely Vegetated
    6: [177, 177, 177, 255],  # Barren
    7: [175, 255, 205, 255],  # Fen
    8: [239, 255, 192, 255],  # Bog
    9: [144, 255, 255, 255],  # Shallows/Littoral
    10: [29, 0, 250, 255],  # Water
}
cmap = cmap.register({"above": above_cmap})
Ejemplo n.º 25
0
def test_template_response_requires_request(tmpdir):
    templates = Jinja2Templates(str(tmpdir))
    with pytest.raises(ValueError):
        templates.TemplateResponse(None, {})
Ejemplo n.º 26
0
from titiler.ressources.enums import (
    ImageMimeTypes,
    ImageType,
    MimeTypes,
    PixelSelectionMethod,
)
from titiler.ressources.responses import ImgResponse, XMLResponse

from fastapi import APIRouter, Depends, Path, Query

from starlette.concurrency import run_in_threadpool
from starlette.requests import Request
from starlette.templating import Jinja2Templates

router = APIRouter()
templates = Jinja2Templates(directory="titiler/templates")


def _read_tile(url: str, *args, **kwargs) -> Tuple[numpy.ndarray, numpy.ndarray]:
    """Read tile from an asset"""
    with COGReader(url) as cog:
        tile, mask = cog.tile(*args, **kwargs)
    return tile, mask


def _read_point(asset: str, *args, **kwargs) -> List:
    """Read pixel value at a point from an asset"""
    with COGReader(asset) as cog:
        return cog.point(*args, **kwargs)

Ejemplo n.º 27
0
class CustomHeaderMiddleware(BaseHTTPMiddleware):
    def __init__(self, app, header_value='Example'):
        print('__init__')
        super().__init__(app)
        self.header_value = header_value

    async def dispatch(self, request, call_next):
        response = await call_next(request)
        response.headers['Custom'] = self.header_value
        return response


asyncio.set_event_loop_policy(uvloop.EventLoopPolicy())
app = FastAPI()
app.add_middleware(CustomHeaderMiddleware)
templates = Jinja2Templates(directory="templates")


def get_local_ip():
    """
    copy and paste from
    https://stackoverflow.com/questions/166506/finding-local-ip-addresses-using-pythons-stdlib
    """
    if os.environ.get('CHAT_HOST_IP', False):
        return os.environ['CHAT_HOST_IP']
    try:
        ip = [l for l in (
            [ip for ip in socket.gethostbyname_ex(socket.gethostname())[2] if
             not ip.startswith("127.")][:1], [
                [(s.connect(('8.8.8.8', 53)), s.getsockname()[0], s.close()) for s
                 in
Ejemplo n.º 28
0
    def __init__(self,
                 enablePiCamera=False,
                 stabilize=False,
                 source=0,
                 camera_num=0,
                 y_tube=False,
                 backend=0,
                 colorspace=None,
                 resolution=(640, 480),
                 framerate=25,
                 logging=False,
                 time_delay=0,
                 **options):

        # initialize global params
        self.__jpeg_quality = 90  # 90% quality
        self.__jpeg_optimize = 0  # optimization off
        self.__jpeg_progressive = 0  # jpeg will be baseline instead
        self.__frame_size_reduction = 20  # 20% reduction
        self.__logging = logging

        custom_data_location = ""  # path to save data-files to custom location
        data_path = ""  # path to WebGear data-files
        overwrite_default = False

        # reformat dictionary
        options = {str(k).strip(): v for k, v in options.items()}

        # assign values to global variables if specified and valid
        if options:
            if "frame_size_reduction" in options:
                value = options["frame_size_reduction"]
                if isinstance(value,
                              (int, float)) and value >= 0 and value <= 90:
                    self.__frame_size_reduction = value
                else:
                    logger.warning(
                        "Skipped invalid `frame_size_reduction` value!")
                del options["frame_size_reduction"]  # clean
            if "frame_jpeg_quality" in options:
                value = options["frame_jpeg_quality"]
                if isinstance(value,
                              (int, float)) and value >= 10 and value <= 95:
                    self.__jpeg_quality = int(value)
                else:
                    logger.warning(
                        "Skipped invalid `frame_jpeg_quality` value!")
                del options["frame_jpeg_quality"]  # clean
            if "frame_jpeg_optimize" in options:
                value = options["frame_jpeg_optimize"]
                if isinstance(value, bool):
                    self.__jpeg_optimize = int(value)
                else:
                    logger.warning(
                        "Skipped invalid `frame_jpeg_optimize` value!")
                del options["frame_jpeg_optimize"]  # clean
            if "frame_jpeg_progressive" in options:
                value = options["frame_jpeg_progressive"]
                if isinstance(value, bool):
                    self.__jpeg_progressive = int(value)
                else:
                    logger.warning(
                        "Skipped invalid `frame_jpeg_progressive` value!")
                del options["frame_jpeg_progressive"]  # clean
            if "custom_data_location" in options:
                value = options["custom_data_location"]
                if isinstance(value, str):
                    assert os.access(
                        value, os.W_OK
                    ), "[WebGear:ERROR] :: Permission Denied!, cannot write WebGear data-files to '{}' directory!".format(
                        value)
                    assert os.path.isdir(
                        os.path.abspath(value)
                    ), "[WebGear:ERROR] :: `custom_data_location` value must be the path to a directory and not to a file!"
                    custom_data_location = os.path.abspath(value)
                else:
                    logger.warning(
                        "Skipped invalid `custom_data_location` value!")
                del options["custom_data_location"]  # clean
            if "overwrite_default_files" in options:
                value = options["overwrite_default_files"]
                if isinstance(value, bool):
                    overwrite_default = value
                else:
                    logger.warning(
                        "Skipped invalid `overwrite_default_files` value!")
                del options["overwrite_default_files"]  # clean

        # define stream with necessary params
        self.stream = VideoGear(enablePiCamera=enablePiCamera,
                                stabilize=stabilize,
                                source=source,
                                camera_num=camera_num,
                                y_tube=y_tube,
                                backend=backend,
                                colorspace=colorspace,
                                resolution=resolution,
                                framerate=framerate,
                                logging=logging,
                                time_delay=time_delay,
                                **options)

        # check if custom certificates path is specified
        if custom_data_location:
            data_path = generate_webdata(
                custom_data_location,
                overwrite_default=overwrite_default,
                logging=logging,
            )
        else:
            # otherwise generate suitable path
            from os.path import expanduser

            data_path = generate_webdata(
                os.path.join(expanduser("~"), ".vidgear"),
                overwrite_default=overwrite_default,
                logging=logging,
            )

        # log it
        if self.__logging:
            logger.debug(
                "`{}` is the default location for saving WebGear data-files.".
                format(data_path))
        if self.__logging:
            logger.debug(
                "Setting params:: Size Reduction:{}%, JPEG quality:{}%, JPEG optimizations:{}, JPEG progressive:{}"
                .format(
                    self.__frame_size_reduction,
                    self.__jpeg_quality,
                    bool(self.__jpeg_optimize),
                    bool(self.__jpeg_progressive),
                ))

        # define Jinja2 templates handler
        self.__templates = Jinja2Templates(
            directory="{}/templates".format(data_path))

        # define custom exception handlers
        self.__exception_handlers = {
            404: self.__not_found,
            500: self.__server_error
        }
        # define routing tables
        self.routes = [
            Route("/", endpoint=self.__homepage),
            Route("/video", endpoint=self.__video),
            Mount(
                "/static",
                app=StaticFiles(directory="{}/static".format(data_path)),
                name="static",
            ),
        ]
        # copying original routing tables for further validation
        self.__rt_org_copy = self.routes[:]
        # keeps check if producer loop should be running
        self.__isrunning = True
Ejemplo n.º 29
0
    def __init__(self,
                 enablePiCamera=False,
                 stabilize=False,
                 source=None,
                 camera_num=0,
                 stream_mode=False,
                 backend=0,
                 colorspace=None,
                 resolution=(640, 480),
                 framerate=25,
                 logging=False,
                 time_delay=0,
                 **options):
        """
        This constructor method initializes the object state and attributes of the WebGear_RTC class.

        Parameters:
            enablePiCamera (bool): provide access to PiGear(if True) or CamGear(if False) APIs respectively.
            stabilize (bool): enable access to Stabilizer Class for stabilizing frames.
            camera_num (int): selects the camera module index which will be used as Rpi source.
            resolution (tuple): sets the resolution (i.e. `(width,height)`) of the Rpi source.
            framerate (int/float): sets the framerate of the Rpi source.
            source (based on input): defines the source for the input stream.
            stream_mode (bool): controls the exclusive YouTube Mode.
            backend (int): selects the backend for OpenCV's VideoCapture class.
            colorspace (str): selects the colorspace of the input stream.
            logging (bool): enables/disables logging.
            time_delay (int): time delay (in sec) before start reading the frames.
            options (dict): provides ability to alter Tweak Parameters of WebGear_RTC, CamGear, PiGear & Stabilizer.
        """
        # raise error(s) for critical Class imports
        import_dependency_safe("starlette" if starlette is None else "")
        import_dependency_safe("aiortc" if aiortc is None else "")

        # initialize global params
        self.__logging = logging

        custom_data_location = ""  # path to save data-files to custom location
        data_path = ""  # path to WebGear_RTC data-files
        overwrite_default = False
        self.__relay = None  # act as broadcaster

        # reformat dictionary
        options = {str(k).strip(): v for k, v in options.items()}

        # assign values to global variables if specified and valid
        if options:
            if "custom_data_location" in options:
                value = options["custom_data_location"]
                if isinstance(value, str):
                    assert os.access(
                        value, os.W_OK
                    ), "[WebGear_RTC:ERROR] :: Permission Denied!, cannot write WebGear_RTC data-files to '{}' directory!".format(
                        value)
                    assert os.path.isdir(
                        os.path.abspath(value)
                    ), "[WebGear_RTC:ERROR] :: `custom_data_location` value must be the path to a directory and not to a file!"
                    custom_data_location = os.path.abspath(value)
                else:
                    logger.warning(
                        "Skipped invalid `custom_data_location` value!")
                del options["custom_data_location"]  # clean

            if "overwrite_default_files" in options:
                value = options["overwrite_default_files"]
                if isinstance(value, bool):
                    overwrite_default = value
                else:
                    logger.warning(
                        "Skipped invalid `overwrite_default_files` value!")
                del options["overwrite_default_files"]  # clean

            if "enable_live_broadcast" in options:
                value = options["enable_live_broadcast"]
                if isinstance(value, bool):
                    if value:
                        self.__relay = MediaRelay()
                        options[
                            "enable_infinite_frames"] = True  # enforce infinite frames
                        logger.critical(
                            "Enabled live broadcasting for Peer connection(s)."
                        )
                    else:
                        None
                else:
                    logger.warning(
                        "Skipped invalid `enable_live_broadcast` value!")
                del options["enable_live_broadcast"]  # clean

        # check if custom certificates path is specified
        if custom_data_location:
            data_path = generate_webdata(
                custom_data_location,
                c_name="webgear_rtc",
                overwrite_default=overwrite_default,
                logging=logging,
            )
        else:
            # otherwise generate suitable path
            data_path = generate_webdata(
                os.path.join(expanduser("~"), ".vidgear"),
                c_name="webgear_rtc",
                overwrite_default=overwrite_default,
                logging=logging,
            )

        # log it
        if self.__logging:
            logger.debug(
                "`{}` is the default location for saving WebGear_RTC data-files."
                .format(data_path))

        # define Jinja2 templates handler
        self.__templates = Jinja2Templates(
            directory="{}/templates".format(data_path))

        # define custom exception handlers
        self.__exception_handlers = {
            404: self.__not_found,
            500: self.__server_error
        }
        # define routing tables
        self.routes = [
            Route("/", endpoint=self.__homepage),
            Route("/offer", self.__offer, methods=["GET", "POST"]),
            Mount(
                "/static",
                app=StaticFiles(directory="{}/static".format(data_path)),
                name="static",
            ),
        ]

        # define middleware support
        self.middleware = []

        # Handle RTC video server
        if source is None:
            self.config = {"server": None}
            self.__default_rtc_server = None
            if self.__logging:
                logger.warning("Given source is of NoneType!")
        else:
            # Handle video source
            self.__default_rtc_server = RTC_VideoServer(
                enablePiCamera=enablePiCamera,
                stabilize=stabilize,
                source=source,
                camera_num=camera_num,
                stream_mode=stream_mode,
                backend=backend,
                colorspace=colorspace,
                resolution=resolution,
                framerate=framerate,
                logging=logging,
                time_delay=time_delay,
                **options)
            # define default frame generator in configuration
            self.config = {"server": self.__default_rtc_server}
            # add exclusive reset connection node
            self.routes.append(
                Route("/close_connection",
                      self.__reset_connections,
                      methods=["POST"]))
        # copying original routing tables for further validation
        self.__rt_org_copy = self.routes[:]
        # collects peer RTC connections
        self.__pcs = set()
Ejemplo n.º 30
0
from fastapi import FastAPI
from starlette.requests import Request
from starlette.staticfiles import StaticFiles
from starlette.templating import Jinja2Templates

from . import auth
from .api.v1 import api_v1

app = FastAPI(debug=True)  # pylint: disable=invalid-name

base_dir = Path(__file__).parent
app.mount("/static", StaticFiles(directory=str(base_dir / "static")),
          name="static")
app.mount("/api/v1", api_v1)

templates = Jinja2Templates(directory=str(base_dir / "templates"))

app.include_router(
    auth.router,
    tags=["Authentication"],
    prefix="/api"
)


@app.get("/.*")
async def index(request: Request):
    """Index url, let frontend handle all routes."""
    return templates.TemplateResponse("index.html", {"request": request})


@app.middleware("http")