示例#1
0
    def test_serves(self):
        whitenoise = WhiteNoise(None, autorefresh=True)
        whitenoise.add_files(
            static.resolver.resolve("warehouse:/static/dist/").abspath(),
            prefix="/static/",
        )

        path, headers = (whitenoise.find_file("/static/manifest.json")
                                   .get_path_and_headers({}))
        headers = dict(headers)

        response = pretend.stub()
        handler = pretend.call_recorder(lambda request: response)
        registry = pretend.stub(whitenoise=whitenoise)

        request = pretend.stub(
            method="GET",
            environ={},
            path_info="/static/manifest.json",
            registry=registry,
        )

        tween = static.whitenoise_tween_factory(handler, registry)
        resp = tween(request)

        assert resp.status_code == 200
        assert resp.headers["Content-Type"] == "application/json"
        assert resp.headers["Cache-Control"] == "public, max-age=60"
        assert resp.headers["Vary"] == "Accept-Encoding"

        with open(path, "rb") as fp:
            assert resp.body == fp.read()
示例#2
0
class Statics(object):
    preload = True

    def __init__(self, root_dir: str=None) -> None:
        assert whitenoise is not None, 'whitenoise must be installed.'
        from whitenoise import WhiteNoise
        self.whitenoise = WhiteNoise(application=None, root=root_dir)
        self.whitenoise.add_files(PACKAGE_STATICS, prefix='apistar')

    @classmethod
    def build(cls, settings: Settings):
        root_dir = settings.get(['STATICS', 'DIR'])
        return cls(root_dir)
示例#3
0
    def test_bypasses(self, autorefresh):
        whitenoise = WhiteNoise(None, autorefresh=autorefresh)
        whitenoise.add_files(
            static.resolver.resolve("warehouse:/static/dist/").abspath(),
            prefix="/static/",
        )

        response = pretend.stub()
        handler = pretend.call_recorder(lambda request: response)
        registry = pretend.stub(whitenoise=whitenoise)

        request = pretend.stub(path_info="/other/", registry=registry)

        tween = static.whitenoise_tween_factory(handler, registry)
        resp = tween(request)

        assert resp is response
示例#4
0
def _create_whitenoise(app, config):
    wh_config = config.registry.settings.get("whitenoise", {}).copy()
    if wh_config:
        # Create our Manifest immutable file checker.
        manifest = ImmutableManifestFiles()
        for manifest_spec, prefix in config.registry.settings.get(
            "whitenoise.manifests", []
        ):
            manifest.add_manifest(manifest_spec, prefix)

        # Wrap our WSGI application with WhiteNoise
        app = WhiteNoise(app, **wh_config, immutable_file_test=manifest)

        # Go through and add all of the files we were meant to add.
        for path, kwargs in config.registry.settings.get("whitenoise.files", []):
            app.add_files(resolver.resolve(path).abspath(), **kwargs)

    return app
示例#5
0
    def test_method_not_allowed(self, autorefresh):
        whitenoise = WhiteNoise(None, autorefresh=autorefresh)
        whitenoise.add_files(
            static.resolver.resolve("warehouse:/static/dist/").abspath(),
            prefix="/static/",
        )

        response = pretend.stub()
        handler = pretend.call_recorder(lambda request: response)
        registry = pretend.stub(whitenoise=whitenoise)

        request = pretend.stub(
            method="POST",
            environ={"HTTP_ACCEPT_ENCODING": "gzip"},
            path_info="/static/manifest.json",
            registry=registry,
        )

        tween = static.whitenoise_tween_factory(handler, registry)
        resp = tween(request)

        assert resp.status_code == 405
示例#6
0
from os.path import join

from flask import Flask, render_template
from flask_assets import Bundle, Environment
from webassets.filter import register_filter
from webassets_elm import Elm
from whitenoise import WhiteNoise

# create app
app = Flask('cunhajacaiu')
app.config.from_object('cunhajacaiu.settings')

# config whitenoise
imgs = join(app.config['BASEDIR'], 'cunhajacaiu', 'static', 'imgs')
wsgi = WhiteNoise(app)
for dir in ('css', 'imgs', 'js'):
    wsgi.add_files(join(app.config['STATIC_PATH'], dir), prefix=dir)

# create assets
register_filter(Elm)
assets = Environment(app)

