U a*@sBdZddlZddlZddlZddlZddlZddlmZddlmZddl m Z ddl m Z ddl m Z dd lmZdd lmZdd lmZdd lmZdd lmZddlmZddlmZejgejejeeffZejeje gejeje ejeffZ!ej"r0ddl#m$Z$ddl#m%Z%ddl#m&Z&GdddZ'dS)z Serve Shared Static Files ========================= .. autoclass:: SharedDataMiddleware :members: is_allowed :copyright: 2007 Pallets :license: BSD-3-Clause N)datetime)timezone)BytesIO)time)adler32)get_filesystem_encoding) http_date)is_resource_modified) safe_join)get_content_type) get_path_info) wrap_file) StartResponse)WSGIApplication)WSGIEnvironmentc @seZdZdZddejejeejeejeefffej ejeejeejeeffffde e edddd Z ee d d d Z eed d dZeed ddZeeedddZeedddZee eedddZddej edddZdS) SharedDataMiddlewarea A WSGI middleware which provides static content for development environments or simple server setups. Its usage is quite simple:: import os from werkzeug.middleware.shared_data import SharedDataMiddleware app = SharedDataMiddleware(app, { '/shared': os.path.join(os.path.dirname(__file__), 'shared') }) The contents of the folder ``./shared`` will now be available on ``http://example.com/shared/``. This is pretty useful during development because a standalone media server is not required. Files can also be mounted on the root folder and still continue to use the application because the shared data middleware forwards all unhandled requests to the application, even if the requests are below one of the shared folders. If `pkg_resources` is available you can also tell the middleware to serve files from package data:: app = SharedDataMiddleware(app, { '/static': ('myapplication', 'static') }) This will then serve the ``static`` folder in the `myapplication` Python package. The optional `disallow` parameter can be a list of :func:`~fnmatch.fnmatch` rules for files that are not accessible from the web. If `cache` is set to `False` no caching headers are sent. Currently the middleware does not support non-ASCII filenames. If the encoding on the file system happens to match the encoding of the URI it may work but this could also be by accident. We strongly suggest using ASCII only file names for static files. The middleware will guess the mimetype using the Python `mimetype` module. If it's unable to figure out the charset it will fall back to `fallback_mimetype`. :param app: the application to wrap. If you don't want to wrap an application you can pass it :exc:`NotFound`. :param exports: a list or dict of exported files and folders. :param disallow: a list of :func:`~fnmatch.fnmatch` rules. :param cache: enable or disable caching headers. :param cache_timeout: the cache timeout in seconds for the headers. :param fallback_mimetype: The fallback mimetype for unknown files. .. versionchanged:: 1.0 The default ``fallback_mimetype`` is ``application/octet-stream``. If a filename looks like a text mimetype, the ``utf-8`` charset is added to it. .. versionadded:: 0.6 Added ``fallback_mimetype``. .. versionchanged:: 0.5 Added ``cache_timeout``. NTapplication/octet-streamr)appexportsdisallowcache cache_timeoutfallback_mimetypereturnc s||_g|_||_||_t|tr*|}|D]j\}}t|trL|j|} nz/SharedDataMiddleware.__init__..)rrrr isinstancedictitemstupleget_package_loaderstrospathisfileget_file_loaderget_directory_loader TypeErrorappendr is_allowedr) selfrrrrrrkeyvalueloaderrr!r"__init__es&          zSharedDataMiddleware.__init__)filenamercCsdS)zSubclasses can override this method to disallow the access to certain files. However by providing `disallow` in the constructor this method is overwritten. Trr3r8rrr"r2szSharedDataMiddleware.is_allowedcs fddS)Ncs0tdtjtjtjdttj fS)Nrbtz) openr fromtimestampr+r,getmtimerutcintgetsizerr8rr"r#sz.SharedDataMiddleware._opener..rr9rrCr"_openerszSharedDataMiddleware._openercsfddS)NcstjfSr)r+r,basenamerDrr8r3rr"r#r$z6SharedDataMiddleware.get_file_loader..rr9rrFr"r.sz$SharedDataMiddleware.get_file_loader)package package_pathrcsttjt|tdr`|tj t tj tj t tj t fdfdd }nd |}tj|tjtj|tj t tj tj t tj t fdfdd }|S)Nget_resource_readerr,rcs~|dkr dSt|}|dkr"dSt|}z|Wntk rPYdSXttrn|fddfS|fddfS)NNNcstfSr)lengetvaluer) load_timeresourcerr"r#r$ISharedDataMiddleware.get_package_loader..loader..cs*tjtjjtjdtjjfS)Nr;) rr>r+r,r?namerr@rBrrOrr"r#s  )r posixpathrE open_resourceOSErrorr%rr,rE)rNrHreaderrRr"r6s"     z7SharedDataMiddleware.get_package_loader..loadercs|dkr dSt|}|dkr"dSt|}rNtj|s@dS||fSz|Wntk rrYdSX|fddfS)NrKcsttfSr)rrLr)datarNrr"r#r$rP) r rSrEr+r,r-rDget_datarUrV) is_filesystemrNproviderrootr3)rXr"r6s   )rnowrr@pkgutil get_loaderhasattrrItOptionalr*Tuple_TOpener get_filenamer+r,existsjoindirname)r3rGrHr6Zpackage_filenamer)rZrNrHr[rWr\r3r"r)s    %  z'SharedDataMiddleware.get_package_loader) directoryrcs6tjttjtjttjtfdfdd }|S)NrJcsJ|dk r t|}|dkr$dSn}tj|rFtj||fSdS)NrK)r r+r,r-rErD)r,rir3rr"r6s  z9SharedDataMiddleware.get_directory_loader..loader)rarbr*rcrd)r3rir6rrjr"r/sz)SharedDataMiddleware.get_directory_loader)mtime file_size real_filenamercCs@t|ts|t}|}t|d@}d|d|d|S)Nlzwzsdm--)r%bytesencoder timestampr)r3rkrlrmrqZchecksumrrr" generate_etags  z"SharedDataMiddleware.generate_etagrr)environstart_responsercCst|}d}|jD]h\}}||kr:|d\}}|dk r:q||dsL|d7}||r||t|d\}}|dk rq|q|dks||s|||St|}t |dp|j d} |\} } } dt fg} |j rP|j }|| | |}| dd|dfdd|d fg7} t||| d s6| |d | gS| d t t|fn | d | d| fdt| fdt | ff|d| t|| S)N/rzutf-8DateZEtag" Cache-Controlzmax-age=z, public)Z last_modifiedz304 Not ModifiedZExpires)rxpublicz Content-TypezContent-Lengthz Last-Modifiedz200 OK)r rendswith startswithrLr2r mimetypes guess_typer rr rrrrr closer1rextendr*r)r3rsrtr,Z file_loader search_pathr6rmZ guessed_typeZ mime_typefrkrlheaderstimeoutetagrrr"__call__sP            zSharedDataMiddleware.__call__)NTrr)__name__ __module__ __qualname____doc__raUnionDictr*rcIterableboolrAr7r2rdrD_TLoaderr.r)r/rrrrorrrrr"r's8C & (M r)(rr|r+r^rStypingrarriorrzlibr filesystemrhttpr r securityr utilsr Zwsgir rCallablercBinaryIOrArdrbr*r TYPE_CHECKINGZ_typeshed.wsgirrrrrrrr"s0             ,