Example #1
0
    def start(self):
        default_app = Starlette()

        @default_app.route("/{actor}", methods=["GET", "POST"])
        async def dispatch_remote_function(request):
            data = await request.json()
            actor_name = request.path_params["actor"]

            slo_seconds = data.pop("slo_ms") / 1000
            deadline = time.perf_counter() + slo_seconds

            inp = data.pop("input")

            result_future = unwrap(
                self.router.call.remote(actor_name, inp, deadline))

            # TODO(simon): change to asyncio ray.get
            result = ray.get(result_future)

            return JSONResponse({
                "success": True,
                "actor": actor_name,
                "result": result
            })

        uvicorn.run(default_app, host=self.ip, port=self.port)
Example #2
0
def main(app=None):
    # setup
    if app is None:
        app = init()

    kwargs = {}
    if LOCAL_DEV:
        kwargs['reload'] = True
    else:
        kwargs['workers'] = 2

    uvicorn.run(app, host='0.0.0.0', http='h11', port=8445, headers=[('Server', 'tmeister')],
                proxy_headers=True, **kwargs)
Example #3
0
    data_bunch = ImageDataBunch.single_from_classes(
        path, classes, tfms=get_transforms(),
        size=224).normalize(imagenet_stats)
    learn = cnn_learner(data_bunch, models.resnet34, pretrained=False)
    learn.load(model_file_name)
    return learn


loop = asyncio.get_event_loop()
tasks = [asyncio.ensure_future(setup_learner())]
learn = loop.run_until_complete(asyncio.gather(*tasks))[0]
loop.close()


@app.route('/')
def index(request):
    html = path / 'view' / 'index.html'
    return HTMLResponse(html.open().read())


@app.route('/analyze', methods=['POST'])
async def analyze(request):
    data = await request.form()
    img_bytes = await (data['file'].read())
    img = open_image(BytesIO(img_bytes))
    return JSONResponse({'result': learn.predict(img)[0]})


if __name__ == '__main__':
    if 'serve' in sys.argv: uvicorn.run(app, host='0.0.0.0', port=8080)
Example #4
0
        pattern = '(?:{})(.*)(?:{})'.format(prepend_esc, eot_esc)
        trunc_text = re.search(pattern, text).group(1)
        valid_card_text = await is_ascii(trunc_text)

        # ensure there is only one of each section in the generated card
        counts = Counter(trunc_text)
        section_ids = ['0', '1', '3', '4', '5', '6', '7', '8', '9']
        if all([counts[x] == 1 for x in section_ids]) and valid_card_text:
            good_text = True
        else:
            return UJSONResponse(
                {
                    'text_format':
                    "<div class='gen-box warning'>Unfortunately, the AI created an invalid card. Please try again!</div>",
                    'image': ""
                },
                headers=response_header)

    try:
        r = requests.post(IMAGE_API_URL, json={'text': trunc_text}, timeout=10)

        return UJSONResponse(r.json(), headers=response_header)

    except:
        return UJSONResponse({'text_format': trunc_text},
                             headers=response_header)


if __name__ == '__main__':
    uvicorn.run(app, host='0.0.0.0', port=int(os.environ.get('PORT', 8080)))
Example #5
0
                         x),
)


@curry
def if_(if_func, func, arg):
    """Whether to apply a function or not
    """
    if if_func(arg):
        return func(arg)
    return arg


@app.get("/get/")
async def get_binary_file(url: UrlStr):
    """Base endpoint to get binary file
    """
    return sequence(
        if_(search(r"https://drive\.google\.com(.*)"), modify_google),
        requests.get,
        lambda x: (BytesIO(x.content), x.headers["content-type"]),
        lambda x: StreamingResponse(x[0], media_type=x[1]),
    )(url)


if __name__ == "__main__":
    # run with python main.py to debug
    import uvicorn

    uvicorn.run(app, host="0.0.0.0", port=8000)