css = Bundle(
    'sass/app.sass',
    depends=('**/*.sass',),
    filters=('libsass',),
    output='css/app.css'
)
elm = Bundle(
    'elm/Main.elm',
    depends=('**/*.elm',),
示例#7
0
import eventlet
from flask import Flask
from flask import render_template
from flask_socketio import SocketIO
from flask_socketio import disconnect, emit
from whitenoise import WhiteNoise
import time


eventlet.monkey_patch()


app = Flask(__name__)
app.wsgi_app = WhiteNoise(app.wsgi_app, root="static/")
app.config['SECRET_KEY'] = 'Intel'
socketio = SocketIO(app=app)


COUNT = 0


@app.route("/", methods=["GET"])
def index():
    """Send HTML file"""
    return render_template("index.html")


@socketio.on("connect")
def handle_connect():
    """
    Send current count to html page when anyone connect.
示例#8
0
文件: api.py 项目: knoguchi/responder
    def __init__(
        self,
        *,
        debug=False,
        title=None,
        version=None,
        description=None,
        terms_of_service=None,
        contact=None,
        license=None,
        openapi=None,
        openapi_route="/schema.yml",
        static_dir="static",
        static_route="/static",
        templates_dir="templates",
        auto_escape=True,
        secret_key=DEFAULT_SECRET_KEY,
        enable_hsts=False,
        docs_route=None,
        cors=False,
        cors_params=DEFAULT_CORS_PARAMS,
        allowed_hosts=None,
    ):
        self.background = BackgroundQueue()

        self.secret_key = secret_key
        self.title = title
        self.version = version
        self.description = description
        self.terms_of_service = terms_of_service
        self.contact = contact
        self.license = license
        self.openapi_version = openapi

        if static_dir is not None:
            if static_route is None:
                static_route = static_dir
            static_dir = Path(os.path.abspath(static_dir))

        self.static_dir = static_dir
        self.static_route = static_route

        self.built_in_templates_dir = Path(
            os.path.abspath(os.path.dirname(__file__) + "/templates"))

        if templates_dir is not None:
            templates_dir = Path(os.path.abspath(templates_dir))

        self.templates_dir = templates_dir or self.built_in_templates_dir

        self.apps = {}
        self.routes = {}
        self.before_requests = {"http": [], "ws": []}
        self.docs_theme = DEFAULT_API_THEME
        self.docs_route = docs_route
        self.schemas = {}
        self.session_cookie = DEFAULT_SESSION_COOKIE

        self.hsts_enabled = enable_hsts
        self.cors = cors
        self.cors_params = cors_params
        self.debug = debug

        if not allowed_hosts:
            # if not debug:
            #     raise RuntimeError(
            #         "You need to specify `allowed_hosts` when debug is set to False"
            #     )
            allowed_hosts = ["*"]
        self.allowed_hosts = allowed_hosts

        # Make the static/templates directory if they don't exist.
        for _dir in (self.static_dir, self.templates_dir):
            if _dir is not None:
                os.makedirs(_dir, exist_ok=True)

        if self.static_dir is not None:
            self.whitenoise = WhiteNoise(application=self._notfound_wsgi_app)
            self.whitenoise.add_files(str(self.static_dir))

            self.whitenoise.add_files(
                (Path(apistar.__file__).parent / "themes" / self.docs_theme /
                 "static").resolve())

            self.mount(self.static_route, self.whitenoise)

        self.formats = get_formats()

        # Cached requests session.
        self._session = None

        if self.openapi_version:
            self.add_route(openapi_route, self.schema_response)

        if self.docs_route:
            self.add_route(self.docs_route, self.docs_response)

        self.default_endpoint = None
        self.app = self.asgi
        self.add_middleware(GZipMiddleware)

        if self.hsts_enabled:
            self.add_middleware(HTTPSRedirectMiddleware)

        self.add_middleware(TrustedHostMiddleware,
                            allowed_hosts=self.allowed_hosts)

        self.lifespan_handler = Lifespan()

        if self.cors:
            self.add_middleware(CORSMiddleware, **self.cors_params)
        self.add_middleware(ServerErrorMiddleware, debug=debug)

        # Jinja environment
        self.jinja_env = jinja2.Environment(
            loader=jinja2.FileSystemLoader(
                [str(self.templates_dir),
                 str(self.built_in_templates_dir)],
                followlinks=True,
            ),
            autoescape=jinja2.select_autoescape(
                ["html", "xml"] if auto_escape else []),
        )
        self.jinja_values_base = {"api": self}  # Give reference to self.
        self.requests = (
            self.session()
        )  #: A Requests session that is connected to the ASGI app.
示例#9
0
    path('redstoneideas/', viewIdea),

    path('ads.txt', ads)
]


if settings.DEBUG:
    import os
    from django.conf.urls.static import static

    print(os.path.join(settings.LOCAL_STATIC_CDN_PATH, 'static'))

    urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
    urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
else:
    import os

    from django.conf import settings
    from django.core.wsgi import get_wsgi_application
    from whitenoise import WhiteNoise

    os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'django_blog.settings')

    WhiteNoise.autorefresh = True

    application = WhiteNoise(
        application=get_wsgi_application(),
        root=settings.MEDIA_ROOT,
        prefix=settings.MEDIA_URL
    )
示例#10
0
"""
WSGI config for the project.

It exposes the WSGI callable as a module-level variable named ``application``.

For more information on this file, see
https://docs.djangoproject.com/en/1.8/howto/deployment/wsgi/
"""

import os

from django.core.wsgi import get_wsgi_application
from django.conf import settings
from whitenoise import WhiteNoise

# Use our production settings as our default settings, which is most secure
os.environ.setdefault(
    "DJANGO_SETTINGS_MODULE",
    "twilio_sample_project.settings.production")

# Get a WSGI application for our project
application = get_wsgi_application()

# Use Whitenoise to serve static files
# See: https://whitenoise.readthedocs.org/
application = WhiteNoise(application, root=settings.STATIC_ROOT)
示例#11
0
import os
import sys
from whitenoise import WhiteNoise
from app.start import app
from config import storage

application = WhiteNoise(app, root='storage/static')

for location, alias in storage.STATICFILES.iteritems():
    application.add_files(location, prefix=alias)
示例#12
0
import os

from bottle import Bottle, response
from whitenoise import WhiteNoise

from ..settings import DATA_PATH

api = Bottle()


@api.hook('after_request')
def enable_cors():
    response.headers['Access-Control-Allow-Origin'] = '*'
    response.headers['Access-Control-Allow-Methods'] = 'GET, POST, DELETE'


application = WhiteNoise(api)
application.add_files(os.path.join(DATA_PATH, 'thumbnails'),
                      prefix='thumbnails/')
application.add_files(os.path.join(DATA_PATH, 'medias'), prefix='medias/')
示例#13
0
# only for local testing via $ heroku local web
#config_name = os.environ.get('FLASK_CONFIG') or 'production'

config_name = os.environ.get('FLASK_CONFIG') or 'production_heroku'
#config_name = os.environ.get('production_heroku')

print(config_name)


from app import create_app, db
from app.models import User

# creating app instance
application = create_app(config_name)

#test print out to confirm config settings
print"CONFIG SETTINGS FOR VIDEO UPLOAD: "
print(application.config["ALLOWED_EXTENSIONS"])
print(application.config["UPLOAD_FOLDER"])
print(application.config["MAX_CONTENT_LENGTH"])


#application = app()
application = WhiteNoise(application, root='/app/static/')

print(application)

application.add_files('/path/to/more/static/files', prefix='more-files/')

示例#14
0
    status = '404 Not Found'
    response_headers = [
        ('Content-Type', 'text/plain'),
        ('Content-Length', str(len(response_body))),
    ]
    start_response(status, response_headers)
    return [response_body.encode()]


# Wrap the 404 responder above around a static file handler (Whitenoise)
# This will intercept requests for serve static files and serve them if found
# If not found, it will default to the 404 response
APP = WhiteNoise(
    application_404,
    root=STATIC_FILE_DIR,
    index_file=True,
    mimetypes=MIME_TYPES,
    max_age=ONE_DAY,
    autorefresh=AUTO_REFRESH,
)


# Define the lambda event handler to route all requests through the app above
def lambda_handler(event, context):
    return awsgi.response(APP,
                          event,
                          context,
                          base64_content_types=BASE64_CONTENT_TYPES)


# Define local testing environment:  AUTO_REFRESH=True python app.py
if __name__ == '__main__':
示例#15
0
 def test_immutable_file_test_accepts_regex(self):
     instance = WhiteNoise(None, immutable_file_test=r'\.test$')
     self.assertTrue(instance.immutable_file_test('', '/myfile.test'))
     self.assertFalse(instance.immutable_file_test('', 'file.test.txt'))
示例#16
0
import os
import sys
# Set up paths and environment variables
sys.path.append(os.getcwd())
os.environ['DJANGO_SETTINGS_MODULE'] = 'multicassa.settings'
import django.core.handlers.wsgi
from django.core.wsgi import get_wsgi_application
from whitenoise import WhiteNoise
SCRIPT_NAME = 'multicassa/wsgi.py'
SCRIPT_NAME = '' #solution for damn link problem
class PassengerPathInfoFix(object):
    def __init__(self, app):
        self.app = app
    def __call__(self, environ, start_response):
        from urllib.parse import unquote
        environ['SCRIPT_NAME'] = SCRIPT_NAME
        request_uri = unquote(environ['REQUEST_URI'])
        script_name = unquote(environ.get('SCRIPT_NAME', ''))
        offset = request_uri.startswith(script_name) and len(environ['SCRIPT_NAME']) or 0
        environ['PATH_INFO'] = request_uri[offset:].split('?', 1)[0]
        return self.app(environ, start_response)
application = get_wsgi_application()
application = PassengerPathInfoFix(application)
application = WhiteNoise(application, root='/home/multikas/multicassa/static')
示例#17
0
"""
WSGI config for OnboardingApp project.

It exposes the WSGI callable as a module-level variable named ``application``.

For more information on this file, see
https://docs.djangoproject.com/en/3.0/howto/deployment/wsgi/
"""

import os

from django.core.wsgi import get_wsgi_application
from whitenoise import WhiteNoise

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'OnboardingApp.settings')

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

application = WhiteNoise(application, root=os.path.join(BASE_DIR, 'root'))
示例#18
0
from waitress import serve
import os
from croma.wsgi import application
from whitenoise import WhiteNoise
import logging

if __name__ == '__main__':
    BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
    logger = logging.getLogger('waitress')
    logger.setLevel(logging.INFO)
    my_application = serve(application, listen='*:8000')
    application = WhiteNoise(my_application,
                             root=os.path.join(BASE_DIR, "static"))
示例#19
0
"""
WSGI config for askadev project.

It exposes the WSGI callable as a module-level variable named ``application``.

For more information on this file, see
https://docs.djangoproject.com/en/3.0/howto/deployment/wsgi/
"""

import os

from django.core.wsgi import get_wsgi_application
from whitenoise import WhiteNoise
from django.conf import settings
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'askadev.settings')

application = get_wsgi_application()
application = WhiteNoise(application, root=settings.STATIC_ROOT)
application.add_files(settings.STATIC_ROOT, prefix='more-files/')
示例#20
0
from whitenoise import WhiteNoise

# import variable app (Flask instanse) from file app.py
from app import app

# create WhiteNoise application as decorator of Flask application
application = WhiteNoise(app)

# connect WhiteNoise application with static files
application.add_files('static/', prefix='static/')
示例#21
0
"""
WSGI config for mics project.

This module contains the WSGI application used by Django's development server
and any production WSGI deployments. It should expose a module-level variable
named ``application``. Django's ``runserver`` and ``runfcgi`` commands discover
this application via the ``WSGI_APPLICATION`` setting.

Usually you will have the standard Django WSGI application here, but it also
might make sense to replace the whole Django WSGI application with a custom one
that later delegates to the Django one. For example, you could introduce WSGI
middleware here, or combine a Django application with an application of another
framework.

"""
import os


os.environ.setdefault("DJANGO_SETTINGS_MODULE", "mics.settings")
from django.core.wsgi import get_wsgi_application
from django.conf import settings
from whitenoise import WhiteNoise

application = get_wsgi_application()
application = WhiteNoise(application, root=settings.STATIC_ROOT)


if settings.STATICFILES_DIRS:
    application.add_files(os.pathsep.join(settings.STATICFILES_DIRS))
示例#22
0
"""
WSGI config for JellyBot project.

It exposes the WSGI callable as a module-level variable named ``application``.

For more information on this file, see
https://docs.djangoproject.com/en/2.2/howto/deployment/wsgi/
"""

import os

from django.core.wsgi import get_wsgi_application
from whitenoise import WhiteNoise

# Django
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'JellyBot.settings')

application = get_wsgi_application()
application = WhiteNoise(application, root='static')
示例#23
0
import os

from flask import Flask
from whitenoise import WhiteNoise

from app import create_app
from dotenv import load_dotenv

load_dotenv()

PROJECT_ROOT = os.path.dirname(os.path.abspath(__file__))
STATIC_ROOT = os.path.join(PROJECT_ROOT, 'app', 'static')
STATIC_URL = 'static/'

app = Flask('app')

create_app(app)
application = WhiteNoise(app, STATIC_ROOT, STATIC_URL)
示例#24
0
"""
WSGI server for server project.

It exposes the WSGI callable as a module-level variable named ``application``.

For more information on this file, see
https://docs.djangoproject.com/en/3.0/howto/deployment/wsgi/
"""

import os

from django.core.wsgi import get_wsgi_application
from whitenoise import WhiteNoise
#from whitenoise.django import DjangoWhiteNoise

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'server.settings.prod')

application = get_wsgi_application()
application = WhiteNoise(
    application, root='/home/ubuntu/srv/Chatt-project-backend/staticfiles')
#application = DjangoWhiteNoise(application)
示例#25
0
"""
WSGI config for DPMMain project.

It exposes the WSGI callable as a module-level variable named ``application``.

For more information on this file, see
https://docs.djangoproject.com/en/3.0/howto/deployment/wsgi/
"""

import os
from whitenoise import WhiteNoise
from django.core.wsgi import get_wsgi_application

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'DPMMain.settings')
application = get_wsgi_application()
application = WhiteNoise(application, root='DPMAPI')
application.add_files('DPMAPI', prefix='static/')
示例#26
0
        docs = db.collection(u'Models').document(u'IPOWERFAN').collection(
            u'Assets').stream()
        for doc in docs:
            dic = doc.to_dict()
            dic['id'] = doc.id
            assets.append(dic)

        return assets
    except google.cloud.exceptions.NotFound:
        return 'error'


updateAssetLists('IPOWERFAN001MPU', True)

app = Flask(__name__)
app.wsgi_app = WhiteNoise(app.wsgi_app)
my_static_folders = ('static/assets/js/', 'static/bower_components/')
for static in my_static_folders:
    app.wsgi_app.add_files(static)

data = pd.read_csv("data.csv")
data = data.drop(columns=['||__time'])
data = shuffle(data)
feature_cols = data.drop(['Normality', 'RUL'], axis=1).columns
X = data[feature_cols]
y = data.Normality

# split the data into test/train
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.20)
neigh = KNeighborsClassifier(n_neighbors=7)
neigh.fit(X_train, y_train)
import requests
from whitenoise import WhiteNoise
from gtts import gTTS

from flask import (Flask, flash, redirect, render_template, request,
                   send_from_directory, url_for)

import run_script

UPLOAD_FOLDER = './static/images/'
ALLOWED_EXTENSIONS = set(['jpg', 'jpeg', 'png'])
YANDEX_API_KEY = 'YOUR API KEY HERE'
SECRET_KEY = '7d441f27d441f27567d441f2b6176a'

app = Flask(__name__)
app.wsgi_app = WhiteNoise(app.wsgi_app, root='static/')
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
app.secret_key = SECRET_KEY


@app.route('/<path:path>')
def static_file(path):
    return app.send_static_file(path)


# check if file extension is right
def allowed_file(filename):
    return '.' in filename and \
           filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS

示例#28
0
def make_wsgi_app():
    passwd = {'admin': '123'}
    # BasicAuth applications
    create = BasicAuth(BlogCreate, 'www', passwd)
    update = BasicAuth(BlogUpdate, 'www', passwd)
    delete = BasicAuth(BlogDelete, 'www', passwd)

    # URL dispatching middleware
    dispatch = selector.Selector()
    dispatch.add('/', GET=BlogIndex)
    dispatch.prefix = '/article'
    dispatch.add('/add', GET=create, POST=create)
    dispatch.add('/{id:digits}', GET=BlogRead)
    dispatch.add('/{id:digits}/edit', GET=update, POST=update)
    dispatch.add('/{id:digits}/delete', GET=delete)

    return dispatch


if __name__ == '__main__':

    app = make_wsgi_app()

    from whitenoise import WhiteNoise
    app = WhiteNoise(app)
    app.add_files('./static/', prefix='static/')

    from paste.httpserver import serve
    serve(app, host='0.0.0.0', port=8000)
示例#29
0
For more information on this file, see
https://docs.djangoproject.com/en/2.0/howto/deployment/wsgi/
"""

import os

from django.core.wsgi import get_wsgi_application
from whitenoise import WhiteNoise

os.environ.setdefault("DJANGO_SETTINGS_MODULE", "smswebapp.settings")

application = get_wsgi_application()

# Only *after* the application is initialised above will the Django settings be available.
from django.conf import settings  # noqa: E402

whitenoise_params = {}

if settings.DEBUG:
    # In development (when DEBUG is True), enable the whitenoise autorefresh feature which will
    # check if the file has updated on disk before responding.
    whitenoise_params['autorefresh'] = True

application = WhiteNoise(
    application,
    root=settings.FRONTEND_APP_BUILD_DIR,
    prefix='/',
    index_file=True,
    **whitenoise_params,
)
示例#30
0
"""
WSGI config for fech project.

It exposes the WSGI callable as a module-level variable named ``application``.

For more information on this file, see
https://docs.djangoproject.com/en/2.2/howto/deployment/wsgi/
"""

import os

from django.core.wsgi import get_wsgi_application
from whitenoise import WhiteNoise

os.environ.setdefault("DJANGO_SETTINGS_MODULE", "fech.settings.dev")

application = get_wsgi_application()


application = WhiteNoise(application)
application.add_files('./static', prefix='static')
application.add_files('./media', prefix='media')
示例#31
0
文件: api.py 项目: knoguchi/responder
class API:
    """The primary web-service class.

        :param static_dir: The directory to use for static files. Will be created for you if it doesn't already exist.
        :param templates_dir: The directory to use for templates. Will be created for you if it doesn't already exist.
        :param auto_escape: If ``True``, HTML and XML templates will automatically be escaped.
        :param enable_hsts: If ``True``, send all responses to HTTPS URLs.
        :param title: The title of the application (OpenAPI Info Object)
        :param version: The version of the OpenAPI document (OpenAPI Info Object)
        :param description: The description of the OpenAPI document (OpenAPI Info Object)
        :param terms_of_service: A URL to the Terms of Service for the API (OpenAPI Info Object)
        :param contact: The contact dictionary of the application (OpenAPI Contact Object)
        :param license: The license information of the exposed API (OpenAPI License Object)
    """

    status_codes = status_codes

    def __init__(
        self,
        *,
        debug=False,
        title=None,
        version=None,
        description=None,
        terms_of_service=None,
        contact=None,
        license=None,
        openapi=None,
        openapi_route="/schema.yml",
        static_dir="static",
        static_route="/static",
        templates_dir="templates",
        auto_escape=True,
        secret_key=DEFAULT_SECRET_KEY,
        enable_hsts=False,
        docs_route=None,
        cors=False,
        cors_params=DEFAULT_CORS_PARAMS,
        allowed_hosts=None,
    ):
        self.background = BackgroundQueue()

        self.secret_key = secret_key
        self.title = title
        self.version = version
        self.description = description
        self.terms_of_service = terms_of_service
        self.contact = contact
        self.license = license
        self.openapi_version = openapi

        if static_dir is not None:
            if static_route is None:
                static_route = static_dir
            static_dir = Path(os.path.abspath(static_dir))

        self.static_dir = static_dir
        self.static_route = static_route

        self.built_in_templates_dir = Path(
            os.path.abspath(os.path.dirname(__file__) + "/templates"))

        if templates_dir is not None:
            templates_dir = Path(os.path.abspath(templates_dir))

        self.templates_dir = templates_dir or self.built_in_templates_dir

        self.apps = {}
        self.routes = {}
        self.before_requests = {"http": [], "ws": []}
        self.docs_theme = DEFAULT_API_THEME
        self.docs_route = docs_route
        self.schemas = {}
        self.session_cookie = DEFAULT_SESSION_COOKIE

        self.hsts_enabled = enable_hsts
        self.cors = cors
        self.cors_params = cors_params
        self.debug = debug

        if not allowed_hosts:
            # if not debug:
            #     raise RuntimeError(
            #         "You need to specify `allowed_hosts` when debug is set to False"
            #     )
            allowed_hosts = ["*"]
        self.allowed_hosts = allowed_hosts

        # Make the static/templates directory if they don't exist.
        for _dir in (self.static_dir, self.templates_dir):
            if _dir is not None:
                os.makedirs(_dir, exist_ok=True)

        if self.static_dir is not None:
            self.whitenoise = WhiteNoise(application=self._notfound_wsgi_app)
            self.whitenoise.add_files(str(self.static_dir))

            self.whitenoise.add_files(
                (Path(apistar.__file__).parent / "themes" / self.docs_theme /
                 "static").resolve())

            self.mount(self.static_route, self.whitenoise)

        self.formats = get_formats()

        # Cached requests session.
        self._session = None

        if self.openapi_version:
            self.add_route(openapi_route, self.schema_response)

        if self.docs_route:
            self.add_route(self.docs_route, self.docs_response)

        self.default_endpoint = None
        self.app = self.asgi
        self.add_middleware(GZipMiddleware)

        if self.hsts_enabled:
            self.add_middleware(HTTPSRedirectMiddleware)

        self.add_middleware(TrustedHostMiddleware,
                            allowed_hosts=self.allowed_hosts)

        self.lifespan_handler = Lifespan()

        if self.cors:
            self.add_middleware(CORSMiddleware, **self.cors_params)
        self.add_middleware(ServerErrorMiddleware, debug=debug)

        # Jinja environment
        self.jinja_env = jinja2.Environment(
            loader=jinja2.FileSystemLoader(
                [str(self.templates_dir),
                 str(self.built_in_templates_dir)],
                followlinks=True,
            ),
            autoescape=jinja2.select_autoescape(
                ["html", "xml"] if auto_escape else []),
        )
        self.jinja_values_base = {"api": self}  # Give reference to self.
        self.requests = (
            self.session()
        )  #: A Requests session that is connected to the ASGI app.

    @staticmethod
    def _default_wsgi_app(environ, start_response):
        pass

    @staticmethod
    def _notfound_wsgi_app(environ, start_response):
        start_response("404 NOT FOUND", [("Content-Type", "text/plain")])
        return [b"Not Found."]

    def before_request(self, websocket=False):
        def decorator(f):
            if websocket:
                self.before_requests.setdefault("ws", []).append(f)
            else:
                self.before_requests.setdefault("http", []).append(f)
            return f

        return decorator

    @property
    def before_http_requests(self):
        return self.before_requests.get("http", [])

    @property
    def before_ws_requests(self):
        return self.before_requests.get("ws", [])

    @property
    def _apispec(self):

        info = {}
        if self.description is not None:
            info["description"] = self.description
        if self.terms_of_service is not None:
            info["termsOfService"] = self.terms_of_service
        if self.contact is not None:
            info["contact"] = self.contact
        if self.license is not None:
            info["license"] = self.license

        spec = APISpec(
            title=self.title,
            version=self.version,
            openapi_version=self.openapi_version,
            plugins=[MarshmallowPlugin()],
            info=info,
        )

        for route in self.routes:
            if self.routes[route].description:
                operations = yaml_utils.load_operations_from_docstring(
                    self.routes[route].description)
                spec.path(path=route, operations=operations)

        for name, schema in self.schemas.items():
            spec.components.schema(name, schema=schema)

        return spec

    @property
    def openapi(self):
        return self._apispec.to_yaml()

    def add_middleware(self, middleware_cls, **middleware_config):
        self.app = middleware_cls(self.app, **middleware_config)

    async def __call__(self, scope, receive, send):
        if scope["type"] == "lifespan":
            await self.lifespan_handler(scope, receive, send)
            return

        path = scope["path"]
        root_path = scope.get("root_path", "")

        # Call into a submounted app, if one exists.
        for path_prefix, app in self.apps.items():
            if path.startswith(path_prefix):
                scope["path"] = path[len(path_prefix):]
                scope["root_path"] = root_path + path_prefix
                try:
                    await app(scope, receive, send)
                    return
                except TypeError:
                    app = WSGIMiddleware(app)
                    await app(scope, receive, send)
                    return

        await self.app(scope, receive, send)

    async def asgi(self, scope, receive, send):
        assert scope["type"] in ("http", "websocket")

        if scope["type"] == "websocket":
            await self._dispatch_ws(scope=scope, receive=receive, send=send)
        else:
            req = models.Request(scope, receive=receive, api=self)
            resp = await self._dispatch_http(req,
                                             scope=scope,
                                             send=send,
                                             receive=receive)
            await resp(scope, receive, send)

    async def _dispatch_http(self, req, **options):
        # Set formats on Request object.
        req.formats = self.formats

        # Get the route.
        route = self.path_matches_route(req.url.path)
        route = self.routes.get(route)
        if route:
            resp = models.Response(req=req, formats=self.formats)

            for before_request in self.before_http_requests:
                await self.background(before_request, req=req, resp=resp)

            await self._execute_route(route=route,
                                      req=req,
                                      resp=resp,
                                      **options)
        else:
            resp = models.Response(req=req, formats=self.formats)
            self.default_response(req=req, resp=resp, notfound=True)
        self.default_response(req=req, resp=resp)

        self._prepare_session(resp)

        return resp

    async def _dispatch_ws(self, scope, receive, send):
        ws = WebSocket(scope=scope, receive=receive, send=send)

        route = self.path_matches_route(ws.url.path)
        route = self.routes.get(route)

        if route:
            for before_request in self.before_ws_requests:
                await self.background(before_request, ws=ws)
            await self.background(route.endpoint, ws)
        else:
            await send({"type": "websocket.close", "code": 1000})

    def add_schema(self, name, schema, check_existing=True):
        """Adds a mashmallow schema to the API specification."""
        if check_existing:
            assert name not in self.schemas

        self.schemas[name] = schema

    def schema(self, name, **options):
        """Decorator for creating new routes around function and class definitions.

        Usage::

            from marshmallow import Schema, fields

            @api.schema("Pet")
            class PetSchema(Schema):
                name = fields.Str()

        """
        def decorator(f):
            self.add_schema(name=name, schema=f, **options)
            return f

        return decorator

    def path_matches_route(self, path):
        """Given a path portion of a URL, tests that it matches against any registered route.

        :param path: The path portion of a URL, to test all known routes against.
        """
        for (route, route_object) in self.routes.items():
            if route_object.does_match(path):
                return route

    @property
    def _signer(self):
        return itsdangerous.Signer(self.secret_key)

    def _prepare_session(self, resp):

        if resp.session:
            data = self._signer.sign(
                b64encode(json.dumps(resp.session).encode("utf-8")))
            resp.cookies[self.session_cookie] = data.decode("utf-8")

    @staticmethod
    def no_response(req, resp, **params):
        pass

    async def _execute_route(self, *, route, req, resp, **options):

        params = route.incoming_matches(req.url.path)

        cont = True

        if route.is_function:
            try:
                try:
                    # Run the view.
                    r = self.background(route.endpoint, req, resp, **params)
                    # If it's async, await it.
                    if hasattr(r, "cr_running"):
                        await r
                except TypeError as e:
                    cont = True
            except Exception:
                await self.background(self.default_response,
                                      req,
                                      resp,
                                      error=True)
                raise

        if route.is_class_based or cont:
            try:
                view = route.endpoint(**params)
            except TypeError:
                try:
                    view = route.endpoint()
                except TypeError:
                    view = route.endpoint
                    pass

            # Run on_request first.
            try:
                # Run the view.
                r = getattr(view, "on_request", self.no_response)
                r = self.background(r, req, resp, **params)
                # If it's async, await it.
                if hasattr(r, "send"):
                    await r
            except Exception:
                await self.background(self.default_response,
                                      req,
                                      resp,
                                      error=True)
                raise

            # Then run on_method.
            method = req.method
            try:
                # Run the view.
                r = getattr(view, f"on_{method}", self.no_response)
                r = self.background(r, req, resp, **params)
                # If it's async, await it.
                if hasattr(r, "send"):
                    await r
            except Exception:
                await self.background(self.default_response,
                                      req,
                                      resp,
                                      error=True)
                raise

    def add_event_handler(self, event_type, handler):
        """Adds an event handler to the API.

        :param event_type: A string in ("startup", "shutdown")
        :param handler: The function to run. Can be either a function or a coroutine.
        """

        self.lifespan_handler.add_event_handler(event_type, handler)

    def add_route(
        self,
        route=None,
        endpoint=None,
        *,
        default=False,
        static=False,
        check_existing=True,
        websocket=False,
        before_request=False,
    ):
        """Adds a route to the API.

        :param route: A string representation of the route.
        :param endpoint: The endpoint for the route -- can be a callable, or a class.
        :param default: If ``True``, all unknown requests will route to this view.
        :param static: If ``True``, and no endpoint was passed, render "static/index.html", and it will become a default route.
        :param check_existing: If ``True``, an AssertionError will be raised, if the route is already defined.
        """
        if before_request:
            if websocket:
                self.before_requests.setdefault("ws", []).append(endpoint)
            else:
                self.before_requests.setdefault("http", []).append(endpoint)
            return

        if route is None:
            route = f"/{uuid4().hex}"

        if check_existing:
            assert route not in self.routes

        if static:
            assert self.static_dir is not None
            if not endpoint:
                endpoint = self.static_response
                default = True

        if default:
            self.default_endpoint = endpoint

        self.routes[route] = Route(route, endpoint, websocket=websocket)
        # TODO: A better data structure or sort it once the app is loaded
        self.routes = dict(
            sorted(self.routes.items(), key=lambda item: item[1]._weight()))

    def default_response(self,
                         req=None,
                         resp=None,
                         websocket=False,
                         notfound=False,
                         error=False):
        if websocket:
            return

        if resp.status_code is None:
            resp.status_code = 200

        if self.default_endpoint and notfound:
            self.default_endpoint(req=req, resp=resp)
        else:
            if notfound:
                resp.status_code = status_codes.HTTP_404
                resp.text = "Not found."
            if error:
                resp.status_code = status_codes.HTTP_500
                resp.text = "Application error."

    def docs_response(self, req, resp):
        resp.html = self.docs

    def static_response(self, req, resp):

        assert self.static_dir is not None

        index = (self.static_dir / "index.html").resolve()
        if os.path.exists(index):
            with open(index, "r") as f:
                resp.html = f.read()
        else:
            resp.status_code = status_codes.HTTP_404
            resp.text = "Not found."

    def schema_response(self, req, resp):
        resp.status_code = status_codes.HTTP_200
        resp.headers["Content-Type"] = "application/x-yaml"
        resp.content = self.openapi

    def redirect(self,
                 resp,
                 location,
                 *,
                 set_text=True,
                 status_code=status_codes.HTTP_301):
        """Redirects a given response to a given location.

        :param resp: The Response to mutate.
        :param location: The location of the redirect.
        :param set_text: If ``True``, sets the Redirect body content automatically.
        :param status_code: an `API.status_codes` attribute, or an integer, representing the HTTP status code of the redirect.
        """

        # assert resp.status_code.is_300(status_code)

        resp.status_code = status_code
        if set_text:
            resp.text = f"Redirecting to: {location}"
        resp.headers.update({"Location": location})

    def on_event(self, event_type: str, **args):
        """Decorator for registering functions or coroutines to run at certain events
        Supported events: startup, shutdown

        Usage::

            @api.on_event('startup')
            async def open_database_connection_pool():
                ...

            @api.on_event('shutdown')
            async def close_database_connection_pool():
                ...

        """
        def decorator(func):
            self.add_event_handler(event_type, func, **args)
            return func

        return decorator

    def route(self, route=None, **options):
        """Decorator for creating new routes around function and class definitions.

        Usage::

            @api.route("/hello")
            def hello(req, resp):
                resp.text = "hello, world!"

        """
        def decorator(f):
            self.add_route(route, f, **options)
            return f

        return decorator

    def mount(self, route, app):
        """Mounts an WSGI / ASGI application at a given route.

        :param route: String representation of the route to be used (shouldn't be parameterized).
        :param app: The other WSGI / ASGI app.
        """
        self.apps.update({route: app})

    def session(self, base_url="http://;"):
        """Testing HTTP client. Returns a Requests session object, able to send HTTP requests to the Responder application.

        :param base_url: The URL to mount the connection adaptor to.
        """

        if self._session is None:
            self._session = TestClient(self, base_url=base_url)
        return self._session

    def _route_for(self, endpoint):
        for route_object in self.routes.values():
            if endpoint in (route_object.endpoint, route_object.endpoint_name):
                return route_object

    def url_for(self, endpoint, **params):
        # TODO: Absolute_url
        """Given an endpoint, returns a rendered URL for its route.

        :param endpoint: The route endpoint you're searching for.
        :param params: Data to pass into the URL generator (for parameterized URLs).
        """
        route_object = self._route_for(endpoint)
        if route_object:
            return route_object.url(**params)
        raise ValueError

    def static_url(self, asset):
        """Given a static asset, return its URL path."""
        assert None not in (self.static_dir, self.static_route)
        return f"{self.static_route}/{str(asset)}"

    @property
    def docs(self):

        loader = jinja2.PrefixLoader({
            self.docs_theme:
            jinja2.PackageLoader(
                "apistar", os.path.join("themes", self.docs_theme,
                                        "templates"))
        })
        env = jinja2.Environment(autoescape=True, loader=loader)
        document = apistar.document.Document()
        document.content = yaml.safe_load(self.openapi)

        template = env.get_template("/".join([self.docs_theme, "index.html"]))

        return template.render(
            document=document,
            langs=["javascript", "python"],
            code_style=None,
            static_url=self.static_url,
            schema_url="/schema.yml",
        )

    def template(self, name_, **values):
        """Renders the given `jinja2 <http://jinja.pocoo.org/docs/>`_ template, with provided values supplied.

        Note: The current ``api`` instance is by default passed into the view. This is set in the dict ``api.jinja_values_base``.

        :param name_: The filename of the jinja2 template, in ``templates_dir``.
        :param values: Data to pass into the template.
        """
        # Prepopulate values with base
        values = {**self.jinja_values_base, **values}

        template = self.jinja_env.get_template(name_)
        return template.render(**values)

    def template_string(self, s_, **values):
        """Renders the given `jinja2 <http://jinja.pocoo.org/docs/>`_ template string, with provided values supplied.

        Note: The current ``api`` instance is by default passed into the view. This is set in the dict ``api.jinja_values_base``.

        :param s_: The template to use.
        :param values: Data to pass into the template.
        """
        # Prepopulate values with base
        values = {**self.jinja_values_base, **values}

        template = self.jinja_env.from_string(s_)
        return template.render(**values)

    def serve(self, *, address=None, port=None, debug=False, **options):
        """Runs the application with uvicorn. If the ``PORT`` environment
        variable is set, requests will be served on that port automatically to all
        known hosts.

        :param address: The address to bind to.
        :param port: The port to bind to. If none is provided, one will be selected at random.
        :param debug: Run uvicorn server in debug mode.
        :param options: Additional keyword arguments to send to ``uvicorn.run()``.
        """

        if "PORT" in os.environ:
            if address is None:
                address = "0.0.0.0"
            port = int(os.environ["PORT"])

        if address is None:
            address = "127.0.0.1"
        if port is None:
            port = 5042

        def spawn():
            uvicorn.run(self, host=address, port=port, debug=debug, **options)

        spawn()

    def run(self, **kwargs):
        if "debug" not in kwargs:
            kwargs.update({"debug": self.debug})
        self.serve(**kwargs)
示例#32
0
"""
WSGI config for bhtom project.

It exposes the WSGI callable as a module-level variable named ``application``.

For more information on this file, see
https://docs.djangoproject.com/en/2.2/howto/deployment/wsgi/
"""

import os

from django.core.wsgi import get_wsgi_application
from django.conf import settings
from django.contrib.staticfiles.handlers import StaticFilesHandler

from whitenoise import WhiteNoise
 
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'bhtom.settings')

