Есть ли способ явно установить типы MIME для Starlette / Uvicorn? - PullRequest
0 голосов
/ 17 февраля 2020

Похоже, что мое простое веб-приложение Starlette / Uvicorn обслуживает неверный тип содержимого MIME для шаблонизированных файлов Jinja (обслуживаемых с того же сервера) JavaScript. Как вы можете видеть на снимке экрана, сервер uvicorn использует тип файла *. js как тип («text / plain»).

Снимок экрана

I Я просмотрел документы для Starlette и Uvicorn, и я просто в тупике.

Мое простое веб-приложение выглядит следующим образом:

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

port = randint(49152,65535)

templates = Jinja2Templates(directory='templates')


app = Starlette(debug=True)
app.mount('/static', StaticFiles(directory='statics', html=True), name='static')
app.add_middleware(
    CORSMiddleware, allow_origins=["*"], allow_headers=["*"], allow_methods=["*"]
)

@app.route('/')
async def homepage(request):
    template = "index.html"
    context = {"request": request}
    return templates.TemplateResponse(template, context, media_type='text/html')


@app.route('/error')
async def error(request):
    """
    An example error. Switch the `debug` setting to see either tracebacks or 500 pages.
    """
    raise RuntimeError("Oh no")


@app.exception_handler(404)
async def not_found(request, exc):
    """
    Return an HTTP 404 page.
    """
    template = "404.html"
    context = {"request": request}
    return templates.TemplateResponse(template, context, status_code=404)


@app.exception_handler(500)
async def server_error(request, exc):
    """
    Return an HTTP 500 page.
    """
    template = "500.html"
    context = {"request": request}
    return templates.TemplateResponse(template, context, status_code=500)


if __name__ == "__main__":
    uvicorn.run("app-567:app", host='0.0.0.0', port=port, log_level="info", http='h11', loop='asyncio', reload=True)

Файлы JavaScript, загруженные в головку, выдают ту же ошибку, но, тем не менее, загружаются. Это побочный продукт новой настройки по умолчанию 'nosniff' в Firefox (73.0 64-bit). Скрипты, которые загружаются при импорте модулей, сразу перестают работать.

Я бегу Windows 10 (x64), Python 3.7, uvicorn 0.11.2 и starlette 0.13.1.

Любая помощь очень ценится. Заранее спасибо.

1 Ответ

0 голосов
/ 18 февраля 2020

Мне удалось решить эту проблему, явно указав переменные mimetypes следующим образом:

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

import mimetypes
mimetypes.init()

port = randint(49152,65535)

templates = Jinja2Templates(directory='templates')


app = Starlette(debug=True)
app.mount('/static', StaticFiles(directory='statics', html=True), name='static')
app.add_middleware(
    CORSMiddleware, allow_origins=["*"], allow_headers=["*"], allow_methods=["*"]
)

@app.route('/')
async def homepage(request):
    mimetypes.add_type('application/javascript', '.js')
    mimetypes.add_type('text/css', '.css')
    mimetypes.add_type('image/svg+xml', '.svg')
    template = "index.html"
    context = {"request": request}
    return templates.TemplateResponse(template, context, media_type='text/html')


@app.route('/error')
async def error(request):
    """
    An example error. Switch the `debug` setting to see either tracebacks or 500 pages.
    """
    raise RuntimeError("Oh no")


@app.exception_handler(404)
async def not_found(request, exc):
    """
    Return an HTTP 404 page.
    """
    template = "404.html"
    context = {"request": request}
    return templates.TemplateResponse(template, context, status_code=404)


@app.exception_handler(500)
async def server_error(request, exc):
    """
    Return an HTTP 500 page.
    """
    template = "500.html"
    context = {"request": request}
    return templates.TemplateResponse(template, context, status_code=500)


if __name__ == "__main__":
    uvicorn.run("app-567:app", host='0.0.0.0', port=port, log_level="info", http='h11', loop='asyncio', reload=True)
...