Example #6
0
    ]
    arr = list(filter(("-").__ne__, arr))
    print(arr)
    reco = mal_scrap.big_list_recommendation(arr)
    arr_reco = []
    arr_reco2 = []
    for i in reco:
        print(reco[i][0])

        if (i in arr):
            arr_reco2.append(
                [i, reco[i][0], reco[i][1] * reco[i][2], "background:#34495e"])
            arr_reco.append(
                [i, reco[i][0], reco[i][1], reco[i][2], "background:#34495e"])
        else:
            arr_reco2.append([i, reco[i][0], reco[i][1] * reco[i][2], ""])
            arr_reco.append([i, reco[i][0], reco[i][1], reco[i][2], ""])

    arr_reco = sorted(arr_reco, key=lambda l: l[2], reverse=True)
    arr_reco2 = sorted(arr_reco2, key=lambda l: l[2], reverse=True)

    return templates.TemplateResponse("download.html", {
        "request": request,
        "data": arr_reco,
        "data2": arr_reco2
    })


if __name__ == "__main__":
    uvicorn.run(app, host="127.0.0.1", port=5001)
Example #7
0
    body = await request.json()
    address = body.get('address')
    db.createTransaction(address)


@app.get('/api/create-transaction')
async def createTransaction():
    db.createTransaction()


@app.post('/api/get-address-transactions')
async def getAddressTransactions(request: Request):
    body = await request.json()
    address = body.get('address')
    transactions = db.getAddressTransactions(address)
    return jsonable_encoder(transactions)


@app.get('/api/get-transactions')
def getTransactions():
    transactions = db.getTransactions()
    return jsonable_encoder(transactions)


if __name__ == '__main__':
    uvicorn.run('app:app',
                host='0.0.0.0',
                port=8000,
                log_level='info',
                reload=True)
Example #8
0
example_query = """
{
  allEmployees(sort: [NAME_ASC, ID_ASC]) {
    edges {
      node {
        id
        name
        department {
          id
          name
        }
        role {
          id
          name
        }
      }
    }
  }
}
"""

app = FastAPI()
app.add_route("/", GraphQLApp(schema=schema, graphiql=True))

if __name__ == "__main__":
    from database import init_db
    import uvicorn
    init_db()
    uvicorn.run(app, port=5000, debug=True)
Example #9
0
    await redis_plugin.init()
    await database.connect()

    # for big files can try https://stackoverflow.com/a/48229517
    with open('tarif.json', 'r') as file:
        data = ujson.load(file)

    # TODO optimize it for big json
    for key, value in data.items():
        for cargo in value:
            await redis_plugin.redis.hmset_dict(
                key,
                {
                    # the cargo_type is key, the rate is value:
                    cargo["cargo_type"]:
                    cargo["rate"]
                })


@app.on_event('shutdown')
async def on_shutdown() -> None:
    await redis_plugin.terminate()
    await database.disconnect()


DEBUG = os.getenv("DEBUG") == 'True'

if __name__ == "__main__" and DEBUG:
    import uvicorn
    uvicorn.run("main:app", debug=True, reload=True)
Example #10
0
        cron_day_of_week=job.cron_day_of_week,
        cron_month=job.cron_month,
        run_type=1,
        enabled=0,
        is_lock=1,
        priority=999,
        create_time=now,
    )
    await database.execute(query=query, values=values)

    return {'result': 'succ'}


@app.post('/delete_db_job/')
async def delete_db_job(job: UpdateJob):
    update_sql = f"delete from  scheduler where id={job.id}"
    await database.execute(update_sql)
    return {'result': 'succ'}


@app.post("/upload/")
async def upload_file(file: UploadFile = File(...)):
    try:
        return {"filename": file.filename, 'result': 'fail', 'msg': "请使用 main_rpc_server.py 才可以使用上传!"}
    except Exception as e:
        raise HTTPException(status_code=400, detail="file upload fail")


if __name__ == '__main__':
    u.run(app, host="0.0.0.0", port=8081)
Example #11
0
from fastapi import FastAPI

from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker

import settings
import os

from starlette.graphql import GraphQLApp
from starlette.datastructures import Secret

from graphql_repo.mutation import Mutation
from graphql_repo.schema import Query

import graphene
import uvicorn

app = FastAPI()

app.add_route(
    "/", GraphQLApp(schema=graphene.Schema(query=Query, mutation=Mutation)))

if __name__ == "__main__":
    uvicorn.run("main:app", host="127.0.0.1", port=8000, reload=True)
Example #12
0

@app.get('/blog/unpublished')
def unpublished():
    return {'data' : 'all unplublished blog'}


@app.get('/blog/{id}')
def show(id: int):
    return {'data': id}