# if settings.DEBUG:
#     application = StaticFilesHandler(get_wsgi_application())
# else:
#     application = get_wsgi_application()

application = get_wsgi_application()
application = WhiteNoise(application, root='/Users/wyrzykow/bhtom/myapp/static')
#application.add_files('/path/to/more/static/files', prefix='more-files/')
示例#33
0
"""
WSGI config for devfolio project.

It exposes the WSGI callable as a module-level variable named ``application``.

For more information on this file, see
https://docs.djangoproject.com/en/3.0/howto/deployment/wsgi/
"""

import os
from django.core.wsgi import get_wsgi_application
from whitenoise import WhiteNoise

os.environ.setdefault("DJANGO_SETTINGS_MODULE", "devfolio.settings")

application = get_wsgi_application()
application = WhiteNoise(application)
示例#34
0
"""
WSGI config for keeper project.

It exposes the WSGI callable as a module-level variable named ``application``.

For more information on this file, see
https://docs.djangoproject.com/en/1.10/howto/deployment/wsgi/
"""

import os

from django.core.wsgi import get_wsgi_application
from whitenoise import WhiteNoise

os.environ.setdefault("DJANGO_SETTINGS_MODULE", "keeper.settings")

# for Heroku
application = WhiteNoise(get_wsgi_application())
示例#35
0
import os