@app.get('/blog/{id}/comment')
def comments(id: int, limit=10):
    return {'data' : f'{id} and {limit}'}


class Blog(BaseModel):
    title: str
    body: str
    published: Optional[bool]


@app.post('/blog')
def create_blog(request: Blog):
    return {'data': f'blog is created with {request.title}'}


if __name__ == '__main__':
    uvicorn.run(app, host='0.0.0.0', port=5000)
Example #13
0
    def bind_entrypoint(self, ep: Entrypoint):
        ep.bind_dependency_overrides_provider(self)
        self.routes.extend(ep.routes)
        self.on_event('shutdown')(ep.shutdown)


if __name__ == '__main__':
    import uvicorn

    app = API()

    api_v1 = Entrypoint('/api/v1/jsonrpc')

    class MyError(BaseError):
        CODE = 5000
        MESSAGE = "My error"

        class DataModel(BaseModel):
            details: str

    @api_v1.method(errors=[MyError])
    def echo(data: str = Body(..., example='123'), ) -> str:
        if data == 'error':
            raise MyError(data={'details': 'error'})
        else:
            return data

    app.bind_entrypoint(api_v1)

    uvicorn.run(app, port=5000, debug=True, access_log=False)
Example #14
0
        else:
            raise


loop = asyncio.get_event_loop()
tasks = [asyncio.ensure_future(setup_learner())]
learn = loop.run_until_complete(asyncio.gather(*tasks))[0]
loop.close()


@app.route('/')
async def homepage(request):
    html_file = path / 'view' / 'index.html'
    return HTMLResponse(html_file.open().read())


@app.route('/analyze', methods=['POST'])
async def analyze(request):
    img_data = await request.form()
    img_bytes = await (img_data['file'].read())
    img = open_image(BytesIO(img_bytes))
    prediction = classes[int(learn.predict(img)[1])]
    return JSONResponse({'result': str(prediction)})


if __name__ == '__main__':
    if 'serve' in sys.argv:
        uvicorn.run(app=app,
                    host='0.0.0.0',
                    port=int(os.environ.get('PORT', 5000)),
                    log_level="info")
Example #15
0
    memory_usage_in_bytes = -1
    cpu_usage_in_nanoseconds = -1

    memory_usage_file_path = '/sys/fs/cgroup/memory/memory.usage_in_bytes'
    if os.path.exists(memory_usage_file_path):
        with open(memory_usage_file_path, 'r') as memory_fd:
            memory_usage_in_bytes = int(memory_fd.read().strip())

    cpu_usage_file_path = '/sys/fs/cgroup/cpu/cpuacct.usage'
    if os.path.exists(cpu_usage_file_path):
        with open(cpu_usage_file_path, 'r') as cpu_fd:
            cpu_usage_in_nanoseconds = int(cpu_fd.read().strip())

    data["pod"] = {
        "memory_usage_in_bytes": memory_usage_in_bytes,
        "cpu_usage_in_nanoseconds": cpu_usage_in_nanoseconds
    }

    return data


if __name__ == "__main__":

    logging_setup()
    logging.info(logf("Started metrics exporter process at port 8050"))

    uvicorn.run("exporter:metrics_app",
                host="0.0.0.0",
                port=8050,
                log_level="info")
Example #16
0
#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import uvicorn
from uvicorn.middleware.proxy_headers import ProxyHeadersMiddleware
from starlette.middleware.base import BaseHTTPMiddleware, RequestResponseEndpoint
from starlette.requests import Request
from starlette.responses import PlainTextResponse

from qllr import app
from qllr.settings import HOST, PORT, TRUSTED_PROXIES


class TrustedProxiesMiddleware(BaseHTTPMiddleware):
    async def dispatch(self, request: Request, call_next: RequestResponseEndpoint):
        if "x-forwarded-for" in request.headers:
            if request.client.host not in TRUSTED_PROXIES:
                return PlainTextResponse("Client address spoofing detected", 403)
        return await call_next(request)


app.add_middleware(ProxyHeadersMiddleware)
app.add_middleware(TrustedProxiesMiddleware)

if __name__ == "__main__":
    uvicorn.run(app, host=HOST, port=PORT, lifespan="on")
Example #17
0
async def do_login(request):
    form = await request.form()
    username = form.get('username')
    password = form.get('password')
    LOG.info(f'Attempting login for {username}')
    response = await session.login(request, username, password, api)
    return response


@app.route('/network/action/{form_name}')
async def network_action_form_get(request):
    form_name = request.path_params['form_name']
    query = api.get_form_query(form_name, **request.query_params)
    results = await api.call(
        query,
        request=request
    )

    resp = {
        'errors': cannula.format_errors(results.errors),
        'data': results.data or {}
    }

    return JSONResponse(resp)


if __name__ == '__main__':
    if USE_MOCKS:
        api.middleware.insert(0, MockMiddleware(mock_all=False))
    uvicorn.run(app, host='0.0.0.0', port=int(PORT), debug=True, log_level=logging.INFO)
Example #18
0
# ################
# Exception Handler
# ################


@APP.exception_handler(pydantic.error_wrappers.ValidationError)
async def handle_validation_error(
    request: Request, exc: pydantic.error_wrappers.ValidationError):  # pylint: disable=unused-argument
    """
    Handles validation errors.
    """
    return JSONResponse({"message": exc.errors()}, status_code=422)


# ################
# Routing
# ################

# Include routers.
APP.include_router(V1, prefix="", tags=["v1"])
APP.include_router(V2, prefix="/v2", tags=["v2"])

# Running of app.
if __name__ == "__main__":
    uvicorn.run(
        "app.main:APP",
        host="127.0.0.1",
        port=int(os.getenv("PORT", "5000")),
        log_level="info",
    )
Example #19
0
from fastapi import FastAPI
import uvicorn

separator = ', '

app = FastAPI()


class Endpoint:
    def get(self, path, queries, return_function_name):
        queries = separator.join(queries)
        exec(f"""@app.get("{path}")
async def end({queries}): return {return_function_name}({queries})""")


end = Endpoint()


def plus(a, b):
    return a + b


end.get(path="/hi", queries=['a', 'b'], return_function_name="plus")

if __name__ == "__main__":
    uvicorn.run(app, host="localhost", port=8000)
Example #20
0
 def start(self):
     """Start tile server."""
     uvicorn.run(app=self.app,
                 host=self.host,
                 port=self.port,
                 log_level="info")
Example #21
0
    local.interfaces = local.get_if_info()
    return {'interfaces': local.interfaces}

# removing due to fastapi issue #894, outlets method was not being used for anything currently so disabling for now
# @app.get('/api/v1.0/outlets')
# def get_outlets(request: Request, outlets=OUTLETS):
#     log_request(request, 'outlets')
#     # -- Collect Outlet Details remove sensitive data --
#     if outlets:
#         outlets = cpi.pwr.pwr_get_outlets()
#         cpiexec.wait_for_threads()
#         if outlets and 'defined' in outlets:
#             outlets['defined'] = {p: {k: v for k, v in outlets['defined'][p].items()
#                                   if k not in ['username', 'password']} for p in outlets['defined']}

#     return outlets


@app.get('/api/v1.0/details')
def get_details(request: Request):
    log_request(request, 'details')
    global last_update
    if int(time()) - last_update > 20:
        local.data = local.build_local_dict(refresh=True)
        last_update = int(time())
    return local.data


if __name__ == "__main__":
    uvicorn.run(app, host="0.0.0.0", port=5000, log_level="info")
Example #22
0
def main():
    uvicorn.run(app, host="0.0.0.0", port=9000)
Example #23
0
origins = ["http://*****:*****@app.get("/")
async def read_root():
    return {"Hello": "World"}


@app.get("/new_example")
async def create_example():
    return {}


@app.post("/new_dsm/")
Example #24
0
from typing import Optional

import uvicorn
from fastapi import FastAPI
from odmantic import AIOEngine, Field, Model

app = FastAPI()

engine = AIOEngine(database="fastapi-app")


class Publisher(Model):
    name: str
    founded: int = Field(ge=1440)
    location: Optional[str] = None


@app.get("/")
async def root():
    publisher = Publisher(name="Garfield", founded=100000)
    await engine.save(publisher)
    return publisher


if __name__ == "__main__":
    from debugger import initialize_server_debugger_if_needed

    initialize_server_debugger_if_needed()
    uvicorn.run("main:app", host="0.0.0.0", port=8000, debug=True)
Example #25
0
                            detail=f'File "{file_path}" not found.')

    body = await request.body()
    post_req = [
        req for req in post_entries[file_path] if req.request_data == body
    ]

    if not post_req:
        print('data not found:', body)
        raise HTTPException(status_code=404,
                            detail='No response exists for given content')

    post_req = post_req[0]

    return Response(post_req.response_data,
                    headers={
                        'mimeType': post_req.mime_type,
                        'Content-Type': post_req.mime_type
                    })