from django.core.wsgi import get_wsgi_application
from whitenoise import WhiteNoise

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'config.settings.dev')

application = get_wsgi_application()

application = WhiteNoise(application, root='./staticfiles')
示例#36
0
 def register():
     config.registry.whitenoise = WhiteNoise(None, **kwargs)
示例#37
0
import os.path

from flask_sslify import SSLify
from werkzeug.contrib.fixers import ProxyFix
from whitenoise import WhiteNoise

from app.app import app


SSLify(app, permanent=True)
APP_ROOT = os.path.dirname(os.path.abspath(__file__))
wn_app = WhiteNoise(app.wsgi_app, root=os.path.join(APP_ROOT, 'static'), prefix='/static')
wn_app.add_files(root=os.path.join(APP_ROOT, 'root_files'), prefix='')
app.wsgi_app = wn_app

app.wsgi_app = ProxyFix(app.wsgi_app)
示例#38
0
 def test_immutable_file_test_accepts_regex(self):
     instance = WhiteNoise(None, immutable_file_test=r'\.test$')
     self.assertTrue(instance.immutable_file_test('', '/myfile.test'))
     self.assertFalse(instance.immutable_file_test('', 'file.test.txt'))
示例#39
0
 def __init__(self, root_dir: str=None) -> None:
     assert whitenoise is not None, 'whitenoise must be installed.'
     from whitenoise import WhiteNoise
     self.whitenoise = WhiteNoise(application=None, root=root_dir)
     self.whitenoise.add_files(PACKAGE_STATICS, prefix='apistar')