if __name__ == '__main__':
    config_kwargs = dict(
        app=app,
        host='0.0.0.0',
        port=int(os.getenv('PORT', 80)),
        #  workers=1,
        log_level='info',
    )
    uvicorn.run(**config_kwargs)
Example #26
0
def calculate(a: int = None, b: int = None):
    c = a + b
    res = {"res": c}
    return res


@app.get('/')
def hello():
    return "Hello1"


class Item(BaseModel):
    POS: str = None


@app.post('/test')
def calculate(request_data: Item):
    if request_data.POS:
        doc = nlp(request_data.POS)
        result = {}
        for token in doc:
            result[token.text] = token.pos_
        return result
    return "error"


if __name__ == '__main__':
    import uvicorn

    uvicorn.run(app=app, host='0.0.0.0', port=8080, workers=1)
Example #27
0
            message = "\n\nThis model was trained with an old version of fastai and will not work in a CPU environment.\n\nPlease update the fastai library in your training environment and export your model again.\n\nSee instructions for 'Returning to work' at https://course.fast.ai."
            raise RuntimeError(message)
        else:
            raise


loop = asyncio.get_event_loop()
tasks = [asyncio.ensure_future(setup_learner())]
learn = loop.run_until_complete(asyncio.gather(*tasks))[0]
loop.close()


@app.route('/')
async def homepage(request):
    html_file = path / 'view' / 'index.html'
    return HTMLResponse(html_file.open().read())


@app.route('/analyze', methods=['POST'])
async def analyze(request):
    img_data = await request.form()
    img_bytes = await (img_data['file'].read())
    img = open_image(BytesIO(img_bytes))
    prediction = learn.predict(img)[0]
    return JSONResponse({'result': str(prediction)})


if __name__ == '__main__':
    if 'serve' in sys.argv:
        uvicorn.run(app=app, host='0.0.0.0', port=5000, log_level="info")
Example #28
0
import logging
import os
import uvicorn
from main import app

LOG = logging.getLogger(__name__)

HOST = os.getenv('HOST', '0.0.0.0')
PORT = int(os.getenv('PORT', '80'))

if __name__ == '__main__':

    env_string = F"HOST={HOST}\nPORT={PORT}\n"

    logging.basicConfig(
        level=logging.INFO,
        format=
        '%(asctime)s.%(msecs)03d|%(name)-12s|%(levelname)-8s| %(message)s',
        datefmt='%m-%d %H:%M:%S')

    LOG.info(F"Environmnet Vars:\n{env_string}")

    uvicorn.run(app, host=HOST, port=PORT)
Example #29
0
    model_fit = model.fit(disp=0)
    fc, se, conf = model_fit.forecast(1)
    diff = fc - last_day
    return fc, diff


def overall(ticker):
    df, last_day = data(ticker)
    order = best_order(df)
    fc, diff = model(df, order, last_day)
    return last_day, fc, diff


app = FastAPI()


@app.get('/')
def index():
    return {'message': 'Hello!'}


@app.post('/predict')
async def predict_price(ticker: str):

    last_day, fc, diff = overall(ticker)
    return {'prediction': fc[0], 'difference:': diff[0]}


if __name__ == '__main__':
    uvicorn.run(app, host='127.0.0.1', port=8000)
Example #30
0
def start():
    if os.path.exists("./.temp") is False:
        os.mkdir("./.temp")
    if os.path.exists("./.serve") is False:
        os.mkdir("./.serve")
    uvicorn.run("main:app", host="0.0.0.0", port=8000, reload=True)
Example #31
0
import uvicorn

import engineio

eio = engineio.AsyncServer(async_mode='asgi')
app = engineio.ASGIApp(eio, static_files={
    '/': {'content_type': 'text/html', 'filename': 'simple.html'},
    '/static/engine.io.js': {'content_type': 'application/javascript',
                             'filename': 'static/engine.io.js'}
})