示例#40
0
 def test_directory_path_can_be_pathlib_instance(self):
     from pathlib import Path
     root = Path(Files('root').directory)
     # Check we can construct instance without it blowing up
     WhiteNoise(None, root=root, autorefresh=True)
示例#41
0
"""
WSGI config for investment_portfolio project.

It exposes the WSGI callable as a module-level variable named ``application``.

For more information on this file, see
https://docs.djangoproject.com/en/1.8/howto/deployment/wsgi/
"""

import os

from django.core.wsgi import get_wsgi_application
from whitenoise import WhiteNoise

os.environ.setdefault("DJANGO_SETTINGS_MODULE", "investment_portfolio.settings")

application = get_wsgi_application()

application = WhiteNoise(application, root='static')
application.add_files('staticfiles', prefix='more-files/')
示例#42
0
# app.py
from flask import *
from whitenoise import WhiteNoise

app = Flask(__name__)
app.wsgi_app = WhiteNoise(app.wsgi_app,
                          root='static/',
                          prefix='static/',
                          index_file="index.htm",
                          autorefresh=True)


@app.route('/', methods=['GET'])
def hello():
    return make_response("Hello, world!!!!!!!!!!!!!")


if __name__ == "__main__":
    app.run(threaded=True, port=5000)
示例#43
0
文件: manage.py 项目: dvelle/memegen
for name, command in [
    ('DEPLOY_DATE', "TZ=America/Detroit date '+%F %T'"),
]:
    output = subprocess.run(command, shell=True, stdout=subprocess.PIPE,
                            universal_newlines=True).stdout.strip() or "???"
    os.environ[name] = os.getenv(name, output)

# Configure the command-line interface
manager = Manager(_app)


@manager.command
def validate():
    if _app.template_service.validate():
        return 0
    else:
        return 1


manager.add_command('server', Server(host='0.0.0.0'))
manager.add_command('db', MigrateCommand)


app = WhiteNoise(_app)
app.add_files("data/images")
app.add_files("memegen/static")


if __name__ == '__main__':
    manager.run()
示例#44
0
from prototype_bootstrap_navbar import app
from whitenoise import WhiteNoise

application = WhiteNoise(app, root='/static')
if __name__ == "__main__":
    application.run()