@eio.on('connect')
def connect(sid, environ):
    print("connect ", sid)


@eio.on('message')
async def message(sid, data):
    print('message from', sid, data)
    await eio.send(sid, 'Thank you for your message!', binary=False)


@eio.on('disconnect')
def disconnect(sid):
    print('disconnect ', sid)


if __name__ == '__main__':
    uvicorn.run(app, host='127.0.0.1', port=5000)
Example #32
0
To use these interactive docs:
- Click on an endpoint below
- Click the **Try it out** button
- Edit the Request body or any parameters
- Click the **Execute** button
- Scroll down to see the Server response Code & Details
"""

app = FastAPI(
    title='DS API',
    description=description,
    docs_url='/',
)

app.include_router(db.router, tags=['Database'])
app.include_router(ml.router, tags=['Machine Learning'])
app.include_router(external.router, tags=['External Resources'])
app.include_router(viz.router, tags=['Visualizations'])

app.add_middleware(
    CORSMiddleware,
    allow_origins=['*'],
    allow_credentials=True,
    allow_methods=['*'],
    allow_headers=['*'],
)

if __name__ == '__main__':
    uvicorn.run(app)
Example #33
0
app = FastAPI()

origins = [
    "http://localhost",
    "http://*****:*****@app.get("/")
async def main():
    return {"message": "Hello World"}

app.include_router(label_sys.router)
app.include_router(task.router)
app.include_router(document.router)
app.include_router(users.router)

if __name__ == "__main__":
    uvicorn.run(app='main:app', host="0.0.0.0", port=9000, reload=True, debug=False)
Example #34
0
            raise GraphQLError("Invalid credentials")
        user = crud.get_user_by_username(db, username=token_data.username)
        if user is None:
            raise GraphQLError("Invalid credentials")
        AnimeSearch = route_optima_search(query, title, str(title))
        return SearchAnime(AnimeSearch=AnimeSearch)


class MyMutations(graphene.ObjectType):
    user = CreateUser.Field()
    authen_user = AuthenUser.Field()
    get_anime_list = GetAnimeList.Field()
    search_anime = SearchAnime.Field()


app = FastAPI()
origins = ["http://localhost", "http://localhost:4200"]
app.add_middleware(
    CORSMiddleware,
    allow_origins=origins,
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)
app.add_route(
    "/graphql",
    GraphQLApp(schema=graphene.Schema(query=Query, mutation=MyMutations)))

if __name__ == "__main__":
    uvicorn.run(app, host="127.0.0.1", port=8000)
Example #35
0
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)
    learn.load(model_file_name)
    return learn

loop = asyncio.get_event_loop()
tasks = [asyncio.ensure_future(setup_learner())]
learn = loop.run_until_complete(asyncio.gather(*tasks))[0]
loop.close()

@app.route('/')
def index(request):
    html = path/'view'/'index.html'
    return HTMLResponse(html.open().read())

@app.route('/analyze', methods=['POST'])
async def analyze(request):
    data = await request.form()
    img_bytes = await (data['file'].read())
    img = open_image(BytesIO(img_bytes))
    prediction = learn.predict(img)[0]
    return JSONResponse({'result': str(prediction)})

if __name__ == '__main__':
    if 'serve' in sys.argv: uvicorn.run(app, host='0.0.0.0', port=5042)

Example #36
0
from flask import Flask, render_template, request
import requests as rq
import argparse as argp
import uvicorn

parser = argp.ArgumentParser()
parser.add_argument('-n', '--host', type=str, default='0.0.0.0')
parser.add_argument('-p', '--port', type=int, default=5000)
parser.add_argument('-l', '--log-level', type=str, default='info')
args = parser.parse_args()

app = Flask(__name__)

@app.route('/', methods=['GET', 'POST'])
def index():
    data = {'encode': 'UTC-8'}
    if request.method == 'POST':
        url = request.form['url']
        res = rq.get(url)
        res.encoding = res.apparent_encoding 
        data['html'] = res.text
        data['encode'] = request.form['encode']
        print(url)

    return render_template('index.html', **data)

if __name__ == '__main__':
    uvicorn.run(app, host=args.host, port=args.port, log_level=args.log_level, interface='wsgi', lifespan='off')