pax_global_header00006660000000000000000000000064133600550630014513gustar00rootroot0000000000000052 comment=f1a275e73763d16a9dba45e2bd568860302786bd python-multipart-0.0.5/000077500000000000000000000000001336005506300150555ustar00rootroot00000000000000python-multipart-0.0.5/.coveragerc000066400000000000000000000013121336005506300171730ustar00rootroot00000000000000# This file contains settings for coverage.py [run] # Change to True some day? branch = False # branch = True omit = *six.py multipart/tests/* [report] # Regexes for lines to exclude from consideration exclude_lines = # Re-enable the standard pragma pragma: no cover # Ignore defensive assertions raise NotImplementedError # Ignore debugging representations. def __str__ def __repr__ # Exclude code that can't be executed. if 0: if False: if __name__ == .__main__.: # Exclude stuff for debugging if self\.config\['DEBUG'\]: if self\.debug: # Ignore import exceptions except ImportError: # Ignore python compatibility. if PY3 python-multipart-0.0.5/.gitignore000066400000000000000000000012451336005506300170470ustar00rootroot00000000000000# Project-specific ignores. venv/ tmp/ # Parts below taken from GitHub's gitignores repository: https://github.com/github/gitignore *.py[cod] # C extensions *.so # Packages *.egg *.egg-info MANIFEST dist /build eggs parts bin var sdist develop-eggs .installed.cfg lib lib64 # Installer logs pip-log.txt # Unit test / coverage reports .coverage .tox nosetests.xml # CTags files tags #Translations *.mo #Mr Developer .mr.developer.cfg # SublimeText project files /*.sublime-project *.sublime-workspace # Windows image file caches Thumbs.db # Folder config file Desktop.ini # Recycle Bin used on file shares $RECYCLE.BIN/ # Linux ignores *~ # OS X ignores .DS_Store python-multipart-0.0.5/.gitmodules000066400000000000000000000001771336005506300172370ustar00rootroot00000000000000[submodule "docs/build/html"] path = docs/build/html url = git://github.com/andrew-d/python-multipart.git branch = gh-pages python-multipart-0.0.5/.travis.yml000066400000000000000000000004331336005506300171660ustar00rootroot00000000000000sudo: false language: python python: - "2.7" - "3.3" - "3.4" - "3.5" - "3.6" - "pypy" install: - pip install -r requirements.txt - "if [[ $TRAVIS_PYTHON_VERSION == '2.6' ]]; then pip install unittest2; fi" script: - py.test branches: only: - master python-multipart-0.0.5/LICENSE.txt000066400000000000000000000010531336005506300166770ustar00rootroot00000000000000Copyright 2012, Andrew Dunham Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. python-multipart-0.0.5/MANIFEST.in000066400000000000000000000002371336005506300166150ustar00rootroot00000000000000include requirements.txt README.md LICENSE.txt recursive-include multipart *.py *.yaml *.bare *.http LICENSE*.* recursive-exclude multipart *.pyc *.pyo *.pyd python-multipart-0.0.5/README.rst000066400000000000000000000012461336005506300165470ustar00rootroot00000000000000================== Python-Multipart ================== .. image:: https://secure.travis-ci.org/andrew-d/python-multipart.png?branch=master :target: http://travis-ci.org/andrew-d/python-multipart python-multipart is an Apache2 licensed streaming multipart parser for Python. It's still under some development, but test coverage is currently 100%. Documentation is available `here`_. .. _here: http://andrew-d.github.io/python-multipart/ Why? ---- Because streaming uploads are awesome for large files. More examples will be coming soon :) How to Test ----------- If you want to test: .. code-block:: bash $ pip install -r requirements.txt $ py.test python-multipart-0.0.5/docs/000077500000000000000000000000001336005506300160055ustar00rootroot00000000000000python-multipart-0.0.5/docs/Makefile000066400000000000000000000152331336005506300174510ustar00rootroot00000000000000# Makefile for Sphinx documentation # # You can set these variables from the command line. SPHINXOPTS = SPHINXBUILD = sphinx-build PAPER = BUILDDIR = build # User-friendly check for sphinx-build ifeq ($(shell which $(SPHINXBUILD) >/dev/null 2>&1; echo $$?), 1) $(error The '$(SPHINXBUILD)' command was not found. Make sure you have Sphinx installed, then set the SPHINXBUILD environment variable to point to the full path of the '$(SPHINXBUILD)' executable. Alternatively you can add the directory with the executable to your PATH. If you don't have Sphinx installed, grab it from http://sphinx-doc.org/) endif # Internal variables. PAPEROPT_a4 = -D latex_paper_size=a4 PAPEROPT_letter = -D latex_paper_size=letter ALLSPHINXOPTS = -d $(BUILDDIR)/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) source # the i18n builder cannot share the environment and doctrees with the others I18NSPHINXOPTS = $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) source .PHONY: help clean html dirhtml singlehtml pickle json htmlhelp qthelp devhelp epub latex latexpdf text man changes linkcheck doctest gettext help: @echo "Please use \`make ' where is one of" @echo " html to make standalone HTML files" @echo " dirhtml to make HTML files named index.html in directories" @echo " singlehtml to make a single large HTML file" @echo " pickle to make pickle files" @echo " json to make JSON files" @echo " htmlhelp to make HTML files and a HTML help project" @echo " qthelp to make HTML files and a qthelp project" @echo " devhelp to make HTML files and a Devhelp project" @echo " epub to make an epub" @echo " latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter" @echo " latexpdf to make LaTeX files and run them through pdflatex" @echo " latexpdfja to make LaTeX files and run them through platex/dvipdfmx" @echo " text to make text files" @echo " man to make manual pages" @echo " texinfo to make Texinfo files" @echo " info to make Texinfo files and run them through makeinfo" @echo " gettext to make PO message catalogs" @echo " changes to make an overview of all changed/added/deprecated items" @echo " xml to make Docutils-native XML files" @echo " pseudoxml to make pseudoxml-XML files for display purposes" @echo " linkcheck to check all external links for integrity" @echo " doctest to run all doctests embedded in the documentation (if enabled)" clean: rm -rf $(BUILDDIR)/* html: $(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html @echo @echo "Build finished. The HTML pages are in $(BUILDDIR)/html." dirhtml: $(SPHINXBUILD) -b dirhtml $(ALLSPHINXOPTS) $(BUILDDIR)/dirhtml @echo @echo "Build finished. The HTML pages are in $(BUILDDIR)/dirhtml." singlehtml: $(SPHINXBUILD) -b singlehtml $(ALLSPHINXOPTS) $(BUILDDIR)/singlehtml @echo @echo "Build finished. The HTML page is in $(BUILDDIR)/singlehtml." pickle: $(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) $(BUILDDIR)/pickle @echo @echo "Build finished; now you can process the pickle files." json: $(SPHINXBUILD) -b json $(ALLSPHINXOPTS) $(BUILDDIR)/json @echo @echo "Build finished; now you can process the JSON files." htmlhelp: $(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) $(BUILDDIR)/htmlhelp @echo @echo "Build finished; now you can run HTML Help Workshop with the" \ ".hhp project file in $(BUILDDIR)/htmlhelp." qthelp: $(SPHINXBUILD) -b qthelp $(ALLSPHINXOPTS) $(BUILDDIR)/qthelp @echo @echo "Build finished; now you can run "qcollectiongenerator" with the" \ ".qhcp project file in $(BUILDDIR)/qthelp, like this:" @echo "# qcollectiongenerator $(BUILDDIR)/qthelp/python-multipart.qhcp" @echo "To view the help file:" @echo "# assistant -collectionFile $(BUILDDIR)/qthelp/python-multipart.qhc" devhelp: $(SPHINXBUILD) -b devhelp $(ALLSPHINXOPTS) $(BUILDDIR)/devhelp @echo @echo "Build finished." @echo "To view the help file:" @echo "# mkdir -p $$HOME/.local/share/devhelp/python-multipart" @echo "# ln -s $(BUILDDIR)/devhelp $$HOME/.local/share/devhelp/python-multipart" @echo "# devhelp" epub: $(SPHINXBUILD) -b epub $(ALLSPHINXOPTS) $(BUILDDIR)/epub @echo @echo "Build finished. The epub file is in $(BUILDDIR)/epub." latex: $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex @echo @echo "Build finished; the LaTeX files are in $(BUILDDIR)/latex." @echo "Run \`make' in that directory to run these through (pdf)latex" \ "(use \`make latexpdf' here to do that automatically)." latexpdf: $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex @echo "Running LaTeX files through pdflatex..." $(MAKE) -C $(BUILDDIR)/latex all-pdf @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex." latexpdfja: $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex @echo "Running LaTeX files through platex and dvipdfmx..." $(MAKE) -C $(BUILDDIR)/latex all-pdf-ja @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex." text: $(SPHINXBUILD) -b text $(ALLSPHINXOPTS) $(BUILDDIR)/text @echo @echo "Build finished. The text files are in $(BUILDDIR)/text." man: $(SPHINXBUILD) -b man $(ALLSPHINXOPTS) $(BUILDDIR)/man @echo @echo "Build finished. The manual pages are in $(BUILDDIR)/man." texinfo: $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo @echo @echo "Build finished. The Texinfo files are in $(BUILDDIR)/texinfo." @echo "Run \`make' in that directory to run these through makeinfo" \ "(use \`make info' here to do that automatically)." info: $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo @echo "Running Texinfo files through makeinfo..." make -C $(BUILDDIR)/texinfo info @echo "makeinfo finished; the Info files are in $(BUILDDIR)/texinfo." gettext: $(SPHINXBUILD) -b gettext $(I18NSPHINXOPTS) $(BUILDDIR)/locale @echo @echo "Build finished. The message catalogs are in $(BUILDDIR)/locale." changes: $(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) $(BUILDDIR)/changes @echo @echo "The overview file is in $(BUILDDIR)/changes." linkcheck: $(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) $(BUILDDIR)/linkcheck @echo @echo "Link check complete; look for any errors in the above output " \ "or in $(BUILDDIR)/linkcheck/output.txt." doctest: $(SPHINXBUILD) -b doctest $(ALLSPHINXOPTS) $(BUILDDIR)/doctest @echo "Testing of doctests in the sources finished, look at the " \ "results in $(BUILDDIR)/doctest/output.txt." xml: $(SPHINXBUILD) -b xml $(ALLSPHINXOPTS) $(BUILDDIR)/xml @echo @echo "Build finished. The XML files are in $(BUILDDIR)/xml." pseudoxml: $(SPHINXBUILD) -b pseudoxml $(ALLSPHINXOPTS) $(BUILDDIR)/pseudoxml @echo @echo "Build finished. The pseudo-XML files are in $(BUILDDIR)/pseudoxml." python-multipart-0.0.5/docs/build/000077500000000000000000000000001336005506300171045ustar00rootroot00000000000000python-multipart-0.0.5/docs/build/.gitignore000066400000000000000000000000111336005506300210640ustar00rootroot00000000000000doctrees python-multipart-0.0.5/docs/build/html/000077500000000000000000000000001336005506300200505ustar00rootroot00000000000000python-multipart-0.0.5/docs/make.bat000066400000000000000000000151121336005506300174120ustar00rootroot00000000000000@ECHO OFF REM Command file for Sphinx documentation if "%SPHINXBUILD%" == "" ( set SPHINXBUILD=sphinx-build ) set BUILDDIR=build set ALLSPHINXOPTS=-d %BUILDDIR%/doctrees %SPHINXOPTS% source set I18NSPHINXOPTS=%SPHINXOPTS% source if NOT "%PAPER%" == "" ( set ALLSPHINXOPTS=-D latex_paper_size=%PAPER% %ALLSPHINXOPTS% set I18NSPHINXOPTS=-D latex_paper_size=%PAPER% %I18NSPHINXOPTS% ) if "%1" == "" goto help if "%1" == "help" ( :help echo.Please use `make ^` where ^ is one of echo. html to make standalone HTML files echo. dirhtml to make HTML files named index.html in directories echo. singlehtml to make a single large HTML file echo. pickle to make pickle files echo. json to make JSON files echo. htmlhelp to make HTML files and a HTML help project echo. qthelp to make HTML files and a qthelp project echo. devhelp to make HTML files and a Devhelp project echo. epub to make an epub echo. latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter echo. text to make text files echo. man to make manual pages echo. texinfo to make Texinfo files echo. gettext to make PO message catalogs echo. changes to make an overview over all changed/added/deprecated items echo. xml to make Docutils-native XML files echo. pseudoxml to make pseudoxml-XML files for display purposes echo. linkcheck to check all external links for integrity echo. doctest to run all doctests embedded in the documentation if enabled goto end ) if "%1" == "clean" ( for /d %%i in (%BUILDDIR%\*) do rmdir /q /s %%i del /q /s %BUILDDIR%\* goto end ) %SPHINXBUILD% 2> nul if errorlevel 9009 ( echo. echo.The 'sphinx-build' command was not found. Make sure you have Sphinx echo.installed, then set the SPHINXBUILD environment variable to point echo.to the full path of the 'sphinx-build' executable. Alternatively you echo.may add the Sphinx directory to PATH. echo. echo.If you don't have Sphinx installed, grab it from echo.http://sphinx-doc.org/ exit /b 1 ) if "%1" == "html" ( %SPHINXBUILD% -b html %ALLSPHINXOPTS% %BUILDDIR%/html if errorlevel 1 exit /b 1 echo. echo.Build finished. The HTML pages are in %BUILDDIR%/html. goto end ) if "%1" == "dirhtml" ( %SPHINXBUILD% -b dirhtml %ALLSPHINXOPTS% %BUILDDIR%/dirhtml if errorlevel 1 exit /b 1 echo. echo.Build finished. The HTML pages are in %BUILDDIR%/dirhtml. goto end ) if "%1" == "singlehtml" ( %SPHINXBUILD% -b singlehtml %ALLSPHINXOPTS% %BUILDDIR%/singlehtml if errorlevel 1 exit /b 1 echo. echo.Build finished. The HTML pages are in %BUILDDIR%/singlehtml. goto end ) if "%1" == "pickle" ( %SPHINXBUILD% -b pickle %ALLSPHINXOPTS% %BUILDDIR%/pickle if errorlevel 1 exit /b 1 echo. echo.Build finished; now you can process the pickle files. goto end ) if "%1" == "json" ( %SPHINXBUILD% -b json %ALLSPHINXOPTS% %BUILDDIR%/json if errorlevel 1 exit /b 1 echo. echo.Build finished; now you can process the JSON files. goto end ) if "%1" == "htmlhelp" ( %SPHINXBUILD% -b htmlhelp %ALLSPHINXOPTS% %BUILDDIR%/htmlhelp if errorlevel 1 exit /b 1 echo. echo.Build finished; now you can run HTML Help Workshop with the ^ .hhp project file in %BUILDDIR%/htmlhelp. goto end ) if "%1" == "qthelp" ( %SPHINXBUILD% -b qthelp %ALLSPHINXOPTS% %BUILDDIR%/qthelp if errorlevel 1 exit /b 1 echo. echo.Build finished; now you can run "qcollectiongenerator" with the ^ .qhcp project file in %BUILDDIR%/qthelp, like this: echo.^> qcollectiongenerator %BUILDDIR%\qthelp\python-multipart.qhcp echo.To view the help file: echo.^> assistant -collectionFile %BUILDDIR%\qthelp\python-multipart.ghc goto end ) if "%1" == "devhelp" ( %SPHINXBUILD% -b devhelp %ALLSPHINXOPTS% %BUILDDIR%/devhelp if errorlevel 1 exit /b 1 echo. echo.Build finished. goto end ) if "%1" == "epub" ( %SPHINXBUILD% -b epub %ALLSPHINXOPTS% %BUILDDIR%/epub if errorlevel 1 exit /b 1 echo. echo.Build finished. The epub file is in %BUILDDIR%/epub. goto end ) if "%1" == "latex" ( %SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex if errorlevel 1 exit /b 1 echo. echo.Build finished; the LaTeX files are in %BUILDDIR%/latex. goto end ) if "%1" == "latexpdf" ( %SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex cd %BUILDDIR%/latex make all-pdf cd %BUILDDIR%/.. echo. echo.Build finished; the PDF files are in %BUILDDIR%/latex. goto end ) if "%1" == "latexpdfja" ( %SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex cd %BUILDDIR%/latex make all-pdf-ja cd %BUILDDIR%/.. echo. echo.Build finished; the PDF files are in %BUILDDIR%/latex. goto end ) if "%1" == "text" ( %SPHINXBUILD% -b text %ALLSPHINXOPTS% %BUILDDIR%/text if errorlevel 1 exit /b 1 echo. echo.Build finished. The text files are in %BUILDDIR%/text. goto end ) if "%1" == "man" ( %SPHINXBUILD% -b man %ALLSPHINXOPTS% %BUILDDIR%/man if errorlevel 1 exit /b 1 echo. echo.Build finished. The manual pages are in %BUILDDIR%/man. goto end ) if "%1" == "texinfo" ( %SPHINXBUILD% -b texinfo %ALLSPHINXOPTS% %BUILDDIR%/texinfo if errorlevel 1 exit /b 1 echo. echo.Build finished. The Texinfo files are in %BUILDDIR%/texinfo. goto end ) if "%1" == "gettext" ( %SPHINXBUILD% -b gettext %I18NSPHINXOPTS% %BUILDDIR%/locale if errorlevel 1 exit /b 1 echo. echo.Build finished. The message catalogs are in %BUILDDIR%/locale. goto end ) if "%1" == "changes" ( %SPHINXBUILD% -b changes %ALLSPHINXOPTS% %BUILDDIR%/changes if errorlevel 1 exit /b 1 echo. echo.The overview file is in %BUILDDIR%/changes. goto end ) if "%1" == "linkcheck" ( %SPHINXBUILD% -b linkcheck %ALLSPHINXOPTS% %BUILDDIR%/linkcheck if errorlevel 1 exit /b 1 echo. echo.Link check complete; look for any errors in the above output ^ or in %BUILDDIR%/linkcheck/output.txt. goto end ) if "%1" == "doctest" ( %SPHINXBUILD% -b doctest %ALLSPHINXOPTS% %BUILDDIR%/doctest if errorlevel 1 exit /b 1 echo. echo.Testing of doctests in the sources finished, look at the ^ results in %BUILDDIR%/doctest/output.txt. goto end ) if "%1" == "xml" ( %SPHINXBUILD% -b xml %ALLSPHINXOPTS% %BUILDDIR%/xml if errorlevel 1 exit /b 1 echo. echo.Build finished. The XML files are in %BUILDDIR%/xml. goto end ) if "%1" == "pseudoxml" ( %SPHINXBUILD% -b pseudoxml %ALLSPHINXOPTS% %BUILDDIR%/pseudoxml if errorlevel 1 exit /b 1 echo. echo.Build finished. The pseudo-XML files are in %BUILDDIR%/pseudoxml. goto end ) :end python-multipart-0.0.5/docs/source/000077500000000000000000000000001336005506300173055ustar00rootroot00000000000000python-multipart-0.0.5/docs/source/_themes/000077500000000000000000000000001336005506300207315ustar00rootroot00000000000000python-multipart-0.0.5/docs/source/_themes/.gitignore000066400000000000000000000000261336005506300227170ustar00rootroot00000000000000*.pyc *.pyo .DS_Store python-multipart-0.0.5/docs/source/_themes/LICENSE000066400000000000000000000033751336005506300217460ustar00rootroot00000000000000Copyright (c) 2010 by Armin Ronacher. Some rights reserved. Redistribution and use in source and binary forms of the theme, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * The names of the contributors may not be used to endorse or promote products derived from this software without specific prior written permission. We kindly ask you to only use these themes in an unmodified manner just for Flask and Flask-related products, not for unrelated projects. If you like the visual style and want to use it for your own projects, please consider making some larger changes to the themes (such as changing font faces, sizes, colors or margins). THIS THEME IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS THEME, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. python-multipart-0.0.5/docs/source/_themes/README000066400000000000000000000021051336005506300216070ustar00rootroot00000000000000Flask Sphinx Styles =================== This repository contains sphinx styles for Flask and Flask related projects. To use this style in your Sphinx documentation, follow this guide: 1. put this folder as _themes into your docs folder. Alternatively you can also use git submodules to check out the contents there. 2. add this to your conf.py: sys.path.append(os.path.abspath('_themes')) html_theme_path = ['_themes'] html_theme = 'flask' The following themes exist: - 'flask' - the standard flask documentation theme for large projects - 'flask_small' - small one-page theme. Intended to be used by very small addon libraries for flask. The following options exist for the flask_small theme: [options] index_logo = '' filename of a picture in _static to be used as replacement for the h1 in the index.rst file. index_logo_height = 120px height of the index logo github_fork = '' repository name on github for the "fork me" badge python-multipart-0.0.5/docs/source/_themes/flask/000077500000000000000000000000001336005506300220315ustar00rootroot00000000000000python-multipart-0.0.5/docs/source/_themes/flask/layout.html000066400000000000000000000013561336005506300242410ustar00rootroot00000000000000{%- extends "basic/layout.html" %} {%- block extrahead %} {{ super() }} {% if theme_touch_icon %} {% endif %} {% endblock %} {%- block relbar2 %}{% endblock %} {% block header %} {{ super() }} {% if pagename == 'index' %}
{% endif %} {% endblock %} {%- block footer %} {% if pagename == 'index' %}
{% endif %} {%- endblock %} python-multipart-0.0.5/docs/source/_themes/flask/relations.html000066400000000000000000000011161336005506300247160ustar00rootroot00000000000000

Related Topics

python-multipart-0.0.5/docs/source/_themes/flask/static/000077500000000000000000000000001336005506300233205ustar00rootroot00000000000000python-multipart-0.0.5/docs/source/_themes/flask/static/flasky.css_t000066400000000000000000000144441336005506300256550ustar00rootroot00000000000000/* * flasky.css_t * ~~~~~~~~~~~~ * * :copyright: Copyright 2010 by Armin Ronacher. * :license: Flask Design License, see LICENSE for details. */ {% set page_width = '940px' %} {% set sidebar_width = '220px' %} @import url("basic.css"); /* -- page layout ----------------------------------------------------------- */ body { font-family: 'Georgia', serif; font-size: 17px; background-color: white; color: #000; margin: 0; padding: 0; } div.document { width: {{ page_width }}; margin: 30px auto 0 auto; } div.documentwrapper { float: left; width: 100%; } div.bodywrapper { margin: 0 0 0 {{ sidebar_width }}; } div.sphinxsidebar { width: {{ sidebar_width }}; } hr { border: 1px solid #B1B4B6; } div.body { background-color: #ffffff; color: #3E4349; padding: 0 30px 0 30px; } img.floatingflask { padding: 0 0 10px 10px; float: right; } div.footer { width: {{ page_width }}; margin: 20px auto 30px auto; font-size: 14px; color: #888; text-align: right; } div.footer a { color: #888; } div.related { display: none; } div.sphinxsidebar a { color: #444; text-decoration: none; border-bottom: 1px dotted #999; } div.sphinxsidebar a:hover { border-bottom: 1px solid #999; } div.sphinxsidebar { font-size: 14px; line-height: 1.5; } div.sphinxsidebarwrapper { padding: 18px 10px; } div.sphinxsidebarwrapper p.logo { padding: 0 0 20px 0; margin: 0; text-align: center; } div.sphinxsidebar h3, div.sphinxsidebar h4 { font-family: 'Garamond', 'Georgia', serif; color: #444; font-size: 24px; font-weight: normal; margin: 0 0 5px 0; padding: 0; } div.sphinxsidebar h4 { font-size: 20px; } div.sphinxsidebar h3 a { color: #444; } div.sphinxsidebar p.logo a, div.sphinxsidebar h3 a, div.sphinxsidebar p.logo a:hover, div.sphinxsidebar h3 a:hover { border: none; } div.sphinxsidebar p { color: #555; margin: 10px 0; } div.sphinxsidebar ul { margin: 10px 0; padding: 0; color: #000; } div.sphinxsidebar input { border: 1px solid #ccc; font-family: 'Georgia', serif; font-size: 1em; } /* -- body styles ----------------------------------------------------------- */ a { color: #004B6B; text-decoration: underline; } a:hover { color: #6D4100; text-decoration: underline; } div.body h1, div.body h2, div.body h3, div.body h4, div.body h5, div.body h6 { font-family: 'Garamond', 'Georgia', serif; font-weight: normal; margin: 30px 0px 10px 0px; padding: 0; } {% if theme_index_logo %} div.indexwrapper h1 { text-indent: -999999px; background: url({{ theme_index_logo }}) no-repeat center center; height: {{ theme_index_logo_height }}; } {% endif %} div.body h1 { margin-top: 0; padding-top: 0; font-size: 240%; } div.body h2 { font-size: 180%; } div.body h3 { font-size: 150%; } div.body h4 { font-size: 130%; } div.body h5 { font-size: 100%; } div.body h6 { font-size: 100%; } a.headerlink { color: #ddd; padding: 0 4px; text-decoration: none; } a.headerlink:hover { color: #444; background: #eaeaea; } div.body p, div.body dd, div.body li { line-height: 1.4em; } div.admonition { background: #fafafa; margin: 20px -30px; padding: 10px 30px; border-top: 1px solid #ccc; border-bottom: 1px solid #ccc; } div.admonition tt.xref, div.admonition a tt { border-bottom: 1px solid #fafafa; } dd div.admonition { margin-left: -60px; padding-left: 60px; } div.admonition p.admonition-title { font-family: 'Garamond', 'Georgia', serif; font-weight: normal; font-size: 24px; margin: 0 0 10px 0; padding: 0; line-height: 1; } div.admonition p.last { margin-bottom: 0; } div.highlight { background-color: white; } dt:target, .highlight { background: #FAF3E8; } div.note { background-color: #eee; border: 1px solid #ccc; } div.seealso { background-color: #ffc; border: 1px solid #ff6; } div.topic { background-color: #eee; } p.admonition-title { display: inline; } p.admonition-title:after { content: ":"; } pre, tt { font-family: 'Consolas', 'Menlo', 'Deja Vu Sans Mono', 'Bitstream Vera Sans Mono', monospace; font-size: 0.9em; } img.screenshot { } tt.descname, tt.descclassname { font-size: 0.95em; } tt.descname { padding-right: 0.08em; } img.screenshot { -moz-box-shadow: 2px 2px 4px #eee; -webkit-box-shadow: 2px 2px 4px #eee; box-shadow: 2px 2px 4px #eee; } table.docutils { border: 1px solid #888; -moz-box-shadow: 2px 2px 4px #eee; -webkit-box-shadow: 2px 2px 4px #eee; box-shadow: 2px 2px 4px #eee; } table.docutils td, table.docutils th { border: 1px solid #888; padding: 0.25em 0.7em; } table.field-list, table.footnote { border: none; -moz-box-shadow: none; -webkit-box-shadow: none; box-shadow: none; } table.footnote { margin: 15px 0; width: 100%; border: 1px solid #eee; background: #fdfdfd; font-size: 0.9em; } table.footnote + table.footnote { margin-top: -15px; border-top: none; } table.field-list th { padding: 0 0.8em 0 0; } table.field-list td { padding: 0; } table.footnote td.label { width: 0px; padding: 0.3em 0 0.3em 0.5em; } table.footnote td { padding: 0.3em 0.5em; } dl { margin: 0; padding: 0; } dl dd { margin-left: 30px; } blockquote { margin: 0 0 0 30px; padding: 0; } ul, ol { margin: 10px 0 10px 30px; padding: 0; } pre { background: #eee; padding: 7px 30px; margin: 15px -30px; line-height: 1.3em; } dl pre, blockquote pre, li pre { margin-left: -60px; padding-left: 60px; } dl dl pre { margin-left: -90px; padding-left: 90px; } tt { background-color: #ecf0f3; color: #222; /* padding: 1px 2px; */ } tt.xref, a tt { background-color: #FBFBFB; border-bottom: 1px solid white; } a.reference { text-decoration: none; border-bottom: 1px dotted #004B6B; } a.reference:hover { border-bottom: 1px solid #6D4100; } a.footnote-reference { text-decoration: none; font-size: 0.7em; vertical-align: top; border-bottom: 1px dotted #004B6B; } a.footnote-reference:hover { border-bottom: 1px solid #6D4100; } a:hover tt { background: #EEE; } python-multipart-0.0.5/docs/source/_themes/flask/static/small_flask.css000066400000000000000000000017201336005506300263220ustar00rootroot00000000000000/* * small_flask.css_t * ~~~~~~~~~~~~~~~~~ * * :copyright: Copyright 2010 by Armin Ronacher. * :license: Flask Design License, see LICENSE for details. */ body { margin: 0; padding: 20px 30px; } div.documentwrapper { float: none; background: white; } div.sphinxsidebar { display: block; float: none; width: 102.5%; margin: 50px -30px -20px -30px; padding: 10px 20px; background: #333; color: white; } div.sphinxsidebar h3, div.sphinxsidebar h4, div.sphinxsidebar p, div.sphinxsidebar h3 a { color: white; } div.sphinxsidebar a { color: #aaa; } div.sphinxsidebar p.logo { display: none; } div.document { width: 100%; margin: 0; } div.related { display: block; margin: 0; padding: 10px 0 20px 0; } div.related ul, div.related ul li { margin: 0; padding: 0; } div.footer { display: none; } div.bodywrapper { margin: 0; } div.body { min-height: 0; padding: 0; } python-multipart-0.0.5/docs/source/_themes/flask/theme.conf000066400000000000000000000002441336005506300240020ustar00rootroot00000000000000[theme] inherit = basic stylesheet = flasky.css pygments_style = flask_theme_support.FlaskyStyle [options] index_logo = '' index_logo_height = 120px touch_icon = python-multipart-0.0.5/docs/source/_themes/flask_small/000077500000000000000000000000001336005506300232215ustar00rootroot00000000000000python-multipart-0.0.5/docs/source/_themes/flask_small/layout.html000066400000000000000000000012531336005506300254250ustar00rootroot00000000000000{% extends "basic/layout.html" %} {% block header %} {{ super() }} {% if pagename == 'index' %}
{% endif %} {% endblock %} {% block footer %} {% if pagename == 'index' %}
{% endif %} {% endblock %} {# do not display relbars #} {% block relbar1 %}{% endblock %} {% block relbar2 %} {% if theme_github_fork %} Fork me on GitHub {% endif %} {% endblock %} {% block sidebar1 %}{% endblock %} {% block sidebar2 %}{% endblock %} python-multipart-0.0.5/docs/source/_themes/flask_small/static/000077500000000000000000000000001336005506300245105ustar00rootroot00000000000000python-multipart-0.0.5/docs/source/_themes/flask_small/static/flasky.css_t000066400000000000000000000110011336005506300270270ustar00rootroot00000000000000/* * flasky.css_t * ~~~~~~~~~~~~ * * Sphinx stylesheet -- flasky theme based on nature theme. * * :copyright: Copyright 2007-2010 by the Sphinx team, see AUTHORS. * :license: BSD, see LICENSE for details. * */ @import url("basic.css"); /* -- page layout ----------------------------------------------------------- */ body { font-family: 'Georgia', serif; font-size: 17px; color: #000; background: white; margin: 0; padding: 0; } div.documentwrapper { float: left; width: 100%; } div.bodywrapper { margin: 40px auto 0 auto; width: 700px; } hr { border: 1px solid #B1B4B6; } div.body { background-color: #ffffff; color: #3E4349; padding: 0 30px 30px 30px; } img.floatingflask { padding: 0 0 10px 10px; float: right; } div.footer { text-align: right; color: #888; padding: 10px; font-size: 14px; width: 650px; margin: 0 auto 40px auto; } div.footer a { color: #888; text-decoration: underline; } div.related { line-height: 32px; color: #888; } div.related ul { padding: 0 0 0 10px; } div.related a { color: #444; } /* -- body styles ----------------------------------------------------------- */ a { color: #004B6B; text-decoration: underline; } a:hover { color: #6D4100; text-decoration: underline; } div.body { padding-bottom: 40px; /* saved for footer */ } div.body h1, div.body h2, div.body h3, div.body h4, div.body h5, div.body h6 { font-family: 'Garamond', 'Georgia', serif; font-weight: normal; margin: 30px 0px 10px 0px; padding: 0; } {% if theme_index_logo %} div.indexwrapper h1 { text-indent: -999999px; background: url({{ theme_index_logo }}) no-repeat center center; height: {{ theme_index_logo_height }}; } {% endif %} div.body h2 { font-size: 180%; } div.body h3 { font-size: 150%; } div.body h4 { font-size: 130%; } div.body h5 { font-size: 100%; } div.body h6 { font-size: 100%; } a.headerlink { color: white; padding: 0 4px; text-decoration: none; } a.headerlink:hover { color: #444; background: #eaeaea; } div.body p, div.body dd, div.body li { line-height: 1.4em; } div.admonition { background: #fafafa; margin: 20px -30px; padding: 10px 30px; border-top: 1px solid #ccc; border-bottom: 1px solid #ccc; } div.admonition p.admonition-title { font-family: 'Garamond', 'Georgia', serif; font-weight: normal; font-size: 24px; margin: 0 0 10px 0; padding: 0; line-height: 1; } div.admonition p.last { margin-bottom: 0; } div.highlight{ background-color: white; } dt:target, .highlight { background: #FAF3E8; } div.note { background-color: #eee; border: 1px solid #ccc; } div.seealso { background-color: #ffc; border: 1px solid #ff6; } div.topic { background-color: #eee; } div.warning { background-color: #ffe4e4; border: 1px solid #f66; } p.admonition-title { display: inline; } p.admonition-title:after { content: ":"; } pre, tt { font-family: 'Consolas', 'Menlo', 'Deja Vu Sans Mono', 'Bitstream Vera Sans Mono', monospace; font-size: 0.85em; } img.screenshot { } tt.descname, tt.descclassname { font-size: 0.95em; } tt.descname { padding-right: 0.08em; } img.screenshot { -moz-box-shadow: 2px 2px 4px #eee; -webkit-box-shadow: 2px 2px 4px #eee; box-shadow: 2px 2px 4px #eee; } table.docutils { border: 1px solid #888; -moz-box-shadow: 2px 2px 4px #eee; -webkit-box-shadow: 2px 2px 4px #eee; box-shadow: 2px 2px 4px #eee; } table.docutils td, table.docutils th { border: 1px solid #888; padding: 0.25em 0.7em; } table.field-list, table.footnote { border: none; -moz-box-shadow: none; -webkit-box-shadow: none; box-shadow: none; } table.footnote { margin: 15px 0; width: 100%; border: 1px solid #eee; } table.field-list th { padding: 0 0.8em 0 0; } table.field-list td { padding: 0; } table.footnote td { padding: 0.5em; } dl { margin: 0; padding: 0; } dl dd { margin-left: 30px; } pre { padding: 0; margin: 15px -30px; padding: 8px; line-height: 1.3em; padding: 7px 30px; background: #eee; border-radius: 2px; -moz-border-radius: 2px; -webkit-border-radius: 2px; } dl pre { margin-left: -60px; padding-left: 60px; } tt { background-color: #ecf0f3; color: #222; /* padding: 1px 2px; */ } tt.xref, a tt { background-color: #FBFBFB; } a:hover tt { background: #EEE; } python-multipart-0.0.5/docs/source/_themes/flask_small/theme.conf000066400000000000000000000002701336005506300251710ustar00rootroot00000000000000[theme] inherit = basic stylesheet = flasky.css nosidebar = true pygments_style = flask_theme_support.FlaskyStyle [options] index_logo = '' index_logo_height = 120px github_fork = '' python-multipart-0.0.5/docs/source/_themes/flask_theme_support.py000066400000000000000000000114131336005506300253610ustar00rootroot00000000000000# flasky extensions. flasky pygments style based on tango style from pygments.style import Style from pygments.token import Keyword, Name, Comment, String, Error, \ Number, Operator, Generic, Whitespace, Punctuation, Other, Literal class FlaskyStyle(Style): background_color = "#f8f8f8" default_style = "" styles = { # No corresponding class for the following: #Text: "", # class: '' Whitespace: "underline #f8f8f8", # class: 'w' Error: "#a40000 border:#ef2929", # class: 'err' Other: "#000000", # class 'x' Comment: "italic #8f5902", # class: 'c' Comment.Preproc: "noitalic", # class: 'cp' Keyword: "bold #004461", # class: 'k' Keyword.Constant: "bold #004461", # class: 'kc' Keyword.Declaration: "bold #004461", # class: 'kd' Keyword.Namespace: "bold #004461", # class: 'kn' Keyword.Pseudo: "bold #004461", # class: 'kp' Keyword.Reserved: "bold #004461", # class: 'kr' Keyword.Type: "bold #004461", # class: 'kt' Operator: "#582800", # class: 'o' Operator.Word: "bold #004461", # class: 'ow' - like keywords Punctuation: "bold #000000", # class: 'p' # because special names such as Name.Class, Name.Function, etc. # are not recognized as such later in the parsing, we choose them # to look the same as ordinary variables. Name: "#000000", # class: 'n' Name.Attribute: "#c4a000", # class: 'na' - to be revised Name.Builtin: "#004461", # class: 'nb' Name.Builtin.Pseudo: "#3465a4", # class: 'bp' Name.Class: "#000000", # class: 'nc' - to be revised Name.Constant: "#000000", # class: 'no' - to be revised Name.Decorator: "#888", # class: 'nd' - to be revised Name.Entity: "#ce5c00", # class: 'ni' Name.Exception: "bold #cc0000", # class: 'ne' Name.Function: "#000000", # class: 'nf' Name.Property: "#000000", # class: 'py' Name.Label: "#f57900", # class: 'nl' Name.Namespace: "#000000", # class: 'nn' - to be revised Name.Other: "#000000", # class: 'nx' Name.Tag: "bold #004461", # class: 'nt' - like a keyword Name.Variable: "#000000", # class: 'nv' - to be revised Name.Variable.Class: "#000000", # class: 'vc' - to be revised Name.Variable.Global: "#000000", # class: 'vg' - to be revised Name.Variable.Instance: "#000000", # class: 'vi' - to be revised Number: "#990000", # class: 'm' Literal: "#000000", # class: 'l' Literal.Date: "#000000", # class: 'ld' String: "#4e9a06", # class: 's' String.Backtick: "#4e9a06", # class: 'sb' String.Char: "#4e9a06", # class: 'sc' String.Doc: "italic #8f5902", # class: 'sd' - like a comment String.Double: "#4e9a06", # class: 's2' String.Escape: "#4e9a06", # class: 'se' String.Heredoc: "#4e9a06", # class: 'sh' String.Interpol: "#4e9a06", # class: 'si' String.Other: "#4e9a06", # class: 'sx' String.Regex: "#4e9a06", # class: 'sr' String.Single: "#4e9a06", # class: 's1' String.Symbol: "#4e9a06", # class: 'ss' Generic: "#000000", # class: 'g' Generic.Deleted: "#a40000", # class: 'gd' Generic.Emph: "italic #000000", # class: 'ge' Generic.Error: "#ef2929", # class: 'gr' Generic.Heading: "bold #000080", # class: 'gh' Generic.Inserted: "#00A000", # class: 'gi' Generic.Output: "#888", # class: 'go' Generic.Prompt: "#745334", # class: 'gp' Generic.Strong: "bold #000000", # class: 'gs' Generic.Subheading: "bold #800080", # class: 'gu' Generic.Traceback: "bold #a40000", # class: 'gt' } python-multipart-0.0.5/docs/source/api.rst000066400000000000000000000020711336005506300206100ustar00rootroot00000000000000.. _api: API === .. module:: multipart This section of the documentation covers all of the public interfaces of python-multipart. Helper Functions ---------------- .. currentmodule:: multipart.multipart .. autofunction:: parse_form .. autofunction:: create_form_parser Main Class ---------- .. currentmodule:: multipart.multipart .. autoclass:: FormParser :members: Parsers ------- .. currentmodule:: multipart.multipart .. autoclass:: BaseParser :members: .. autoclass:: OctetStreamParser :members: .. autoclass:: QuerystringParser :members: .. autoclass:: MultipartParser :members: Support Classes --------------- .. currentmodule:: multipart.multipart .. autoclass:: Field :members: .. autoclass:: File :members: Decoders -------- .. automodule:: multipart.decoders :members: Exceptions ---------- The following are all custom exceptions that python-multipart will raise, for various cases. Each method that will raise an exception will document it in this documentation. .. automodule:: multipart.exceptions :members: python-multipart-0.0.5/docs/source/conf.py000066400000000000000000000203041336005506300206030ustar00rootroot00000000000000# -*- coding: utf-8 -*- # # python-multipart documentation build configuration file, created by # sphinx-quickstart on Fri Apr 5 20:24:27 2013. # # This file is execfile()d with the current directory set to its containing dir. # # Note that not all possible configuration values are present in this # autogenerated file. # # All configuration values have a default; values that are commented out # serve to show the default. import sys, os # If extensions (or modules to document with autodoc) are in another directory, # add these directories to sys.path here. If the directory is relative to the # documentation root, use os.path.abspath to make it absolute, like shown here. sys.path.insert(0, os.path.abspath(os.path.join('..', '..'))) import multipart from multipart import __version__ # -- General configuration ----------------------------------------------------- # If your documentation needs a minimal Sphinx version, state it here. #needs_sphinx = '1.0' # Add any Sphinx extension module names here, as strings. They can be extensions # coming with Sphinx (named 'sphinx.ext.*') or your custom ones. extensions = ['sphinx.ext.autodoc', 'sphinx.ext.intersphinx', 'sphinx.ext.ifconfig'] # Add any paths that contain templates here, relative to this directory. templates_path = ['_templates'] # The suffix of source filenames. source_suffix = '.rst' # The encoding of source files. #source_encoding = 'utf-8-sig' # The master toctree document. master_doc = 'index' # General information about the project. project = u'python-multipart' copyright = u'2013, Andrew Dunham' # The version info for the project you're documenting, acts as replacement for # |version| and |release|, also used in various other places throughout the # built documents. # from multipart import __version__ # The short X.Y version. version = __version__ # The full version, including alpha/beta/rc tags. release = version # The language for content autogenerated by Sphinx. Refer to documentation # for a list of supported languages. #language = None # There are two options for replacing |today|: either, you set today to some # non-false value, then it is used: #today = '' # Else, today_fmt is used as the format for a strftime call. #today_fmt = '%B %d, %Y' # List of patterns, relative to source directory, that match files and # directories to ignore when looking for source files. exclude_patterns = ['build'] # The reST default role (used for this markup: `text`) to use for all documents. #default_role = None # If true, '()' will be appended to :func: etc. cross-reference text. #add_function_parentheses = True # If true, the current module name will be prepended to all description # unit titles (such as .. function::). #add_module_names = True # If true, sectionauthor and moduleauthor directives will be shown in the # output. They are ignored by default. #show_authors = False # The name of the Pygments (syntax highlighting) style to use. pygments_style = 'sphinx' # A list of ignored prefixes for module index sorting. #modindex_common_prefix = [] # If true, keep warnings as "system message" paragraphs in the built documents. #keep_warnings = False # -- Options for HTML output --------------------------------------------------- # The theme to use for HTML and HTML Help pages. See the documentation for # a list of builtin themes. sys.path.append(os.path.abspath('_themes')) html_theme = 'flask' # Theme options are theme-specific and customize the look and feel of a theme # further. For a list of options available for each theme, see the # documentation. html_theme_options = { } # Add any paths that contain custom themes here, relative to this directory. html_theme_path = ['_themes'] # The name for this set of Sphinx documents. If None, it defaults to # " v documentation". #html_title = None # A shorter title for the navigation bar. Default is the same as html_title. #html_short_title = None # The name of an image file (relative to this directory) to place at the top # of the sidebar. #html_logo = None # The name of an image file (within the static path) to use as favicon of the # docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 # pixels large. #html_favicon = None # Add any paths that contain custom static files (such as style sheets) here, # relative to this directory. They are copied after the builtin static files, # so a file named "default.css" will overwrite the builtin "default.css". html_static_path = ['_static'] # If not '', a 'Last updated on:' timestamp is inserted at every page bottom, # using the given strftime format. #html_last_updated_fmt = '%b %d, %Y' # If true, SmartyPants will be used to convert quotes and dashes to # typographically correct entities. #html_use_smartypants = True # Custom sidebar templates, maps document names to template names. #html_sidebars = {} # Additional templates that should be rendered to pages, maps page names to # template names. #html_additional_pages = {} # If false, no module index is generated. #html_domain_indices = True # If false, no index is generated. #html_use_index = True # If true, the index is split into individual pages for each letter. #html_split_index = False # If true, links to the reST sources are added to the pages. html_show_sourcelink = False # If true, "Created using Sphinx" is shown in the HTML footer. Default is True. html_show_sphinx = False # If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. #html_show_copyright = True # If true, an OpenSearch description file will be output, and all pages will # contain a tag referring to it. The value of this option must be the # base URL from which the finished HTML is served. #html_use_opensearch = '' # This is the file name suffix for HTML files (e.g. ".xhtml"). #html_file_suffix = None # Output file base name for HTML help builder. htmlhelp_basename = 'python-multipartdoc' # -- Options for LaTeX output -------------------------------------------------- latex_elements = { # The paper size ('letterpaper' or 'a4paper'). #'papersize': 'letterpaper', # The font size ('10pt', '11pt' or '12pt'). #'pointsize': '10pt', # Additional stuff for the LaTeX preamble. #'preamble': '', } # Grouping the document tree into LaTeX files. List of tuples # (source start file, target name, title, author, documentclass [howto/manual]). latex_documents = [ ('index', 'python-multipart.tex', u'python-multipart Documentation', u'Andrew Dunham', 'manual'), ] # The name of an image file (relative to this directory) to place at the top of # the title page. #latex_logo = None # For "manual" documents, if this is true, then toplevel headings are parts, # not chapters. #latex_use_parts = False # If true, show page references after internal links. #latex_show_pagerefs = False # If true, show URL addresses after external links. #latex_show_urls = False # Documents to append as an appendix to all manuals. #latex_appendices = [] # If false, no module index is generated. #latex_domain_indices = True # -- Options for manual page output -------------------------------------------- # One entry per manual page. List of tuples # (source start file, name, description, authors, manual section). man_pages = [ ('index', 'python-multipart', u'python-multipart Documentation', [u'Andrew Dunham'], 1) ] # If true, show URL addresses after external links. #man_show_urls = False # -- Options for Texinfo output ------------------------------------------------ # Grouping the document tree into Texinfo files. List of tuples # (source start file, target name, title, author, # dir menu entry, description, category) texinfo_documents = [ ('index', 'python-multipart', u'python-multipart Documentation', u'Andrew Dunham', 'python-multipart', 'One line description of project.', 'Miscellaneous'), ] # Documents to append as an appendix to all manuals. #texinfo_appendices = [] # If false, no module index is generated. #texinfo_domain_indices = True # How to display URL addresses: 'footnote', 'no', or 'inline'. #texinfo_show_urls = 'footnote' # If true, do not generate a @detailmenu in the "Top" node's menu. #texinfo_no_detailmenu = False # Example configuration for intersphinx: refer to the Python standard library. intersphinx_mapping = {'http://docs.python.org/': None} python-multipart-0.0.5/docs/source/contents.rst.inc000066400000000000000000000004041336005506300224420ustar00rootroot00000000000000User's Guide ------------ .. toctree:: :maxdepth: 2 quickstart API Reference ------------- If you are looking for information on a specific function, class or method, this part of the documentation is for you. .. toctree:: :maxdepth: 2 api python-multipart-0.0.5/docs/source/index.rst000066400000000000000000000002401336005506300211420ustar00rootroot00000000000000:orphan: Python-Multipart ================ .. module:: multipart Python-Multipart is a streaming multipart parser for Python. .. include:: contents.rst.inc python-multipart-0.0.5/docs/source/quickstart.rst000066400000000000000000000131571336005506300222400ustar00rootroot00000000000000.. _quickstart: Quickstart ========== .. currentmodule:: multipart Python-Multipart foo bar baz Simple Example -------------- The following example shows a quick example of parsing an incoming request body in a simple WSGI application:: import multipart def simple_app(environ, start_response): ret = [] # The following two callbacks just append the name to the return value. def on_field(field): ret.append("Parsed field named: %s" % (field.field_name,)) def on_file(file): ret.append("Parsed file named: %s" % (file.field_name,)) # Create headers object. We need to convert from WSGI to the actual # name of the header, since this library does not assume that you are # using WSGI. headers = {'Content-Type': environ['CONTENT_TYPE']} if 'HTTP_X_FILE_NAME' in environ: headers['X-File-Name'] = environ['HTTP_X_FILE_NAME'] if 'CONTENT_LENGTH' in environ: headers['Content-Length'] = environ['CONTENT_LENGTH'] # Parse the form. multipart.parse_form(headers, environ['wsgi.input'], on_field, on_file) # Return something. start_response('200 OK', [('Content-type', 'text/plain')]) ret.append('\n') return ret from wsgiref.simple_server import make_server httpd = make_server('', 8123, simple_app) print("Serving on port 8123...") httpd.serve_forever() If you test this with curl, you can see that the parser works: .. code-block:: bash $ curl -ik -F "foo=bar" http://localhost:8123/ HTTP/1.0 200 OK Date: Sun, 07 Apr 2013 01:40:52 GMT Server: WSGIServer/0.1 Python/2.7.3 Content-type: text/plain Parsed field named: foo For a more in-depth example showing how the various parts fit together, check out the next section. In-Depth Example ---------------- In this section, we'll build an application that computes the SHA-256 hash of all uploaded files in a streaming manner. To start, we need a simple WSGI application. We could do this with a framework like Flask, Django, or Tornado, but for now let's stick to plain WSGI: .. code-block:: python import multipart def simple_app(environ, start_response): start_response('200 OK', [('Content-type', 'text/plain')]) return ['Hashes:\n'] from wsgiref.simple_server import make_server httpd = make_server('', 8123, simple_app) print("Serving on port 8123...") httpd.serve_forever() You can run this and check with curl that it works properly: .. code-block:: bash $ curl -ik http://localhost:8123/ HTTP/1.0 200 OK Date: Sun, 07 Apr 2013 01:49:03 GMT Server: WSGIServer/0.1 Python/2.7.3 Content-type: text/plain Content-Length: 8 Hashes: Good! It works. Now, let's add some of the code that we need. What we need to do, essentially, is set up the appropriate parser and callbacks so that we can access each portion of the request as it arrives, without needing to store any parts in memory. We can start off by checking if we need to create the parser at all - if the Content-Type isn't `multipart/form-data`, then we're not going to do anything. The final code should look like this: .. code-block:: python import hashlib import multipart from multipart.multipart import parse_options_header def simple_app(environ, start_response): ret = [] # Python 2 doesn't have the "nonlocal" keyword from Python 3, so we get # around it by setting attributes on a dummy object. class g(object): hash = None # This is called when a new part arrives. We create a new hash object # in this callback. def on_part_begin(): g.hash = hashlib.sha256() # We got some data! Update our hash. def on_part_data(data, start, end): g.hash.update(data[start:end]) # Our current part is done, so we can finish the hash. def on_part_end(): ret.append("Part hash: %s" % (g.hash.hexdigest(),)) # Parse the Content-Type header to get the multipart boundary. content_type, params = parse_options_header(environ['CONTENT_TYPE']) boundary = params.get(b'boundary') # Callbacks dictionary. callbacks = { 'on_part_begin': on_part_begin, 'on_part_data': on_part_data, 'on_part_end': on_part_end, } # Create the parser. parser = multipart.MultipartParser(boundary, callbacks) # The input stream is from the WSGI environ. inp = environ['wsgi.input'] # Feed the parser with data from the request. size = int(environ['CONTENT_LENGTH']) while size > 0: to_read = min(size, 1024 * 1024) data = inp.read(to_read) parser.write(data) size -= len(data) if len(data) != to_read: break start_response('200 OK', [('Content-type', 'text/plain')]) return ret from wsgiref.simple_server import make_server httpd = make_server('', 8123, simple_app) print("Serving on port 8123...") httpd.serve_forever() And you can see that this works: .. code-block:: bash $ echo "Foo bar" > /tmp/test.txt $ shasum -a 256 /tmp/test.txt 0b64696c0f7ddb9e3435341720988d5455b3b0f0724688f98ec8e6019af3d931 /tmp/test.txt $ curl -ik -F file=@/tmp/test.txt http://localhost:8123/ HTTP/1.0 200 OK Date: Sun, 07 Apr 2013 02:09:10 GMT Server: WSGIServer/0.1 Python/2.7.3 Content-type: text/plain Hashes: Part hash: 0b64696c0f7ddb9e3435341720988d5455b3b0f0724688f98ec8e6019af3d931 python-multipart-0.0.5/docs_requirements.txt000066400000000000000000000004741336005506300213560ustar00rootroot00000000000000Jinja2==2.6 PyYAML==3.10 Pygments==1.6 Sphinx==1.2b1 cov-core==1.7 coverage==3.6 distribute==0.6.34 docutils==0.10 invoke==0.2.0 mock==1.0.1 pexpect-u==2.5.1 py==1.4.13 pytest==2.3.4 pytest-capturelog==0.7 pytest-cov==1.6 pytest-timeout==0.3 sphinx-bootstrap-theme==0.2.0 tox==1.4.3 virtualenv==1.9.1 wsgiref==0.1.2 python-multipart-0.0.5/multipart/000077500000000000000000000000001336005506300170765ustar00rootroot00000000000000python-multipart-0.0.5/multipart/__init__.py000066400000000000000000000007261336005506300212140ustar00rootroot00000000000000from __future__ import absolute_import import sys # This is the canonical package information. __author__ = 'Andrew Dunham' __license__ = 'Apache' __copyright__ = "Copyright (c) 2012-2013, Andrew Dunham" # We get the version from a sub-file that can be automatically generated. from ._version import __version__ from .multipart import ( FormParser, MultipartParser, QuerystringParser, OctetStreamParser, create_form_parser, parse_form, ) python-multipart-0.0.5/multipart/_version.py000066400000000000000000000000261336005506300212720ustar00rootroot00000000000000__version__ = '0.0.5' python-multipart-0.0.5/multipart/decoders.py000066400000000000000000000137751336005506300212550ustar00rootroot00000000000000import base64 import binascii from .exceptions import Base64Error, DecodeError class Base64Decoder(object): """This object provides an interface to decode a stream of Base64 data. It is instantiated with an "underlying object", and whenever a write() operation is performed, it will decode the incoming data as Base64, and call write() on the underlying object. This is primarily used for decoding form data encoded as Base64, but can be used for other purposes:: from multipart.decoders import Base64Decoder fd = open("notb64.txt", "wb") decoder = Base64Decoder(fd) try: decoder.write("Zm9vYmFy") # "foobar" in Base64 decoder.finalize() finally: decoder.close() # The contents of "notb64.txt" should be "foobar". This object will also pass all finalize() and close() calls to the underlying object, if the underlying object supports them. Note that this class maintains a cache of base64 chunks, so that a write of arbitrary size can be performed. You must call :meth:`finalize` on this object after all writes are completed to ensure that all data is flushed to the underlying object. :param underlying: the underlying object to pass writes to """ def __init__(self, underlying): self.cache = bytearray() self.underlying = underlying def write(self, data): """Takes any input data provided, decodes it as base64, and passes it on to the underlying object. If the data provided is invalid base64 data, then this method will raise a :class:`multipart.exceptions.DecodeError` :param data: base64 data to decode """ # Prepend any cache info to our data. if len(self.cache) > 0: data = self.cache + data # Slice off a string that's a multiple of 4. decode_len = (len(data) // 4) * 4 val = data[:decode_len] # Decode and write, if we have any. if len(val) > 0: try: decoded = base64.b64decode(val) except Base64Error: raise DecodeError('There was an error raised while decoding ' 'base64-encoded data.') self.underlying.write(decoded) # Get the remaining bytes and save in our cache. remaining_len = len(data) % 4 if remaining_len > 0: self.cache = data[-remaining_len:] else: self.cache = b'' # Return the length of the data to indicate no error. return len(data) def close(self): """Close this decoder. If the underlying object has a `close()` method, this function will call it. """ if hasattr(self.underlying, 'close'): self.underlying.close() def finalize(self): """Finalize this object. This should be called when no more data should be written to the stream. This function can raise a :class:`multipart.exceptions.DecodeError` if there is some remaining data in the cache. If the underlying object has a `finalize()` method, this function will call it. """ if len(self.cache) > 0: raise DecodeError('There are %d bytes remaining in the ' 'Base64Decoder cache when finalize() is called' % len(self.cache)) if hasattr(self.underlying, 'finalize'): self.underlying.finalize() def __repr__(self): return "%s(underlying=%r)" % (self.__class__.__name__, self.underlying) class QuotedPrintableDecoder(object): """This object provides an interface to decode a stream of quoted-printable data. It is instantiated with an "underlying object", in the same manner as the :class:`multipart.decoders.Base64Decoder` class. This class behaves in exactly the same way, including maintaining a cache of quoted-printable chunks. :param underlying: the underlying object to pass writes to """ def __init__(self, underlying): self.cache = b'' self.underlying = underlying def write(self, data): """Takes any input data provided, decodes it as quoted-printable, and passes it on to the underlying object. :param data: quoted-printable data to decode """ # Prepend any cache info to our data. if len(self.cache) > 0: data = self.cache + data # If the last 2 characters have an '=' sign in it, then we won't be # able to decode the encoded value and we'll need to save it for the # next decoding step. if data[-2:].find(b'=') != -1: enc, rest = data[:-2], data[-2:] else: enc = data rest = b'' # Encode and write, if we have data. if len(enc) > 0: self.underlying.write(binascii.a2b_qp(enc)) # Save remaining in cache. self.cache = rest return len(data) def close(self): """Close this decoder. If the underlying object has a `close()` method, this function will call it. """ if hasattr(self.underlying, 'close'): self.underlying.close() def finalize(self): """Finalize this object. This should be called when no more data should be written to the stream. This function will not raise any exceptions, but it may write more data to the underlying object if there is data remaining in the cache. If the underlying object has a `finalize()` method, this function will call it. """ # If we have a cache, write and then remove it. if len(self.cache) > 0: self.underlying.write(binascii.a2b_qp(self.cache)) self.cache = b'' # Finalize our underlying stream. if hasattr(self.underlying, 'finalize'): self.underlying.finalize() def __repr__(self): return "%s(underlying=%r)" % (self.__class__.__name__, self.underlying) python-multipart-0.0.5/multipart/exceptions.py000066400000000000000000000032701336005506300216330ustar00rootroot00000000000000import binascii from six import PY3 class FormParserError(ValueError): """Base error class for our form parser.""" pass class ParseError(FormParserError): """This exception (or a subclass) is raised when there is an error while parsing something. """ #: This is the offset in the input data chunk (*NOT* the overall stream) in #: which the parse error occured. It will be -1 if not specified. offset = -1 class MultipartParseError(ParseError): """This is a specific error that is raised when the MultipartParser detects an error while parsing. """ pass class QuerystringParseError(ParseError): """This is a specific error that is raised when the QuerystringParser detects an error while parsing. """ pass class DecodeError(ParseError): """This exception is raised when there is a decoding error - for example with the Base64Decoder or QuotedPrintableDecoder. """ pass # On Python 3.3, IOError is the same as OSError, so we don't want to inherit # from both of them. We handle this case below. if IOError is not OSError: # pragma: no cover class FileError(FormParserError, IOError, OSError): """Exception class for problems with the File class.""" pass else: # pragma: no cover class FileError(FormParserError, OSError): """Exception class for problems with the File class.""" pass # We check which version of Python we're on to figure out what error we need # to catch for invalid Base64. if PY3: # pragma: no cover Base64Error = binascii.Error else: # pragma: no cover Base64Error = TypeError python-multipart-0.0.5/multipart/multipart.py000066400000000000000000002143231336005506300214760ustar00rootroot00000000000000from __future__ import with_statement, absolute_import, print_function from six import ( binary_type, text_type, PY3, ) from .decoders import * from .exceptions import * try: from urlparse import parse_qs except ImportError: from urllib.parse import parse_qs import os import re import sys import shutil import logging import tempfile from io import BytesIO from numbers import Number # Unique missing object. _missing = object() # States for the querystring parser. STATE_BEFORE_FIELD = 0 STATE_FIELD_NAME = 1 STATE_FIELD_DATA = 2 # States for the multipart parser STATE_START = 0 STATE_START_BOUNDARY = 1 STATE_HEADER_FIELD_START = 2 STATE_HEADER_FIELD = 3 STATE_HEADER_VALUE_START = 4 STATE_HEADER_VALUE = 5 STATE_HEADER_VALUE_ALMOST_DONE = 6 STATE_HEADERS_ALMOST_DONE = 7 STATE_PART_DATA_START = 8 STATE_PART_DATA = 9 STATE_PART_DATA_END = 10 STATE_END = 11 STATES = [ "START", "START_BOUNDARY", "HEADER_FEILD_START", "HEADER_FIELD", "HEADER_VALUE_START", "HEADER_VALUE", "HEADER_VALUE_ALMOST_DONE", "HEADRES_ALMOST_DONE", "PART_DATA_START", "PART_DATA", "PART_DATA_END", "END" ] # Flags for the multipart parser. FLAG_PART_BOUNDARY = 1 FLAG_LAST_BOUNDARY = 2 # Get constants. Since iterating over a str on Python 2 gives you a 1-length # string, but iterating over a bytes object on Python 3 gives you an integer, # we need to save these constants. CR = b'\r'[0] LF = b'\n'[0] COLON = b':'[0] SPACE = b' '[0] HYPHEN = b'-'[0] AMPERSAND = b'&'[0] SEMICOLON = b';'[0] LOWER_A = b'a'[0] LOWER_Z = b'z'[0] NULL = b'\x00'[0] # Lower-casing a character is different, because of the difference between # str on Py2, and bytes on Py3. Same with getting the ordinal value of a byte, # and joining a list of bytes together. # These functions abstract that. if PY3: # pragma: no cover lower_char = lambda c: c | 0x20 ord_char = lambda c: c join_bytes = lambda b: bytes(list(b)) else: # pragma: no cover lower_char = lambda c: c.lower() ord_char = lambda c: ord(c) join_bytes = lambda b: b''.join(list(b)) # These are regexes for parsing header values. SPECIAL_CHARS = re.escape(b'()<>@,;:\\"/[]?={} \t') QUOTED_STR = br'"(?:\\.|[^"])*"' VALUE_STR = br'(?:[^' + SPECIAL_CHARS + br']+|' + QUOTED_STR + br')' OPTION_RE_STR = ( br'(?:;|^)\s*([^' + SPECIAL_CHARS + br']+)\s*=\s*(' + VALUE_STR + br')' ) OPTION_RE = re.compile(OPTION_RE_STR) QUOTE = b'"'[0] def parse_options_header(value): """ Parses a Content-Type header into a value in the following format: (content_type, {parameters}) """ if not value: return (b'', {}) # If we are passed a string, we assume that it conforms to WSGI and does # not contain any code point that's not in latin-1. if isinstance(value, text_type): # pragma: no cover value = value.encode('latin-1') # If we have no options, return the string as-is. if b';' not in value: return (value.lower().strip(), {}) # Split at the first semicolon, to get our value and then options. ctype, rest = value.split(b';', 1) options = {} # Parse the options. for match in OPTION_RE.finditer(rest): key = match.group(1).lower() value = match.group(2) if value[0] == QUOTE and value[-1] == QUOTE: # Unquote the value. value = value[1:-1] value = value.replace(b'\\\\', b'\\').replace(b'\\"', b'"') # If the value is a filename, we need to fix a bug on IE6 that sends # the full file path instead of the filename. if key == b'filename': if value[1:3] == b':\\' or value[:2] == b'\\\\': value = value.split(b'\\')[-1] options[key] = value return ctype, options class Field(object): """A Field object represents a (parsed) form field. It represents a single field with a corresponding name and value. The name that a :class:`Field` will be instantiated with is the same name that would be found in the following HTML:: This class defines two methods, :meth:`on_data` and :meth:`on_end`, that will be called when data is written to the Field, and when the Field is finalized, respectively. :param name: the name of the form field """ def __init__(self, name): self._name = name self._value = [] # We cache the joined version of _value for speed. self._cache = _missing @classmethod def from_value(klass, name, value): """Create an instance of a :class:`Field`, and set the corresponding value - either None or an actual value. This method will also finalize the Field itself. :param name: the name of the form field :param value: the value of the form field - either a bytestring or None """ f = klass(name) if value is None: f.set_none() else: f.write(value) f.finalize() return f def write(self, data): """Write some data into the form field. :param data: a bytestring """ return self.on_data(data) def on_data(self, data): """This method is a callback that will be called whenever data is written to the Field. :param data: a bytestring """ self._value.append(data) self._cache = _missing return len(data) def on_end(self): """This method is called whenever the Field is finalized. """ if self._cache is _missing: self._cache = b''.join(self._value) def finalize(self): """Finalize the form field. """ self.on_end() def close(self): """Close the Field object. This will free any underlying cache. """ # Free our value array. if self._cache is _missing: self._cache = b''.join(self._value) del self._value def set_none(self): """Some fields in a querystring can possibly have a value of None - for example, the string "foo&bar=&baz=asdf" will have a field with the name "foo" and value None, one with name "bar" and value "", and one with name "baz" and value "asdf". Since the write() interface doesn't support writing None, this function will set the field value to None. """ self._cache = None @property def field_name(self): """This property returns the name of the field.""" return self._name @property def value(self): """This property returns the value of the form field.""" if self._cache is _missing: self._cache = b''.join(self._value) return self._cache def __eq__(self, other): if isinstance(other, Field): return ( self.field_name == other.field_name and self.value == other.value ) else: return NotImplemented def __repr__(self): if len(self.value) > 97: # We get the repr, and then insert three dots before the final # quote. v = repr(self.value[:97])[:-1] + "...'" else: v = repr(self.value) return "%s(field_name=%r, value=%s)" % ( self.__class__.__name__, self.field_name, v ) class File(object): """This class represents an uploaded file. It handles writing file data to either an in-memory file or a temporary file on-disk, if the optional threshold is passed. There are some options that can be passed to the File to change behavior of the class. Valid options are as follows: .. list-table:: :widths: 15 5 5 30 :header-rows: 1 * - Name - Type - Default - Description * - UPLOAD_DIR - `str` - None - The directory to store uploaded files in. If this is None, a temporary file will be created in the system's standard location. * - UPLOAD_DELETE_TMP - `bool` - True - Delete automatically created TMP file * - UPLOAD_KEEP_FILENAME - `bool` - False - Whether or not to keep the filename of the uploaded file. If True, then the filename will be converted to a safe representation (e.g. by removing any invalid path segments), and then saved with the same name). Otherwise, a temporary name will be used. * - UPLOAD_KEEP_EXTENSIONS - `bool` - False - Whether or not to keep the uploaded file's extension. If False, the file will be saved with the default temporary extension (usually ".tmp"). Otherwise, the file's extension will be maintained. Note that this will properly combine with the UPLOAD_KEEP_FILENAME setting. * - MAX_MEMORY_FILE_SIZE - `int` - 1 MiB - The maximum number of bytes of a File to keep in memory. By default, the contents of a File are kept into memory until a certain limit is reached, after which the contents of the File are written to a temporary file. This behavior can be disabled by setting this value to an appropriately large value (or, for example, infinity, such as `float('inf')`. :param file_name: The name of the file that this :class:`File` represents :param field_name: The field name that uploaded this file. Note that this can be None, if, for example, the file was uploaded with Content-Type application/octet-stream :param config: The configuration for this File. See above for valid configuration keys and their corresponding values. """ def __init__(self, file_name, field_name=None, config={}): # Save configuration, set other variables default. self.logger = logging.getLogger(__name__) self._config = config self._in_memory = True self._bytes_written = 0 self._fileobj = BytesIO() # Save the provided field/file name. self._field_name = field_name self._file_name = file_name # Our actual file name is None by default, since, depending on our # config, we may not actually use the provided name. self._actual_file_name = None # Split the extension from the filename. if file_name is not None: base, ext = os.path.splitext(file_name) self._file_base = base self._ext = ext @property def field_name(self): """The form field associated with this file. May be None if there isn't one, for example when we have an application/octet-stream upload. """ return self._field_name @property def file_name(self): """The file name given in the upload request. """ return self._file_name @property def actual_file_name(self): """The file name that this file is saved as. Will be None if it's not currently saved on disk. """ return self._actual_file_name @property def file_object(self): """The file object that we're currently writing to. Note that this will either be an instance of a :class:`io.BytesIO`, or a regular file object. """ return self._fileobj @property def size(self): """The total size of this file, counted as the number of bytes that currently have been written to the file. """ return self._bytes_written @property def in_memory(self): """A boolean representing whether or not this file object is currently stored in-memory or on-disk. """ return self._in_memory def flush_to_disk(self): """If the file is already on-disk, do nothing. Otherwise, copy from the in-memory buffer to a disk file, and then reassign our internal file object to this new disk file. Note that if you attempt to flush a file that is already on-disk, a warning will be logged to this module's logger. """ if not self._in_memory: self.logger.warning( "Trying to flush to disk when we're not in memory" ) return # Go back to the start of our file. self._fileobj.seek(0) # Open a new file. new_file = self._get_disk_file() # Copy the file objects. shutil.copyfileobj(self._fileobj, new_file) # Seek to the new position in our new file. new_file.seek(self._bytes_written) # Reassign the fileobject. old_fileobj = self._fileobj self._fileobj = new_file # We're no longer in memory. self._in_memory = False # Close the old file object. old_fileobj.close() def _get_disk_file(self): """This function is responsible for getting a file object on-disk for us. """ self.logger.info("Opening a file on disk") file_dir = self._config.get('UPLOAD_DIR') keep_filename = self._config.get('UPLOAD_KEEP_FILENAME', False) keep_extensions = self._config.get('UPLOAD_KEEP_EXTENSIONS', False) delete_tmp = self._config.get('UPLOAD_DELETE_TMP', True) # If we have a directory and are to keep the filename... if file_dir is not None and keep_filename: self.logger.info("Saving with filename in: %r", file_dir) # Build our filename. # TODO: what happens if we don't have a filename? fname = self._file_base if keep_extensions: fname = fname + self._ext path = os.path.join(file_dir, fname) try: self.logger.info("Opening file: %r", path) tmp_file = open(path, 'w+b') except (IOError, OSError) as e: tmp_file = None self.logger.exception("Error opening temporary file") raise FileError("Error opening temporary file: %r" % path) else: # Build options array. # Note that on Python 3, tempfile doesn't support byte names. We # encode our paths using the default filesystem encoding. options = {} if keep_extensions: ext = self._ext if isinstance(ext, binary_type): ext = ext.decode(sys.getfilesystemencoding()) options['suffix'] = ext if file_dir is not None: d = file_dir if isinstance(d, binary_type): d = d.decode(sys.getfilesystemencoding()) options['dir'] = d options['delete'] = delete_tmp # Create a temporary (named) file with the appropriate settings. self.logger.info("Creating a temporary file with options: %r", options) try: tmp_file = tempfile.NamedTemporaryFile(**options) except (IOError, OSError): self.logger.exception("Error creating named temporary file") raise FileError("Error creating named temporary file") fname = tmp_file.name # Encode filename as bytes. if isinstance(fname, text_type): fname = fname.encode(sys.getfilesystemencoding()) self._actual_file_name = fname return tmp_file def write(self, data): """Write some data to the File. :param data: a bytestring """ return self.on_data(data) def on_data(self, data): """This method is a callback that will be called whenever data is written to the File. :param data: a bytestring """ pos = self._fileobj.tell() bwritten = self._fileobj.write(data) # true file objects write returns None if bwritten is None: bwritten = self._fileobj.tell() - pos # If the bytes written isn't the same as the length, just return. if bwritten != len(data): self.logger.warning("bwritten != len(data) (%d != %d)", bwritten, len(data)) return bwritten # Keep track of how many bytes we've written. self._bytes_written += bwritten # If we're in-memory and are over our limit, we create a file. if (self._in_memory and self._config.get('MAX_MEMORY_FILE_SIZE') is not None and (self._bytes_written > self._config.get('MAX_MEMORY_FILE_SIZE'))): self.logger.info("Flushing to disk") self.flush_to_disk() # Return the number of bytes written. return bwritten def on_end(self): """This method is called whenever the Field is finalized. """ # Flush the underlying file object self._fileobj.flush() def finalize(self): """Finalize the form file. This will not close the underlying file, but simply signal that we are finished writing to the File. """ self.on_end() def close(self): """Close the File object. This will actually close the underlying file object (whether it's a :class:`io.BytesIO` or an actual file object). """ self._fileobj.close() def __repr__(self): return "%s(file_name=%r, field_name=%r)" % ( self.__class__.__name__, self.file_name, self.field_name ) class BaseParser(object): """This class is the base class for all parsers. It contains the logic for calling and adding callbacks. A callback can be one of two different forms. "Notification callbacks" are callbacks that are called when something happens - for example, when a new part of a multipart message is encountered by the parser. "Data callbacks" are called when we get some sort of data - for example, part of the body of a multipart chunk. Notification callbacks are called with no parameters, whereas data callbacks are called with three, as follows:: data_callback(data, start, end) The "data" parameter is a bytestring (i.e. "foo" on Python 2, or b"foo" on Python 3). "start" and "end" are integer indexes into the "data" string that represent the data of interest. Thus, in a data callback, the slice `data[start:end]` represents the data that the callback is "interested in". The callback is not passed a copy of the data, since copying severely hurts performance. """ def __init__(self): self.logger = logging.getLogger(__name__) def callback(self, name, data=None, start=None, end=None): """This function calls a provided callback with some data. If the callback is not set, will do nothing. :param name: The name of the callback to call (as a string). :param data: Data to pass to the callback. If None, then it is assumed that the callback is a notification callback, and no parameters are given. :param end: An integer that is passed to the data callback. :param start: An integer that is passed to the data callback. """ name = "on_" + name func = self.callbacks.get(name) if func is None: return # Depending on whether we're given a buffer... if data is not None: # Don't do anything if we have start == end. if start is not None and start == end: return self.logger.debug("Calling %s with data[%d:%d]", name, start, end) func(data, start, end) else: self.logger.debug("Calling %s with no data", name) func() def set_callback(self, name, new_func): """Update the function for a callback. Removes from the callbacks dict if new_func is None. :param name: The name of the callback to call (as a string). :param new_func: The new function for the callback. If None, then the callback will be removed (with no error if it does not exist). """ if new_func is None: self.callbacks.pop('on_' + name, None) else: self.callbacks['on_' + name] = new_func def close(self): pass # pragma: no cover def finalize(self): pass # pragma: no cover def __repr__(self): return "%s()" % self.__class__.__name__ class OctetStreamParser(BaseParser): """This parser parses an octet-stream request body and calls callbacks when incoming data is received. Callbacks are as follows: .. list-table:: :widths: 15 10 30 :header-rows: 1 * - Callback Name - Parameters - Description * - on_start - None - Called when the first data is parsed. * - on_data - data, start, end - Called for each data chunk that is parsed. * - on_end - None - Called when the parser is finished parsing all data. :param callbacks: A dictionary of callbacks. See the documentation for :class:`BaseParser`. :param max_size: The maximum size of body to parse. Defaults to infinity - i.e. unbounded. """ def __init__(self, callbacks={}, max_size=float('inf')): super(OctetStreamParser, self).__init__() self.callbacks = callbacks self._started = False if not isinstance(max_size, Number) or max_size < 1: raise ValueError("max_size must be a positive number, not %r" % max_size) self.max_size = max_size self._current_size = 0 def write(self, data): """Write some data to the parser, which will perform size verification, and then pass the data to the underlying callback. :param data: a bytestring """ if not self._started: self.callback('start') self._started = True # Truncate data length. data_len = len(data) if (self._current_size + data_len) > self.max_size: # We truncate the length of data that we are to process. new_size = int(self.max_size - self._current_size) self.logger.warning("Current size is %d (max %d), so truncating " "data length from %d to %d", self._current_size, self.max_size, data_len, new_size) data_len = new_size # Increment size, then callback, in case there's an exception. self._current_size += data_len self.callback('data', data, 0, data_len) return data_len def finalize(self): """Finalize this parser, which signals to that we are finished parsing, and sends the on_end callback. """ self.callback('end') def __repr__(self): return "%s()" % self.__class__.__name__ class QuerystringParser(BaseParser): """This is a streaming querystring parser. It will consume data, and call the callbacks given when it has data. .. list-table:: :widths: 15 10 30 :header-rows: 1 * - Callback Name - Parameters - Description * - on_field_start - None - Called when a new field is encountered. * - on_field_name - data, start, end - Called when a portion of a field's name is encountered. * - on_field_data - data, start, end - Called when a portion of a field's data is encountered. * - on_field_end - None - Called when the end of a field is encountered. * - on_end - None - Called when the parser is finished parsing all data. :param callbacks: A dictionary of callbacks. See the documentation for :class:`BaseParser`. :param strict_parsing: Whether or not to parse the body strictly. Defaults to False. If this is set to True, then the behavior of the parser changes as the following: if a field has a value with an equal sign (e.g. "foo=bar", or "foo="), it is always included. If a field has no equals sign (e.g. "...&name&..."), it will be treated as an error if 'strict_parsing' is True, otherwise included. If an error is encountered, then a :class:`multipart.exceptions.QuerystringParseError` will be raised. :param max_size: The maximum size of body to parse. Defaults to infinity - i.e. unbounded. """ def __init__(self, callbacks={}, strict_parsing=False, max_size=float('inf')): super(QuerystringParser, self).__init__() self.state = STATE_BEFORE_FIELD self._found_sep = False self.callbacks = callbacks # Max-size stuff if not isinstance(max_size, Number) or max_size < 1: raise ValueError("max_size must be a positive number, not %r" % max_size) self.max_size = max_size self._current_size = 0 # Should parsing be strict? self.strict_parsing = strict_parsing def write(self, data): """Write some data to the parser, which will perform size verification, parse into either a field name or value, and then pass the corresponding data to the underlying callback. If an error is encountered while parsing, a QuerystringParseError will be raised. The "offset" attribute of the raised exception will be set to the offset in the input data chunk (NOT the overall stream) that caused the error. :param data: a bytestring """ # Handle sizing. data_len = len(data) if (self._current_size + data_len) > self.max_size: # We truncate the length of data that we are to process. new_size = int(self.max_size - self._current_size) self.logger.warning("Current size is %d (max %d), so truncating " "data length from %d to %d", self._current_size, self.max_size, data_len, new_size) data_len = new_size l = 0 try: l = self._internal_write(data, data_len) finally: self._current_size += l return l def _internal_write(self, data, length): state = self.state strict_parsing = self.strict_parsing found_sep = self._found_sep i = 0 while i < length: ch = data[i] # Depending on our state... if state == STATE_BEFORE_FIELD: # If the 'found_sep' flag is set, we've already encountered # and skipped a single seperator. If so, we check our strict # parsing flag and decide what to do. Otherwise, we haven't # yet reached a seperator, and thus, if we do, we need to skip # it as it will be the boundary between fields that's supposed # to be there. if ch == AMPERSAND or ch == SEMICOLON: if found_sep: # If we're parsing strictly, we disallow blank chunks. if strict_parsing: e = QuerystringParseError( "Skipping duplicate ampersand/semicolon at " "%d" % i ) e.offset = i raise e else: self.logger.debug("Skipping duplicate ampersand/" "semicolon at %d", i) else: # This case is when we're skipping the (first) # seperator between fields, so we just set our flag # and continue on. found_sep = True else: # Emit a field-start event, and go to that state. Also, # reset the "found_sep" flag, for the next time we get to # this state. self.callback('field_start') i -= 1 state = STATE_FIELD_NAME found_sep = False elif state == STATE_FIELD_NAME: # Try and find a seperator - we ensure that, if we do, we only # look for the equal sign before it. sep_pos = data.find(b'&', i) if sep_pos == -1: sep_pos = data.find(b';', i) # See if we can find an equals sign in the remaining data. If # so, we can immedately emit the field name and jump to the # data state. if sep_pos != -1: equals_pos = data.find(b'=', i, sep_pos) else: equals_pos = data.find(b'=', i) if equals_pos != -1: # Emit this name. self.callback('field_name', data, i, equals_pos) # Jump i to this position. Note that it will then have 1 # added to it below, which means the next iteration of this # loop will inspect the character after the equals sign. i = equals_pos state = STATE_FIELD_DATA else: # No equals sign found. if not strict_parsing: # See also comments in the STATE_FIELD_DATA case below. # If we found the seperator, we emit the name and just # end - there's no data callback at all (not even with # a blank value). if sep_pos != -1: self.callback('field_name', data, i, sep_pos) self.callback('field_end') i = sep_pos - 1 state = STATE_BEFORE_FIELD else: # Otherwise, no seperator in this block, so the # rest of this chunk must be a name. self.callback('field_name', data, i, length) i = length else: # We're parsing strictly. If we find a seperator, # this is an error - we require an equals sign. if sep_pos != -1: e = QuerystringParseError( "When strict_parsing is True, we require an " "equals sign in all field chunks. Did not " "find one in the chunk that starts at %d" % (i,) ) e.offset = i raise e # No seperator in the rest of this chunk, so it's just # a field name. self.callback('field_name', data, i, length) i = length elif state == STATE_FIELD_DATA: # Try finding either an ampersand or a semicolon after this # position. sep_pos = data.find(b'&', i) if sep_pos == -1: sep_pos = data.find(b';', i) # If we found it, callback this bit as data and then go back # to expecting to find a field. if sep_pos != -1: self.callback('field_data', data, i, sep_pos) self.callback('field_end') # Note that we go to the seperator, which brings us to the # "before field" state. This allows us to properly emit # "field_start" events only when we actually have data for # a field of some sort. i = sep_pos - 1 state = STATE_BEFORE_FIELD # Otherwise, emit the rest as data and finish. else: self.callback('field_data', data, i, length) i = length else: # pragma: no cover (error case) msg = "Reached an unknown state %d at %d" % (state, i) self.logger.warning(msg) e = QuerystringParseError(msg) e.offset = i raise e i += 1 self.state = state self._found_sep = found_sep return len(data) def finalize(self): """Finalize this parser, which signals to that we are finished parsing, if we're still in the middle of a field, an on_field_end callback, and then the on_end callback. """ # If we're currently in the middle of a field, we finish it. if self.state == STATE_FIELD_DATA: self.callback('field_end') self.callback('end') def __repr__(self): return "%s(keep_blank_values=%r, strict_parsing=%r, max_size=%r)" % ( self.__class__.__name__, self.keep_blank_values, self.strict_parsing, self.max_size ) class MultipartParser(BaseParser): """This class is a streaming multipart/form-data parser. .. list-table:: :widths: 15 10 30 :header-rows: 1 * - Callback Name - Parameters - Description * - on_part_begin - None - Called when a new part of the multipart message is encountered. * - on_part_data - data, start, end - Called when a portion of a part's data is encountered. * - on_part_end - None - Called when the end of a part is reached. * - on_header_begin - None - Called when we've found a new header in a part of a multipart message * - on_header_field - data, start, end - Called each time an additional portion of a header is read (i.e. the part of the header that is before the colon; the "Foo" in "Foo: Bar"). * - on_header_value - data, start, end - Called when we get data for a header. * - on_header_end - None - Called when the current header is finished - i.e. we've reached the newline at the end of the header. * - on_headers_finished - None - Called when all headers are finished, and before the part data starts. * - on_end - None - Called when the parser is finished parsing all data. :param boundary: The multipart boundary. This is required, and must match what is given in the HTTP request - usually in the Content-Type header. :param callbacks: A dictionary of callbacks. See the documentation for :class:`BaseParser`. :param max_size: The maximum size of body to parse. Defaults to infinity - i.e. unbounded. """ def __init__(self, boundary, callbacks={}, max_size=float('inf')): # Initialize parser state. super(MultipartParser, self).__init__() self.state = STATE_START self.index = self.flags = 0 self.callbacks = callbacks if not isinstance(max_size, Number) or max_size < 1: raise ValueError("max_size must be a positive number, not %r" % max_size) self.max_size = max_size self._current_size = 0 # Setup marks. These are used to track the state of data recieved. self.marks = {} # TODO: Actually use this rather than the dumb version we currently use # # Precompute the skip table for the Boyer-Moore-Horspool algorithm. # skip = [len(boundary) for x in range(256)] # for i in range(len(boundary) - 1): # skip[ord_char(boundary[i])] = len(boundary) - i - 1 # # # We use a tuple since it's a constant, and marginally faster. # self.skip = tuple(skip) # Save our boundary. if isinstance(boundary, text_type): # pragma: no cover boundary = boundary.encode('latin-1') self.boundary = b'\r\n--' + boundary # Get a set of characters that belong to our boundary. self.boundary_chars = frozenset(self.boundary) # We also create a lookbehind list. # Note: the +8 is since we can have, at maximum, "\r\n--" + boundary + # "--\r\n" at the final boundary, and the length of '\r\n--' and # '--\r\n' is 8 bytes. self.lookbehind = [NULL for x in range(len(boundary) + 8)] def write(self, data): """Write some data to the parser, which will perform size verification, and then parse the data into the appropriate location (e.g. header, data, etc.), and pass this on to the underlying callback. If an error is encountered, a MultipartParseError will be raised. The "offset" attribute on the raised exception will be set to the offset of the byte in the input chunk that caused the error. :param data: a bytestring """ # Handle sizing. data_len = len(data) if (self._current_size + data_len) > self.max_size: # We truncate the length of data that we are to process. new_size = int(self.max_size - self._current_size) self.logger.warning("Current size is %d (max %d), so truncating " "data length from %d to %d", self._current_size, self.max_size, data_len, new_size) data_len = new_size l = 0 try: l = self._internal_write(data, data_len) finally: self._current_size += l return l def _internal_write(self, data, length): # Get values from locals. boundary = self.boundary # Get our state, flags and index. These are persisted between calls to # this function. state = self.state index = self.index flags = self.flags # Our index defaults to 0. i = 0 # Set a mark. def set_mark(name): self.marks[name] = i # Remove a mark. def delete_mark(name, reset=False): self.marks.pop(name, None) # Helper function that makes calling a callback with data easier. The # 'remaining' parameter will callback from the marked value until the # end of the buffer, and reset the mark, instead of deleting it. This # is used at the end of the function to call our callbacks with any # remaining data in this chunk. def data_callback(name, remaining=False): marked_index = self.marks.get(name) if marked_index is None: return # If we're getting remaining data, we ignore the current i value # and just call with the remaining data. if remaining: self.callback(name, data, marked_index, length) self.marks[name] = 0 # Otherwise, we call it from the mark to the current byte we're # processing. else: self.callback(name, data, marked_index, i) self.marks.pop(name, None) # For each byte... while i < length: c = data[i] if state == STATE_START: # Skip leading newlines if c == CR or c == LF: i += 1 self.logger.debug("Skipping leading CR/LF at %d", i) continue # index is used as in index into our boundary. Set to 0. index = 0 # Move to the next state, but decrement i so that we re-process # this character. state = STATE_START_BOUNDARY i -= 1 elif state == STATE_START_BOUNDARY: # Check to ensure that the last 2 characters in our boundary # are CRLF. if index == len(boundary) - 2: if c != CR: # Error! msg = "Did not find CR at end of boundary (%d)" % (i,) self.logger.warning(msg) e = MultipartParseError(msg) e.offset = i raise e index += 1 elif index == len(boundary) - 2 + 1: if c != LF: msg = "Did not find LF at end of boundary (%d)" % (i,) self.logger.warning(msg) e = MultipartParseError(msg) e.offset = i raise e # The index is now used for indexing into our boundary. index = 0 # Callback for the start of a part. self.callback('part_begin') # Move to the next character and state. state = STATE_HEADER_FIELD_START else: # Check to ensure our boundary matches if c != boundary[index + 2]: msg = "Did not find boundary character %r at index " \ "%d" % (c, index + 2) self.logger.warning(msg) e = MultipartParseError(msg) e.offset = i raise e # Increment index into boundary and continue. index += 1 elif state == STATE_HEADER_FIELD_START: # Mark the start of a header field here, reset the index, and # continue parsing our header field. index = 0 # Set a mark of our header field. set_mark('header_field') # Move to parsing header fields. state = STATE_HEADER_FIELD i -= 1 elif state == STATE_HEADER_FIELD: # If we've reached a CR at the beginning of a header, it means # that we've reached the second of 2 newlines, and so there are # no more headers to parse. if c == CR: delete_mark('header_field') state = STATE_HEADERS_ALMOST_DONE i += 1 continue # Increment our index in the header. index += 1 # Do nothing if we encounter a hyphen. if c == HYPHEN: pass # If we've reached a colon, we're done with this header. elif c == COLON: # A 0-length header is an error. if index == 1: msg = "Found 0-length header at %d" % (i,) self.logger.warning(msg) e = MultipartParseError(msg) e.offset = i raise e # Call our callback with the header field. data_callback('header_field') # Move to parsing the header value. state = STATE_HEADER_VALUE_START else: # Lower-case this character, and ensure that it is in fact # a valid letter. If not, it's an error. cl = lower_char(c) if cl < LOWER_A or cl > LOWER_Z: msg = "Found non-alphanumeric character %r in " \ "header at %d" % (c, i) self.logger.warning(msg) e = MultipartParseError(msg) e.offset = i raise e elif state == STATE_HEADER_VALUE_START: # Skip leading spaces. if c == SPACE: i += 1 continue # Mark the start of the header value. set_mark('header_value') # Move to the header-value state, reprocessing this character. state = STATE_HEADER_VALUE i -= 1 elif state == STATE_HEADER_VALUE: # If we've got a CR, we're nearly done our headers. Otherwise, # we do nothing and just move past this character. if c == CR: data_callback('header_value') self.callback('header_end') state = STATE_HEADER_VALUE_ALMOST_DONE elif state == STATE_HEADER_VALUE_ALMOST_DONE: # The last character should be a LF. If not, it's an error. if c != LF: msg = "Did not find LF character at end of header " \ "(found %r)" % (c,) self.logger.warning(msg) e = MultipartParseError(msg) e.offset = i raise e # Move back to the start of another header. Note that if that # state detects ANOTHER newline, it'll trigger the end of our # headers. state = STATE_HEADER_FIELD_START elif state == STATE_HEADERS_ALMOST_DONE: # We're almost done our headers. This is reached when we parse # a CR at the beginning of a header, so our next character # should be a LF, or it's an error. if c != LF: msg = "Did not find LF at end of headers (found %r)" % (c,) self.logger.warning(msg) e = MultipartParseError(msg) e.offset = i raise e self.callback('headers_finished') state = STATE_PART_DATA_START elif state == STATE_PART_DATA_START: # Mark the start of our part data. set_mark('part_data') # Start processing part data, including this character. state = STATE_PART_DATA i -= 1 elif state == STATE_PART_DATA: # We're processing our part data right now. During this, we # need to efficiently search for our boundary, since any data # on any number of lines can be a part of the current data. # We use the Boyer-Moore-Horspool algorithm to efficiently # search through the remainder of the buffer looking for our # boundary. # Save the current value of our index. We use this in case we # find part of a boundary, but it doesn't match fully. prev_index = index # Set up variables. boundary_length = len(boundary) boundary_end = boundary_length - 1 data_length = length boundary_chars = self.boundary_chars # If our index is 0, we're starting a new part, so start our # search. if index == 0: # Search forward until we either hit the end of our buffer, # or reach a character that's in our boundary. i += boundary_end while i < data_length - 1 and data[i] not in boundary_chars: i += boundary_length # Reset i back the length of our boundary, which is the # earliest possible location that could be our match (i.e. # if we've just broken out of our loop since we saw the # last character in our boundary) i -= boundary_end c = data[i] # Now, we have a couple of cases here. If our index is before # the end of the boundary... if index < boundary_length: # If the character matches... if boundary[index] == c: # If we found a match for our boundary, we send the # existing data. if index == 0: data_callback('part_data') # The current character matches, so continue! index += 1 else: index = 0 # Our index is equal to the length of our boundary! elif index == boundary_length: # First we increment it. index += 1 # Now, if we've reached a newline, we need to set this as # the potential end of our boundary. if c == CR: flags |= FLAG_PART_BOUNDARY # Otherwise, if this is a hyphen, we might be at the last # of all boundaries. elif c == HYPHEN: flags |= FLAG_LAST_BOUNDARY # Otherwise, we reset our index, since this isn't either a # newline or a hyphen. else: index = 0 # Our index is right after the part boundary, which should be # a LF. elif index == boundary_length + 1: # If we're at a part boundary (i.e. we've seen a CR # character already)... if flags & FLAG_PART_BOUNDARY: # We need a LF character next. if c == LF: # Unset the part boundary flag. flags &= (~FLAG_PART_BOUNDARY) # Callback indicating that we've reached the end of # a part, and are starting a new one. self.callback('part_end') self.callback('part_begin') # Move to parsing new headers. index = 0 state = STATE_HEADER_FIELD_START i += 1 continue # We didn't find an LF character, so no match. Reset # our index and clear our flag. index = 0 flags &= (~FLAG_PART_BOUNDARY) # Otherwise, if we're at the last boundary (i.e. we've # seen a hyphen already)... elif flags & FLAG_LAST_BOUNDARY: # We need a second hyphen here. if c == HYPHEN: # Callback to end the current part, and then the # message. self.callback('part_end') self.callback('end') state = STATE_END else: # No match, so reset index. index = 0 # If we have an index, we need to keep this byte for later, in # case we can't match the full boundary. if index > 0: self.lookbehind[index - 1] = c # Otherwise, our index is 0. If the previous index is not, it # means we reset something, and we need to take the data we # thought was part of our boundary and send it along as actual # data. elif prev_index > 0: # Callback to write the saved data. lb_data = join_bytes(self.lookbehind) self.callback('part_data', lb_data, 0, prev_index) # Overwrite our previous index. prev_index = 0 # Re-set our mark for part data. set_mark('part_data') # Re-consider the current character, since this could be # the start of the boundary itself. i -= 1 elif state == STATE_END: # Do nothing and just consume a byte in the end state. if c not in (CR, LF): self.logger.warning("Consuming a byte '0x%x' in the end state", c) else: # pragma: no cover (error case) # We got into a strange state somehow! Just stop processing. msg = "Reached an unknown state %d at %d" % (state, i) self.logger.warning(msg) e = MultipartParseError(msg) e.offset = i raise e # Move to the next byte. i += 1 # We call our callbacks with any remaining data. Note that we pass # the 'remaining' flag, which sets the mark back to 0 instead of # deleting it, if it's found. This is because, if the mark is found # at this point, we assume that there's data for one of these things # that has been parsed, but not yet emitted. And, as such, it implies # that we haven't yet reached the end of this 'thing'. So, by setting # the mark to 0, we cause any data callbacks that take place in future # calls to this function to start from the beginning of that buffer. data_callback('header_field', True) data_callback('header_value', True) data_callback('part_data', True) # Save values to locals. self.state = state self.index = index self.flags = flags # Return our data length to indicate no errors, and that we processed # all of it. return length def finalize(self): """Finalize this parser, which signals to that we are finished parsing. Note: It does not currently, but in the future, it will verify that we are in the final state of the parser (i.e. the end of the multipart message is well-formed), and, if not, throw an error. """ # TODO: verify that we're in the state STATE_END, otherwise throw an # error or otherwise state that we're not finished parsing. pass def __repr__(self): return "%s(boundary=%r)" % (self.__class__.__name__, self.boundary) class FormParser(object): """This class is the all-in-one form parser. Given all the information necessary to parse a form, it will instantiate the correct parser, create the proper :class:`Field` and :class:`File` classes to store the data that is parsed, and call the two given callbacks with each field and file as they become available. :param content_type: The Content-Type of the incoming request. This is used to select the appropriate parser. :param on_field: The callback to call when a field has been parsed and is ready for usage. See above for parameters. :param on_file: The callback to call when a file has been parsed and is ready for usage. See above for parameters. :param on_end: An optional callback to call when all fields and files in a request has been parsed. Can be None. :param boundary: If the request is a multipart/form-data request, this should be the boundary of the request, as given in the Content-Type header, as a bytestring. :param file_name: If the request is of type application/octet-stream, then the body of the request will not contain any information about the uploaded file. In such cases, you can provide the file name of the uploaded file manually. :param FileClass: The class to use for uploaded files. Defaults to :class:`File`, but you can provide your own class if you wish to customize behaviour. The class will be instantiated as FileClass(file_name, field_name), and it must provide the folllowing functions:: file_instance.write(data) file_instance.finalize() file_instance.close() :param FieldClass: The class to use for uploaded fields. Defaults to :class:`Field`, but you can provide your own class if you wish to customize behaviour. The class will be instantiated as FieldClass(field_name), and it must provide the folllowing functions:: field_instance.write(data) field_instance.finalize() field_instance.close() :param config: Configuration to use for this FormParser. The default values are taken from the DEFAULT_CONFIG value, and then any keys present in this dictionary will overwrite the default values. """ #: This is the default configuration for our form parser. #: Note: all file sizes should be in bytes. DEFAULT_CONFIG = { 'MAX_BODY_SIZE': float('inf'), 'MAX_MEMORY_FILE_SIZE': 1 * 1024 * 1024, 'UPLOAD_DIR': None, 'UPLOAD_KEEP_FILENAME': False, 'UPLOAD_KEEP_EXTENSIONS': False, # Error on invalid Content-Transfer-Encoding? 'UPLOAD_ERROR_ON_BAD_CTE': False, } def __init__(self, content_type, on_field, on_file, on_end=None, boundary=None, file_name=None, FileClass=File, FieldClass=Field, config={}): self.logger = logging.getLogger(__name__) # Save variables. self.content_type = content_type self.boundary = boundary self.bytes_received = 0 self.parser = None # Save callbacks. self.on_field = on_field self.on_file = on_file self.on_end = on_end # Save classes. self.FileClass = File self.FieldClass = Field # Set configuration options. self.config = self.DEFAULT_CONFIG.copy() self.config.update(config) # Depending on the Content-Type, we instantiate the correct parser. if content_type == 'application/octet-stream': # Work around the lack of 'nonlocal' in Py2 class vars(object): f = None def on_start(): vars.f = FileClass(file_name, None, config=self.config) def on_data(data, start, end): vars.f.write(data[start:end]) def on_end(): # Finalize the file itself. vars.f.finalize() # Call our callback. on_file(vars.f) # Call the on-end callback. if self.on_end is not None: self.on_end() callbacks = { 'on_start': on_start, 'on_data': on_data, 'on_end': on_end, } # Instantiate an octet-stream parser parser = OctetStreamParser(callbacks, max_size=self.config['MAX_BODY_SIZE']) elif (content_type == 'application/x-www-form-urlencoded' or content_type == 'application/x-url-encoded'): name_buffer = [] class vars(object): f = None def on_field_start(): pass def on_field_name(data, start, end): name_buffer.append(data[start:end]) def on_field_data(data, start, end): if vars.f is None: vars.f = FieldClass(b''.join(name_buffer)) del name_buffer[:] vars.f.write(data[start:end]) def on_field_end(): # Finalize and call callback. if vars.f is None: # If we get here, it's because there was no field data. # We create a field, set it to None, and then continue. vars.f = FieldClass(b''.join(name_buffer)) del name_buffer[:] vars.f.set_none() vars.f.finalize() on_field(vars.f) vars.f = None def on_end(): if self.on_end is not None: self.on_end() # Setup callbacks. callbacks = { 'on_field_start': on_field_start, 'on_field_name': on_field_name, 'on_field_data': on_field_data, 'on_field_end': on_field_end, 'on_end': on_end, } # Instantiate parser. parser = QuerystringParser( callbacks=callbacks, max_size=self.config['MAX_BODY_SIZE'] ) elif content_type == 'multipart/form-data': if boundary is None: self.logger.error("No boundary given") raise FormParserError("No boundary given") header_name = [] header_value = [] headers = {} # No 'nonlocal' on Python 2 :-( class vars(object): f = None writer = None is_file = False def on_part_begin(): pass def on_part_data(data, start, end): bytes_processed = vars.writer.write(data[start:end]) # TODO: check for error here. return bytes_processed def on_part_end(): vars.f.finalize() if vars.is_file: on_file(vars.f) else: on_field(vars.f) def on_header_field(data, start, end): header_name.append(data[start:end]) def on_header_value(data, start, end): header_value.append(data[start:end]) def on_header_end(): headers[b''.join(header_name)] = b''.join(header_value) del header_name[:] del header_value[:] def on_headers_finished(): # Reset the 'is file' flag. vars.is_file = False # Parse the content-disposition header. # TODO: handle mixed case content_disp = headers.get(b'Content-Disposition') disp, options = parse_options_header(content_disp) # Get the field and filename. field_name = options.get(b'name') file_name = options.get(b'filename') # TODO: check for errors # Create the proper class. if file_name is None: vars.f = FieldClass(field_name) else: vars.f = FileClass(file_name, field_name, config=self.config) vars.is_file = True # Parse the given Content-Transfer-Encoding to determine what # we need to do with the incoming data. # TODO: check that we properly handle 8bit / 7bit encoding. transfer_encoding = headers.get(b'Content-Transfer-Encoding', b'7bit') if (transfer_encoding == b'binary' or transfer_encoding == b'8bit' or transfer_encoding == b'7bit'): vars.writer = vars.f elif transfer_encoding == b'base64': vars.writer = Base64Decoder(vars.f) elif transfer_encoding == b'quoted-printable': vars.writer = QuotedPrintableDecoder(vars.f) else: self.logger.warning("Unknown Content-Transfer-Encoding: " "%r", transfer_encoding) if self.config['UPLOAD_ERROR_ON_BAD_CTE']: raise FormParserError( 'Unknown Content-Transfer-Encoding "{0}"'.format( transfer_encoding ) ) else: # If we aren't erroring, then we just treat this as an # unencoded Content-Transfer-Encoding. vars.writer = vars.f def on_end(): vars.writer.finalize() if self.on_end is not None: self.on_end() # These are our callbacks for the parser. callbacks = { 'on_part_begin': on_part_begin, 'on_part_data': on_part_data, 'on_part_end': on_part_end, 'on_header_field': on_header_field, 'on_header_value': on_header_value, 'on_header_end': on_header_end, 'on_headers_finished': on_headers_finished, 'on_end': on_end, } # Instantiate a multipart parser. parser = MultipartParser(boundary, callbacks, max_size=self.config['MAX_BODY_SIZE']) else: self.logger.warning("Unknown Content-Type: %r", content_type) raise FormParserError("Unknown Content-Type: {0}".format( content_type )) self.parser = parser def write(self, data): """Write some data. The parser will forward this to the appropriate underlying parser. :param data: a bytestring """ self.bytes_received += len(data) # TODO: check the parser's return value for errors? return self.parser.write(data) def finalize(self): """Finalize the parser.""" if self.parser is not None and hasattr(self.parser, 'finalize'): self.parser.finalize() def close(self): """Close the parser.""" if self.parser is not None and hasattr(self.parser, 'close'): self.parser.close() def __repr__(self): return "%s(content_type=%r, parser=%r)" % ( self.__class__.__name__, self.content_type, self.parser, ) def create_form_parser(headers, on_field, on_file, trust_x_headers=False, config={}): """This function is a helper function to aid in creating a FormParser instances. Given a dictionary-like headers object, it will determine the correct information needed, instantiate a FormParser with the appropriate values and given callbacks, and then return the corresponding parser. :param headers: A dictionary-like object of HTTP headers. The only required header is Content-Type. :param on_field: Callback to call with each parsed field. :param on_file: Callback to call with each parsed file. :param trust_x_headers: Whether or not to trust information received from certain X-Headers - for example, the file name from X-File-Name. :param config: Configuration variables to pass to the FormParser. """ content_type = headers.get('Content-Type') if content_type is None: logging.getLogger(__name__).warning("No Content-Type header given") raise ValueError("No Content-Type header given!") # Boundaries are optional (the FormParser will raise if one is needed # but not given). content_type, params = parse_options_header(content_type) boundary = params.get(b'boundary') # We need content_type to be a string, not a bytes object. content_type = content_type.decode('latin-1') # File names are optional. file_name = headers.get('X-File-Name') # Instantiate a form parser. form_parser = FormParser(content_type, on_field, on_file, boundary=boundary, file_name=file_name, config=config) # Return our parser. return form_parser def parse_form(headers, input_stream, on_field, on_file, chunk_size=1048576, **kwargs): """This function is useful if you just want to parse a request body, without too much work. Pass it a dictionary-like object of the request's headers, and a file-like object for the input stream, along with two callbacks that will get called whenever a field or file is parsed. :param headers: A dictionary-like object of HTTP headers. The only required header is Content-Type. :param input_stream: A file-like object that represents the request body. The read() method must return bytestrings. :param on_field: Callback to call with each parsed field. :param on_file: Callback to call with each parsed file. :param chunk_size: The maximum size to read from the input stream and write to the parser at one time. Defaults to 1 MiB. """ # Create our form parser. parser = create_form_parser(headers, on_field, on_file) # Read chunks of 100KiB and write to the parser, but never read more than # the given Content-Length, if any. content_length = headers.get('Content-Length') if content_length is not None: content_length = int(content_length) else: content_length = float('inf') bytes_read = 0 while True: # Read only up to the Content-Length given. max_readable = min(content_length - bytes_read, 1048576) buff = input_stream.read(max_readable) # Write to the parser and update our length. parser.write(buff) bytes_read += len(buff) # If we get a buffer that's smaller than the size requested, or if we # have read up to our content length, we're done. if len(buff) != max_readable or bytes_read == content_length: break # Tell our parser that we're done writing data. parser.finalize() python-multipart-0.0.5/multipart/tests/000077500000000000000000000000001336005506300202405ustar00rootroot00000000000000python-multipart-0.0.5/multipart/tests/__init__.py000066400000000000000000000000001336005506300223370ustar00rootroot00000000000000python-multipart-0.0.5/multipart/tests/compat.py000066400000000000000000000104051336005506300220750ustar00rootroot00000000000000try: import unittest2 as unittest except ImportError: import unittest import os import re import sys import types import functools def ensure_in_path(path): """ Ensure that a given path is in the sys.path array """ if not os.path.isdir(path): raise RuntimeError('Tried to add nonexisting path') def _samefile(x, y): try: return os.path.samefile(x, y) except (IOError, OSError): return False except AttributeError: # Probably on Windows. path1 = os.path.abspath(x).lower() path2 = os.path.abspath(y).lower() return path1 == path2 # Remove existing copies of it. for pth in sys.path: if _samefile(pth, path): sys.path.remove(pth) # Add it at the beginning. sys.path.insert(0, path) # Check if pytest is imported. If so, we use it to create marking decorators. # If not, we just create a function that does nothing. try: import pytest except ImportError: pytest = None if pytest is not None: slow_test = pytest.mark.slow_test xfail = pytest.mark.xfail else: slow_test = lambda x: x def xfail(*args, **kwargs): if len(args) > 0 and isinstance(args[0], types.FunctionType): return args[0] return lambda x: x # We don't use the py.test parametrizing function, since it seems to break # with unittest.TestCase subclasses. def parametrize(field_names, field_values): # If we're not given a list of field names, we make it. if not isinstance(field_names, (tuple, list)): field_names = (field_names,) field_values = [(val,) for val in field_values] # Create a decorator that saves this list of field names and values on the # function for later parametrizing. def decorator(func): func.__dict__['param_names'] = field_names func.__dict__['param_values'] = field_values return func return decorator # This is a metaclass that actually performs the parametrization. class ParametrizingMetaclass(type): IDENTIFIER_RE = re.compile('[^A-Za-z0-9]') def __new__(klass, name, bases, attrs): new_attrs = attrs.copy() for attr_name, attr in attrs.items(): # We only care about functions if not isinstance(attr, types.FunctionType): continue param_names = attr.__dict__.pop('param_names', None) param_values = attr.__dict__.pop('param_values', None) if param_names is None or param_values is None: continue # Create multiple copies of the function. for i, values in enumerate(param_values): assert len(param_names) == len(values) # Get a repr of the values, and fix it to be a valid identifier human = '_'.join( [klass.IDENTIFIER_RE.sub('', repr(x)) for x in values] ) # Create a new name. # new_name = attr.__name__ + "_%d" % i new_name = attr.__name__ + "__" + human # Create a replacement function. def create_new_func(func, names, values): # Create a kwargs dictionary. kwargs = dict(zip(names, values)) @functools.wraps(func) def new_func(self): return func(self, **kwargs) # Manually set the name and return the new function. new_func.__name__ = new_name return new_func # Actually create the new function. new_func = create_new_func(attr, param_names, values) # Save this new function in our attrs dict. new_attrs[new_name] = new_func # Remove the old attribute from our new dictionary. del new_attrs[attr_name] # We create the class as normal, except we use our new attributes. return type.__new__(klass, name, bases, new_attrs) # This is a class decorator that actually applies the above metaclass. def parametrize_class(klass): return ParametrizingMetaclass(klass.__name__, klass.__bases__, klass.__dict__) python-multipart-0.0.5/multipart/tests/test_data/000077500000000000000000000000001336005506300222105ustar00rootroot00000000000000python-multipart-0.0.5/multipart/tests/test_data/http/000077500000000000000000000000001336005506300231675ustar00rootroot00000000000000python-multipart-0.0.5/multipart/tests/test_data/http/CR_in_header.http000066400000000000000000000002251336005506300263710ustar00rootroot00000000000000------WebKitFormBoundaryTkr3kCBQlBe1nrhc Content- isposition: form-data; name="field" This is a test. ------WebKitFormBoundaryTkr3kCBQlBe1nrhc--python-multipart-0.0.5/multipart/tests/test_data/http/CR_in_header.yaml000066400000000000000000000001111336005506300263460ustar00rootroot00000000000000boundary: ----WebKitFormBoundaryTkr3kCBQlBe1nrhc expected: error: 51 python-multipart-0.0.5/multipart/tests/test_data/http/CR_in_header_value.http000066400000000000000000000002251336005506300275650ustar00rootroot00000000000000------WebKitFormBoundaryTkr3kCBQlBe1nrhc Content-Disposition: form-data; n me="field" This is a test. ------WebKitFormBoundaryTkr3kCBQlBe1nrhc--python-multipart-0.0.5/multipart/tests/test_data/http/CR_in_header_value.yaml000066400000000000000000000001111336005506300275420ustar00rootroot00000000000000boundary: ----WebKitFormBoundaryTkr3kCBQlBe1nrhc expected: error: 76 python-multipart-0.0.5/multipart/tests/test_data/http/almost_match_boundary.http000066400000000000000000000004101336005506300304410ustar00rootroot00000000000000----boundary Content-Disposition: form-data; name="file"; filename="test.txt" Content-Type: text/plain --boundari --boundaryq--boundary q--boundarq --bounaryd-- --notbound-- --mismatch --mismatch-- --boundary-Q --boundary Q--boundaryQ ----boundary-- python-multipart-0.0.5/multipart/tests/test_data/http/almost_match_boundary.yaml000066400000000000000000000004541336005506300304340ustar00rootroot00000000000000boundary: --boundary expected: - name: file type: file file_name: test.txt data: !!binary | LS1ib3VuZGFyaQ0KLS1ib3VuZGFyeXEtLWJvdW5kYXJ5DXEtLWJvdW5kYXJxDQotLWJvdW5hcnlkLS0NCi0tbm90Ym91bmQtLQ0KLS1taXNtYXRjaA0KLS1taXNtYXRjaC0tDQotLWJvdW5kYXJ5LVENCi0tYm91bmRhcnkNUS0tYm91bmRhcnlR python-multipart-0.0.5/multipart/tests/test_data/http/almost_match_boundary_without_CR.http000066400000000000000000000002041336005506300326110ustar00rootroot00000000000000----boundary Content-Disposition: form-data; name="field" QQQQQQQQQQQQQQQQQQQQ ----boundaryQQQQQQQQQQQQQQQQQQQQ ----boundary--python-multipart-0.0.5/multipart/tests/test_data/http/almost_match_boundary_without_CR.yaml000066400000000000000000000002471336005506300326030ustar00rootroot00000000000000boundary: --boundary expected: - name: field type: field data: !!binary | UVFRUVFRUVFRUVFRUVFRUVFRUVENCi0tLS1ib3VuZGFyeVFRUVFRUVFRUVFRUVFRUVFRUVFR python-multipart-0.0.5/multipart/tests/test_data/http/almost_match_boundary_without_LF.http000066400000000000000000000002051336005506300326070ustar00rootroot00000000000000----boundary Content-Disposition: form-data; name="field" QQQQQQQQQQQQQQQQQQQQ ----boundary QQQQQQQQQQQQQQQQQQQQ ----boundary--python-multipart-0.0.5/multipart/tests/test_data/http/almost_match_boundary_without_LF.yaml000066400000000000000000000002531336005506300325750ustar00rootroot00000000000000boundary: --boundary expected: - name: field type: field data: !!binary | UVFRUVFRUVFRUVFRUVFRUVFRUVENCi0tLS1ib3VuZGFyeQ1RUVFRUVFRUVFRUVFRUVFRUVFRUQ== almost_match_boundary_without_final_hyphen.http000066400000000000000000000002051336005506300346730ustar00rootroot00000000000000python-multipart-0.0.5/multipart/tests/test_data/http----boundary Content-Disposition: form-data; name="field" QQQQQQQQQQQQQQQQQQQQ ----boundary-QQQQQQQQQQQQQQQQQQQQ ----boundary--almost_match_boundary_without_final_hyphen.yaml000066400000000000000000000002531336005506300346610ustar00rootroot00000000000000python-multipart-0.0.5/multipart/tests/test_data/httpboundary: --boundary expected: - name: field type: field data: !!binary | UVFRUVFRUVFRUVFRUVFRUVFRUVENCi0tLS1ib3VuZGFyeS1RUVFRUVFRUVFRUVFRUVFRUVFRUQ== python-multipart-0.0.5/multipart/tests/test_data/http/bad_end_of_headers.http000066400000000000000000000002251336005506300276220ustar00rootroot00000000000000------WebKitFormBoundaryTkr3kCBQlBe1nrhc Content-Disposition: form-data; name="field" QThis is a test. ------WebKitFormBoundaryTkr3kCBQlBe1nrhc--python-multipart-0.0.5/multipart/tests/test_data/http/bad_end_of_headers.yaml000066400000000000000000000001111336005506300275770ustar00rootroot00000000000000boundary: ----WebKitFormBoundaryTkr3kCBQlBe1nrhc expected: error: 89 python-multipart-0.0.5/multipart/tests/test_data/http/bad_header_char.http000066400000000000000000000002251336005506300271220ustar00rootroot00000000000000------WebKitFormBoundaryTkr3kCBQlBe1nrhc Content-999position: form-data; name="field" This is a test. ------WebKitFormBoundaryTkr3kCBQlBe1nrhc--python-multipart-0.0.5/multipart/tests/test_data/http/bad_header_char.yaml000066400000000000000000000001111336005506300270770ustar00rootroot00000000000000boundary: ----WebKitFormBoundaryTkr3kCBQlBe1nrhc expected: error: 50 python-multipart-0.0.5/multipart/tests/test_data/http/bad_initial_boundary.http000066400000000000000000000002251336005506300302310ustar00rootroot00000000000000------WebQitFormBoundaryTkr3kCBQlBe1nrhc Content-Disposition: form-data; name="field" This is a test. ------WebKitFormBoundaryTkr3kCBQlBe1nrhc--python-multipart-0.0.5/multipart/tests/test_data/http/bad_initial_boundary.yaml000066400000000000000000000001101336005506300302050ustar00rootroot00000000000000boundary: ----WebKitFormBoundaryTkr3kCBQlBe1nrhc expected: error: 9 python-multipart-0.0.5/multipart/tests/test_data/http/base64_encoding.http000066400000000000000000000002551336005506300270240ustar00rootroot00000000000000----boundary Content-Disposition: form-data; name="file"; filename="test.txt" Content-Type: text/plain Content-Transfer-Encoding: base64 VGVzdCAxMjM= ----boundary-- python-multipart-0.0.5/multipart/tests/test_data/http/base64_encoding.yaml000066400000000000000000000001751336005506300270100ustar00rootroot00000000000000boundary: --boundary expected: - name: file type: file file_name: test.txt data: !!binary | VGVzdCAxMjM= python-multipart-0.0.5/multipart/tests/test_data/http/empty_header.http000066400000000000000000000002021336005506300265300ustar00rootroot00000000000000------WebKitFormBoundaryTkr3kCBQlBe1nrhc : form-data; name="field" This is a test. ------WebKitFormBoundaryTkr3kCBQlBe1nrhc--python-multipart-0.0.5/multipart/tests/test_data/http/empty_header.yaml000066400000000000000000000001111336005506300265120ustar00rootroot00000000000000boundary: ----WebKitFormBoundaryTkr3kCBQlBe1nrhc expected: error: 42 python-multipart-0.0.5/multipart/tests/test_data/http/multiple_fields.http000066400000000000000000000003621336005506300272520ustar00rootroot00000000000000------WebKitFormBoundaryTkr3kCBQlBe1nrhc Content-Disposition: form-data; name="field1" field1 ------WebKitFormBoundaryTkr3kCBQlBe1nrhc Content-Disposition: form-data; name="field2" field2 ------WebKitFormBoundaryTkr3kCBQlBe1nrhc-- python-multipart-0.0.5/multipart/tests/test_data/http/multiple_fields.yaml000066400000000000000000000003051336005506300272320ustar00rootroot00000000000000boundary: ----WebKitFormBoundaryTkr3kCBQlBe1nrhc expected: - name: field1 type: field data: !!binary | ZmllbGQx - name: field2 type: field data: !!binary | ZmllbGQy python-multipart-0.0.5/multipart/tests/test_data/http/multiple_files.http000066400000000000000000000005341336005506300271070ustar00rootroot00000000000000------WebKitFormBoundarygbACTUR58IyeurVf Content-Disposition: form-data; name="file1"; filename="test1.txt" Content-Type: text/plain Test file #1 ------WebKitFormBoundarygbACTUR58IyeurVf Content-Disposition: form-data; name="file2"; filename="test2.txt" Content-Type: text/plain Test file #2 ------WebKitFormBoundarygbACTUR58IyeurVf-- python-multipart-0.0.5/multipart/tests/test_data/http/multiple_files.yaml000066400000000000000000000004041336005506300270660ustar00rootroot00000000000000boundary: ----WebKitFormBoundarygbACTUR58IyeurVf expected: - name: file1 type: file file_name: test1.txt data: !!binary | VGVzdCBmaWxlICMx - name: file2 type: file file_name: test2.txt data: !!binary | VGVzdCBmaWxlICMy python-multipart-0.0.5/multipart/tests/test_data/http/quoted_printable_encoding.http000066400000000000000000000002641336005506300313010ustar00rootroot00000000000000----boundary Content-Disposition: form-data; name="file"; filename="test.txt" Content-Type: text/plain Content-Transfer-Encoding: quoted-printable foo=3Dbar ----boundary-- python-multipart-0.0.5/multipart/tests/test_data/http/quoted_printable_encoding.yaml000066400000000000000000000001771336005506300312670ustar00rootroot00000000000000boundary: --boundary expected: - name: file type: file file_name: test.txt data: !!binary | Zm9vPWJhcg== python-multipart-0.0.5/multipart/tests/test_data/http/single_field.http000066400000000000000000000002251336005506300265130ustar00rootroot00000000000000------WebKitFormBoundaryTkr3kCBQlBe1nrhc Content-Disposition: form-data; name="field" This is a test. ------WebKitFormBoundaryTkr3kCBQlBe1nrhc--python-multipart-0.0.5/multipart/tests/test_data/http/single_field.yaml000066400000000000000000000002131336005506300264730ustar00rootroot00000000000000boundary: ----WebKitFormBoundaryTkr3kCBQlBe1nrhc expected: - name: field type: field data: !!binary | VGhpcyBpcyBhIHRlc3Qu python-multipart-0.0.5/multipart/tests/test_data/http/single_field_blocks.http000066400000000000000000000001631336005506300300510ustar00rootroot00000000000000--boundary Content-Disposition: form-data; name="field" 0123456789ABCDEFGHIJ0123456789ABCDEFGHIJ --boundary-- python-multipart-0.0.5/multipart/tests/test_data/http/single_field_blocks.yaml000066400000000000000000000002231336005506300300310ustar00rootroot00000000000000boundary: --boundary expected: - name: field type: field data: !!binary | MDEyMzQ1Njc4OUFCQ0RFRkdISUowMTIzNDU2Nzg5QUJDREVGR0hJSg== python-multipart-0.0.5/multipart/tests/test_data/http/single_field_longer.http000066400000000000000000000004061336005506300300620ustar00rootroot00000000000000------WebKitFormBoundaryTkr3kCBQlBe1nrhc Content-Disposition: form-data; name="field" qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq ------WebKitFormBoundaryTkr3kCBQlBe1nrhc--python-multipart-0.0.5/multipart/tests/test_data/http/single_field_longer.yaml000066400000000000000000000004451336005506300300500ustar00rootroot00000000000000boundary: ----WebKitFormBoundaryTkr3kCBQlBe1nrhc expected: - name: field type: field data: !!binary | cXFxcXFxcXFxcXFxcXFxcXFxcXFxcXFxcXFxcXFxcXFxcXFxcXFxcXFxcXFxcXFxcXFxcXFxcXFxcXFxcXFxcXFxcXFxcXFxcXFxcXFxcXFxcXFxcXFxcXFxcXFxcXFxcXFxcXFxcXFxcXFxcXFxcXFxcXFxcXFxcXFxcXFxcXE= python-multipart-0.0.5/multipart/tests/test_data/http/single_field_single_file.http000066400000000000000000000003001336005506300310450ustar00rootroot00000000000000--boundary Content-Disposition: form-data; name="field" test1 --boundary Content-Disposition: form-data; name="file"; filename="file.txt" Content-Type: text/plain test2 --boundary--python-multipart-0.0.5/multipart/tests/test_data/http/single_field_single_file.yaml000066400000000000000000000002751336005506300310430ustar00rootroot00000000000000boundary: boundary expected: - name: field type: field data: !!binary | dGVzdDE= - name: file type: file file_name: file.txt data: !!binary | dGVzdDI= python-multipart-0.0.5/multipart/tests/test_data/http/single_field_with_leading_newlines.http000066400000000000000000000002311336005506300331320ustar00rootroot00000000000000 ------WebKitFormBoundaryTkr3kCBQlBe1nrhc Content-Disposition: form-data; name="field" This is a test. ------WebKitFormBoundaryTkr3kCBQlBe1nrhc--python-multipart-0.0.5/multipart/tests/test_data/http/single_field_with_leading_newlines.yaml000066400000000000000000000002131336005506300331150ustar00rootroot00000000000000boundary: ----WebKitFormBoundaryTkr3kCBQlBe1nrhc expected: - name: field type: field data: !!binary | VGhpcyBpcyBhIHRlc3Qu python-multipart-0.0.5/multipart/tests/test_data/http/single_file.http000066400000000000000000000003121336005506300263440ustar00rootroot00000000000000------WebKitFormBoundary5BZGOJCWtXGYC9HW Content-Disposition: form-data; name="file"; filename="test.txt" Content-Type: text/plain This is a test file. ------WebKitFormBoundary5BZGOJCWtXGYC9HW-- python-multipart-0.0.5/multipart/tests/test_data/http/single_file.yaml000066400000000000000000000002521336005506300263320ustar00rootroot00000000000000boundary: ----WebKitFormBoundary5BZGOJCWtXGYC9HW expected: - name: file type: file file_name: test.txt data: !!binary | VGhpcyBpcyBhIHRlc3QgZmlsZS4= python-multipart-0.0.5/multipart/tests/test_data/http/utf8_filename.http000066400000000000000000000003201336005506300266110ustar00rootroot00000000000000------WebKitFormBoundaryI9SCEFp2lpx5DR2K Content-Disposition: form-data; name="file"; filename="???.txt" Content-Type: text/plain これはテストです。 ------WebKitFormBoundaryI9SCEFp2lpx5DR2K-- python-multipart-0.0.5/multipart/tests/test_data/http/utf8_filename.yaml000066400000000000000000000002611336005506300266000ustar00rootroot00000000000000boundary: ----WebKitFormBoundaryI9SCEFp2lpx5DR2K expected: - name: file type: file file_name: ???.txt data: !!binary | 44GT44KM44Gv44OG44K544OI44Gn44GZ44CC python-multipart-0.0.5/multipart/tests/test_multipart.py000066400000000000000000001134231336005506300236760ustar00rootroot00000000000000# -*- coding: utf-8 -*- import os import sys import glob import yaml import base64 import random import tempfile from .compat import ( parametrize, parametrize_class, slow_test, unittest, ) from io import BytesIO from six import binary_type, text_type from mock import MagicMock, Mock, patch from ..multipart import * # Get the current directory for our later test cases. curr_dir = os.path.abspath(os.path.dirname(__file__)) def force_bytes(val): if isinstance(val, text_type): val = val.encode(sys.getfilesystemencoding()) return val class TestField(unittest.TestCase): def setUp(self): self.f = Field('foo') def test_name(self): self.assertEqual(self.f.field_name, 'foo') def test_data(self): self.f.write(b'test123') self.assertEqual(self.f.value, b'test123') def test_cache_expiration(self): self.f.write(b'test') self.assertEqual(self.f.value, b'test') self.f.write(b'123') self.assertEqual(self.f.value, b'test123') def test_finalize(self): self.f.write(b'test123') self.f.finalize() self.assertEqual(self.f.value, b'test123') def test_close(self): self.f.write(b'test123') self.f.close() self.assertEqual(self.f.value, b'test123') def test_from_value(self): f = Field.from_value(b'name', b'value') self.assertEqual(f.field_name, b'name') self.assertEqual(f.value, b'value') f2 = Field.from_value(b'name', None) self.assertEqual(f2.value, None) def test_equality(self): f1 = Field.from_value(b'name', b'value') f2 = Field.from_value(b'name', b'value') self.assertEqual(f1, f2) def test_equality_with_other(self): f = Field.from_value(b'foo', b'bar') self.assertFalse(f == b'foo') self.assertFalse(b'foo' == f) def test_set_none(self): f = Field(b'foo') self.assertEqual(f.value, b'') f.set_none() self.assertEqual(f.value, None) class TestFile(unittest.TestCase): def setUp(self): self.c = {} self.d = force_bytes(tempfile.mkdtemp()) self.f = File(b'foo.txt', config=self.c) def assert_data(self, data): f = self.f.file_object f.seek(0) self.assertEqual(f.read(), data) f.seek(0) f.truncate() def assert_exists(self): full_path = os.path.join(self.d, self.f.actual_file_name) self.assertTrue(os.path.exists(full_path)) def test_simple(self): self.f.write(b'foobar') self.assert_data(b'foobar') def test_invalid_write(self): m = Mock() m.write.return_value = 5 self.f._fileobj = m v = self.f.write(b'foobar') self.assertEqual(v, 5) def test_file_fallback(self): self.c['MAX_MEMORY_FILE_SIZE'] = 1 self.f.write(b'1') self.assertTrue(self.f.in_memory) self.assert_data(b'1') self.f.write(b'123') self.assertFalse(self.f.in_memory) self.assert_data(b'123') # Test flushing too. old_obj = self.f.file_object self.f.flush_to_disk() self.assertFalse(self.f.in_memory) self.assertIs(self.f.file_object, old_obj) def test_file_fallback_with_data(self): self.c['MAX_MEMORY_FILE_SIZE'] = 10 self.f.write(b'1' * 10) self.assertTrue(self.f.in_memory) self.f.write(b'2' * 10) self.assertFalse(self.f.in_memory) self.assert_data(b'11111111112222222222') def test_file_name(self): # Write to this dir. self.c['UPLOAD_DIR'] = self.d self.c['MAX_MEMORY_FILE_SIZE'] = 10 # Write. self.f.write(b'12345678901') self.assertFalse(self.f.in_memory) # Assert that the file exists self.assertIsNotNone(self.f.actual_file_name) self.assert_exists() def test_file_full_name(self): # Write to this dir. self.c['UPLOAD_DIR'] = self.d self.c['UPLOAD_KEEP_FILENAME'] = True self.c['MAX_MEMORY_FILE_SIZE'] = 10 # Write. self.f.write(b'12345678901') self.assertFalse(self.f.in_memory) # Assert that the file exists self.assertEqual(self.f.actual_file_name, b'foo') self.assert_exists() def test_file_full_name_with_ext(self): self.c['UPLOAD_DIR'] = self.d self.c['UPLOAD_KEEP_FILENAME'] = True self.c['UPLOAD_KEEP_EXTENSIONS'] = True self.c['MAX_MEMORY_FILE_SIZE'] = 10 # Write. self.f.write(b'12345678901') self.assertFalse(self.f.in_memory) # Assert that the file exists self.assertEqual(self.f.actual_file_name, b'foo.txt') self.assert_exists() def test_file_full_name_with_ext(self): self.c['UPLOAD_DIR'] = self.d self.c['UPLOAD_KEEP_FILENAME'] = True self.c['UPLOAD_KEEP_EXTENSIONS'] = True self.c['MAX_MEMORY_FILE_SIZE'] = 10 # Write. self.f.write(b'12345678901') self.assertFalse(self.f.in_memory) # Assert that the file exists self.assertEqual(self.f.actual_file_name, b'foo.txt') self.assert_exists() def test_no_dir_with_extension(self): self.c['UPLOAD_KEEP_EXTENSIONS'] = True self.c['MAX_MEMORY_FILE_SIZE'] = 10 # Write. self.f.write(b'12345678901') self.assertFalse(self.f.in_memory) # Assert that the file exists ext = os.path.splitext(self.f.actual_file_name)[1] self.assertEqual(ext, b'.txt') self.assert_exists() def test_invalid_dir_with_name(self): # Write to this dir. self.c['UPLOAD_DIR'] = force_bytes(os.path.join('/', 'tmp', 'notexisting')) self.c['UPLOAD_KEEP_FILENAME'] = True self.c['MAX_MEMORY_FILE_SIZE'] = 5 # Write. with self.assertRaises(FileError): self.f.write(b'1234567890') def test_invalid_dir_no_name(self): # Write to this dir. self.c['UPLOAD_DIR'] = force_bytes(os.path.join('/', 'tmp', 'notexisting')) self.c['UPLOAD_KEEP_FILENAME'] = False self.c['MAX_MEMORY_FILE_SIZE'] = 5 # Write. with self.assertRaises(FileError): self.f.write(b'1234567890') # TODO: test uploading two files with the same name. class TestParseOptionsHeader(unittest.TestCase): def test_simple(self): t, p = parse_options_header('application/json') self.assertEqual(t, b'application/json') self.assertEqual(p, {}) def test_blank(self): t, p = parse_options_header('') self.assertEqual(t, b'') self.assertEqual(p, {}) def test_single_param(self): t, p = parse_options_header('application/json;par=val') self.assertEqual(t, b'application/json') self.assertEqual(p, {b'par': b'val'}) def test_single_param_with_spaces(self): t, p = parse_options_header(b'application/json; par=val') self.assertEqual(t, b'application/json') self.assertEqual(p, {b'par': b'val'}) def test_multiple_params(self): t, p = parse_options_header(b'application/json;par=val;asdf=foo') self.assertEqual(t, b'application/json') self.assertEqual(p, {b'par': b'val', b'asdf': b'foo'}) def test_quoted_param(self): t, p = parse_options_header(b'application/json;param="quoted"') self.assertEqual(t, b'application/json') self.assertEqual(p, {b'param': b'quoted'}) def test_quoted_param_with_semicolon(self): t, p = parse_options_header(b'application/json;param="quoted;with;semicolons"') self.assertEqual(p[b'param'], b'quoted;with;semicolons') def test_quoted_param_with_escapes(self): t, p = parse_options_header(b'application/json;param="This \\" is \\" a \\" quote"') self.assertEqual(p[b'param'], b'This " is " a " quote') def test_handles_ie6_bug(self): t, p = parse_options_header(b'text/plain; filename="C:\\this\\is\\a\\path\\file.txt"') self.assertEqual(p[b'filename'], b'file.txt') class TestBaseParser(unittest.TestCase): def setUp(self): self.b = BaseParser() self.b.callbacks = {} def test_callbacks(self): # The stupid list-ness is to get around lack of nonlocal on py2 l = [0] def on_foo(): l[0] += 1 self.b.set_callback('foo', on_foo) self.b.callback('foo') self.assertEqual(l[0], 1) self.b.set_callback('foo', None) self.b.callback('foo') self.assertEqual(l[0], 1) class TestQuerystringParser(unittest.TestCase): def assert_fields(self, *args, **kwargs): if kwargs.pop('finalize', True): self.p.finalize() self.assertEqual(self.f, list(args)) if kwargs.get('reset', True): self.f = [] def setUp(self): self.reset() def reset(self): self.f = [] name_buffer = [] data_buffer = [] def on_field_name(data, start, end): name_buffer.append(data[start:end]) def on_field_data(data, start, end): data_buffer.append(data[start:end]) def on_field_end(): self.f.append(( b''.join(name_buffer), b''.join(data_buffer) )) del name_buffer[:] del data_buffer[:] callbacks = { 'on_field_name': on_field_name, 'on_field_data': on_field_data, 'on_field_end': on_field_end } self.p = QuerystringParser(callbacks) def test_simple_querystring(self): self.p.write(b'foo=bar') self.assert_fields((b'foo', b'bar')) def test_querystring_blank_beginning(self): self.p.write(b'&foo=bar') self.assert_fields((b'foo', b'bar')) def test_querystring_blank_end(self): self.p.write(b'foo=bar&') self.assert_fields((b'foo', b'bar')) def test_multiple_querystring(self): self.p.write(b'foo=bar&asdf=baz') self.assert_fields( (b'foo', b'bar'), (b'asdf', b'baz') ) def test_streaming_simple(self): self.p.write(b'foo=bar&') self.assert_fields( (b'foo', b'bar'), finalize=False ) self.p.write(b'asdf=baz') self.assert_fields( (b'asdf', b'baz') ) def test_streaming_break(self): self.p.write(b'foo=one') self.assert_fields(finalize=False) self.p.write(b'two') self.assert_fields(finalize=False) self.p.write(b'three') self.assert_fields(finalize=False) self.p.write(b'&asd') self.assert_fields( (b'foo', b'onetwothree'), finalize=False ) self.p.write(b'f=baz') self.assert_fields( (b'asdf', b'baz') ) def test_semicolon_seperator(self): self.p.write(b'foo=bar;asdf=baz') self.assert_fields( (b'foo', b'bar'), (b'asdf', b'baz') ) def test_too_large_field(self): self.p.max_size = 15 # Note: len = 8 self.p.write(b"foo=bar&") self.assert_fields((b'foo', b'bar'), finalize=False) # Note: len = 8, only 7 bytes processed self.p.write(b'a=123456') self.assert_fields((b'a', b'12345')) def test_invalid_max_size(self): with self.assertRaises(ValueError): p = QuerystringParser(max_size=-100) def test_strict_parsing_pass(self): data = b'foo=bar&another=asdf' for first, last in split_all(data): self.reset() self.p.strict_parsing = True print("%r / %r" % (first, last)) self.p.write(first) self.p.write(last) self.assert_fields((b'foo', b'bar'), (b'another', b'asdf')) def test_strict_parsing_fail_double_sep(self): data = b'foo=bar&&another=asdf' for first, last in split_all(data): self.reset() self.p.strict_parsing = True cnt = 0 with self.assertRaises(QuerystringParseError) as cm: cnt += self.p.write(first) cnt += self.p.write(last) self.p.finalize() # The offset should occur at 8 bytes into the data (as a whole), # so we calculate the offset into the chunk. if cm is not None: self.assertEqual(cm.exception.offset, 8 - cnt) def test_double_sep(self): data = b'foo=bar&&another=asdf' for first, last in split_all(data): print(" %r / %r " % (first, last)) self.reset() cnt = 0 cnt += self.p.write(first) cnt += self.p.write(last) self.assert_fields((b'foo', b'bar'), (b'another', b'asdf')) def test_strict_parsing_fail_no_value(self): self.p.strict_parsing = True with self.assertRaises(QuerystringParseError) as cm: self.p.write(b'foo=bar&blank&another=asdf') if cm is not None: self.assertEqual(cm.exception.offset, 8) def test_success_no_value(self): self.p.write(b'foo=bar&blank&another=asdf') self.assert_fields( (b'foo', b'bar'), (b'blank', b''), (b'another', b'asdf') ) class TestOctetStreamParser(unittest.TestCase): def setUp(self): self.d = [] self.started = 0 self.finished = 0 def on_start(): self.started += 1 def on_data(data, start, end): self.d.append(data[start:end]) def on_end(): self.finished += 1 callbacks = { 'on_start': on_start, 'on_data': on_data, 'on_end': on_end } self.p = OctetStreamParser(callbacks) def assert_data(self, data, finalize=True): self.assertEqual(b''.join(self.d), data) self.d = [] def assert_started(self, val=True): if val: self.assertEqual(self.started, 1) else: self.assertEqual(self.started, 0) def assert_finished(self, val=True): if val: self.assertEqual(self.finished, 1) else: self.assertEqual(self.finished, 0) def test_simple(self): # Assert is not started self.assert_started(False) # Write something, it should then be started + have data self.p.write(b'foobar') self.assert_started() self.assert_data(b'foobar') # Finalize, and check self.assert_finished(False) self.p.finalize() self.assert_finished() def test_multiple_chunks(self): self.p.write(b'foo') self.p.write(b'bar') self.p.write(b'baz') self.p.finalize() self.assert_data(b'foobarbaz') self.assert_finished() def test_max_size(self): self.p.max_size = 5 self.p.write(b'0123456789') self.p.finalize() self.assert_data(b'01234') self.assert_finished() def test_invalid_max_size(self): with self.assertRaises(ValueError): q = OctetStreamParser(max_size='foo') class TestBase64Decoder(unittest.TestCase): # Note: base64('foobar') == 'Zm9vYmFy' def setUp(self): self.f = BytesIO() self.d = Base64Decoder(self.f) def assert_data(self, data, finalize=True): if finalize: self.d.finalize() self.f.seek(0) self.assertEqual(self.f.read(), data) self.f.seek(0) self.f.truncate() def test_simple(self): self.d.write(b'Zm9vYmFy') self.assert_data(b'foobar') def test_bad(self): with self.assertRaises(DecodeError): self.d.write(b'Zm9v!mFy') def test_split_properly(self): self.d.write(b'Zm9v') self.d.write(b'YmFy') self.assert_data(b'foobar') def test_bad_split(self): buff = b'Zm9v' for i in range(1, 4): first, second = buff[:i], buff[i:] self.setUp() self.d.write(first) self.d.write(second) self.assert_data(b'foo') def test_long_bad_split(self): buff = b'Zm9vYmFy' for i in range(5, 8): first, second = buff[:i], buff[i:] self.setUp() self.d.write(first) self.d.write(second) self.assert_data(b'foobar') def test_close_and_finalize(self): parser = Mock() f = Base64Decoder(parser) f.finalize() parser.finalize.assert_called_once_with() f.close() parser.close.assert_called_once_with() def test_bad_length(self): self.d.write(b'Zm9vYmF') # missing ending 'y' with self.assertRaises(DecodeError): self.d.finalize() class TestQuotedPrintableDecoder(unittest.TestCase): def setUp(self): self.f = BytesIO() self.d = QuotedPrintableDecoder(self.f) def assert_data(self, data, finalize=True): if finalize: self.d.finalize() self.f.seek(0) self.assertEqual(self.f.read(), data) self.f.seek(0) self.f.truncate() def test_simple(self): self.d.write(b'foobar') self.assert_data(b'foobar') def test_with_escape(self): self.d.write(b'foo=3Dbar') self.assert_data(b'foo=bar') def test_with_newline_escape(self): self.d.write(b'foo=\r\nbar') self.assert_data(b'foobar') def test_with_only_newline_escape(self): self.d.write(b'foo=\nbar') self.assert_data(b'foobar') def test_with_split_escape(self): self.d.write(b'foo=3') self.d.write(b'Dbar') self.assert_data(b'foo=bar') def test_with_split_newline_escape_1(self): self.d.write(b'foo=\r') self.d.write(b'\nbar') self.assert_data(b'foobar') def test_with_split_newline_escape_2(self): self.d.write(b'foo=') self.d.write(b'\r\nbar') self.assert_data(b'foobar') def test_close_and_finalize(self): parser = Mock() f = QuotedPrintableDecoder(parser) f.finalize() parser.finalize.assert_called_once_with() f.close() parser.close.assert_called_once_with() def test_not_aligned(self): """ https://github.com/andrew-d/python-multipart/issues/6 """ self.d.write(b'=3AX') self.assert_data(b':X') # Additional offset tests self.d.write(b'=3') self.d.write(b'AX') self.assert_data(b':X') self.d.write(b'q=3AX') self.assert_data(b'q:X') # Load our list of HTTP test cases. http_tests_dir = os.path.join(curr_dir, 'test_data', 'http') # Read in all test cases and load them. NON_PARAMETRIZED_TESTS = set(['single_field_blocks']) http_tests = [] for f in os.listdir(http_tests_dir): # Only load the HTTP test cases. fname, ext = os.path.splitext(f) if fname in NON_PARAMETRIZED_TESTS: continue if ext == '.http': # Get the YAML file and load it too. yaml_file = os.path.join(http_tests_dir, fname + '.yaml') # Load both. with open(os.path.join(http_tests_dir, f), 'rb') as f: test_data = f.read() with open(yaml_file, 'rb') as f: yaml_data = yaml.load(f) http_tests.append({ 'name': fname, 'test': test_data, 'result': yaml_data }) def split_all(val): """ This function will split an array all possible ways. For example: split_all([1,2,3,4]) will give: ([1], [2,3,4]), ([1,2], [3,4]), ([1,2,3], [4]) """ for i in range(1, len(val) - 1): yield (val[:i], val[i:]) @parametrize_class class TestFormParser(unittest.TestCase): def make(self, boundary, config={}): self.ended = False self.files = [] self.fields = [] def on_field(f): self.fields.append(f) def on_file(f): self.files.append(f) def on_end(): self.ended = True # Get a form-parser instance. self.f = FormParser('multipart/form-data', on_field, on_file, on_end, boundary=boundary, config=config) def assert_file_data(self, f, data): o = f.file_object o.seek(0) file_data = o.read() self.assertEqual(file_data, data) def assert_file(self, field_name, file_name, data): # Find this file. found = None for f in self.files: if f.field_name == field_name: found = f break # Assert that we found it. self.assertIsNotNone(found) try: # Assert about this file. self.assert_file_data(found, data) self.assertEqual(found.file_name, file_name) # Remove it from our list. self.files.remove(found) finally: # Close our file found.close() def assert_field(self, name, value): # Find this field in our fields list. found = None for f in self.fields: if f.field_name == name: found = f break # Assert that it exists and matches. self.assertIsNotNone(found) self.assertEqual(value, found.value) # Remove it for future iterations. self.fields.remove(found) @parametrize('param', http_tests) def test_http(self, param): # Firstly, create our parser with the given boundary. boundary = param['result']['boundary'] if isinstance(boundary, text_type): boundary = boundary.encode('latin-1') self.make(boundary) # Now, we feed the parser with data. exc = None try: processed = self.f.write(param['test']) self.f.finalize() except MultipartParseError as e: processed = 0 exc = e # print(repr(param)) # print("") # print(repr(self.fields)) # print(repr(self.files)) # Do we expect an error? if 'error' in param['result']['expected']: self.assertIsNotNone(exc) self.assertEqual(param['result']['expected']['error'], exc.offset) return # No error! self.assertEqual(processed, len(param['test'])) # Assert that the parser gave us the appropriate fields/files. for e in param['result']['expected']: # Get our type and name. type = e['type'] name = e['name'].encode('latin-1') if type == 'field': self.assert_field(name, e['data']) elif type == 'file': self.assert_file( name, e['file_name'].encode('latin-1'), e['data'] ) else: assert False def test_random_splitting(self): """ This test runs a simple multipart body with one field and one file through every possible split. """ # Load test data. test_file = 'single_field_single_file.http' with open(os.path.join(http_tests_dir, test_file), 'rb') as f: test_data = f.read() # We split the file through all cases. for first, last in split_all(test_data): # Create form parser. self.make('boundary') # Feed with data in 2 chunks. i = 0 i += self.f.write(first) i += self.f.write(last) self.f.finalize() # Assert we processed everything. self.assertEqual(i, len(test_data)) # Assert that our file and field are here. self.assert_field(b'field', b'test1') self.assert_file(b'file', b'file.txt', b'test2') def test_feed_single_bytes(self): """ This test parses a simple multipart body 1 byte at a time. """ # Load test data. test_file = 'single_field_single_file.http' with open(os.path.join(http_tests_dir, test_file), 'rb') as f: test_data = f.read() # Create form parser. self.make('boundary') # Write all bytes. # NOTE: Can't simply do `for b in test_data`, since that gives # an integer when iterating over a bytes object on Python 3. i = 0 for x in range(len(test_data)): b = test_data[x:x + 1] i += self.f.write(b) self.f.finalize() # Assert we processed everything. self.assertEqual(i, len(test_data)) # Assert that our file and field are here. self.assert_field(b'field', b'test1') self.assert_file(b'file', b'file.txt', b'test2') def test_feed_blocks(self): """ This test parses a simple multipart body 1 byte at a time. """ # Load test data. test_file = 'single_field_blocks.http' with open(os.path.join(http_tests_dir, test_file), 'rb') as f: test_data = f.read() for c in range(1, len(test_data) + 1): # Skip first `d` bytes - not interesting for d in range(c): # Create form parser. self.make('boundary') # Skip i = 0 self.f.write(test_data[:d]) i += d for x in range(d, len(test_data), c): # Write a chunk to achieve condition # `i == data_length - 1` # in boundary search loop (multipatr.py:1302) b = test_data[x:x + c] i += self.f.write(b) self.f.finalize() # Assert we processed everything. self.assertEqual(i, len(test_data)) # Assert that our field is here. self.assert_field(b'field', b'0123456789ABCDEFGHIJ0123456789ABCDEFGHIJ') @slow_test def test_request_body_fuzz(self): """ This test randomly fuzzes the request body to ensure that no strange exceptions are raised and we don't end up in a strange state. The fuzzing consists of randomly doing one of the following: - Adding a random byte at a random offset - Randomly deleting a single byte - Randomly swapping two bytes """ # Load test data. test_file = 'single_field_single_file.http' with open(os.path.join(http_tests_dir, test_file), 'rb') as f: test_data = f.read() iterations = 1000 successes = 0 failures = 0 exceptions = 0 print("Running %d iterations of fuzz testing:" % (iterations,)) for i in range(iterations): # Create a bytearray to mutate. fuzz_data = bytearray(test_data) # Pick what we're supposed to do. choice = random.choice([1, 2, 3]) if choice == 1: # Add a random byte. i = random.randrange(len(test_data)) b = random.randrange(256) fuzz_data.insert(i, b) msg = "Inserting byte %r at offset %d" % (b, i) elif choice == 2: # Remove a random byte. i = random.randrange(len(test_data)) del fuzz_data[i] msg = "Deleting byte at offset %d" % (i,) elif choice == 3: # Swap two bytes. i = random.randrange(len(test_data) - 1) fuzz_data[i], fuzz_data[i + 1] = fuzz_data[i + 1], fuzz_data[i] msg = "Swapping bytes %d and %d" % (i, i + 1) # Print message, so if this crashes, we can inspect the output. print(" " + msg) # Create form parser. self.make('boundary') # Feed with data, and ignore form parser exceptions. i = 0 try: i = self.f.write(bytes(fuzz_data)) self.f.finalize() except FormParserError: exceptions += 1 else: if i == len(fuzz_data): successes += 1 else: failures += 1 print("--------------------------------------------------") print("Successes: %d" % (successes,)) print("Failures: %d" % (failures,)) print("Exceptions: %d" % (exceptions,)) @slow_test def test_request_body_fuzz_random_data(self): """ This test will fuzz the multipart parser with some number of iterations of randomly-generated data. """ iterations = 1000 successes = 0 failures = 0 exceptions = 0 print("Running %d iterations of fuzz testing:" % (iterations,)) for i in range(iterations): data_size = random.randrange(100, 4096) data = os.urandom(data_size) print(" Testing with %d random bytes..." % (data_size,)) # Create form parser. self.make('boundary') # Feed with data, and ignore form parser exceptions. i = 0 try: i = self.f.write(bytes(data)) self.f.finalize() except FormParserError: exceptions += 1 else: if i == len(data): successes += 1 else: failures += 1 print("--------------------------------------------------") print("Successes: %d" % (successes,)) print("Failures: %d" % (failures,)) print("Exceptions: %d" % (exceptions,)) def test_bad_start_boundary(self): self.make('boundary') data = b'--boundary\rfoobar' with self.assertRaises(MultipartParseError): self.f.write(data) self.make('boundary') data = b'--boundaryfoobar' with self.assertRaises(MultipartParseError): i = self.f.write(data) def test_octet_stream(self): files = [] def on_file(f): files.append(f) on_field = Mock() on_end = Mock() f = FormParser('application/octet-stream', on_field, on_file, on_end=on_end, file_name=b'foo.txt') self.assertTrue(isinstance(f.parser, OctetStreamParser)) f.write(b'test') f.write(b'1234') f.finalize() # Assert that we only recieved a single file, with the right data, and that we're done. self.assertFalse(on_field.called) self.assertEqual(len(files), 1) self.assert_file_data(files[0], b'test1234') self.assertTrue(on_end.called) def test_querystring(self): fields = [] def on_field(f): fields.append(f) on_file = Mock() on_end = Mock() def simple_test(f): # Reset tracking. del fields[:] on_file.reset_mock() on_end.reset_mock() # Write test data. f.write(b'foo=bar') f.write(b'&test=asdf') f.finalize() # Assert we only recieved 2 fields... self.assertFalse(on_file.called) self.assertEqual(len(fields), 2) # ...assert that we have the correct data... self.assertEqual(fields[0].field_name, b'foo') self.assertEqual(fields[0].value, b'bar') self.assertEqual(fields[1].field_name, b'test') self.assertEqual(fields[1].value, b'asdf') # ... and assert that we've finished. self.assertTrue(on_end.called) f = FormParser('application/x-www-form-urlencoded', on_field, on_file, on_end=on_end) self.assertTrue(isinstance(f.parser, QuerystringParser)) simple_test(f) f = FormParser('application/x-url-encoded', on_field, on_file, on_end=on_end) self.assertTrue(isinstance(f.parser, QuerystringParser)) simple_test(f) def test_close_methods(self): parser = Mock() f = FormParser('application/x-url-encoded', None, None) f.parser = parser f.finalize() parser.finalize.assert_called_once_with() f.close() parser.close.assert_called_once_with() def test_bad_content_type(self): # We should raise a ValueError for a bad Content-Type with self.assertRaises(ValueError): f = FormParser('application/bad', None, None) def test_no_boundary_given(self): # We should raise a FormParserError when parsing a multipart message # without a boundary. with self.assertRaises(FormParserError): f = FormParser('multipart/form-data', None, None) def test_bad_content_transfer_encoding(self): data = b'----boundary\r\nContent-Disposition: form-data; name="file"; filename="test.txt"\r\nContent-Type: text/plain\r\nContent-Transfer-Encoding: badstuff\r\n\r\nTest\r\n----boundary--\r\n' files = [] def on_file(f): files.append(f) on_field = Mock() on_end = Mock() # Test with erroring. config = {'UPLOAD_ERROR_ON_BAD_CTE': True} f = FormParser('multipart/form-data', on_field, on_file, on_end=on_end, boundary='--boundary', config=config) with self.assertRaises(FormParserError): f.write(data) f.finalize() # Test without erroring. config = {'UPLOAD_ERROR_ON_BAD_CTE': False} f = FormParser('multipart/form-data', on_field, on_file, on_end=on_end, boundary='--boundary', config=config) f.write(data) f.finalize() self.assert_file_data(files[0], b'Test') def test_handles_None_fields(self): fields = [] def on_field(f): fields.append(f) on_file = Mock() on_end = Mock() f = FormParser('application/x-www-form-urlencoded', on_field, on_file, on_end=on_end) f.write(b'foo=bar&another&baz=asdf') f.finalize() self.assertEqual(fields[0].field_name, b'foo') self.assertEqual(fields[0].value, b'bar') self.assertEqual(fields[1].field_name, b'another') self.assertEqual(fields[1].value, None) self.assertEqual(fields[2].field_name, b'baz') self.assertEqual(fields[2].value, b'asdf') def test_max_size_multipart(self): # Load test data. test_file = 'single_field_single_file.http' with open(os.path.join(http_tests_dir, test_file), 'rb') as f: test_data = f.read() # Create form parser. self.make('boundary') # Set the maximum length that we can process to be halfway through the # given data. self.f.parser.max_size = len(test_data) / 2 i = self.f.write(test_data) self.f.finalize() # Assert we processed the correct amount. self.assertEqual(i, len(test_data) / 2) def test_max_size_form_parser(self): # Load test data. test_file = 'single_field_single_file.http' with open(os.path.join(http_tests_dir, test_file), 'rb') as f: test_data = f.read() # Create form parser setting the maximum length that we can process to # be halfway through the given data. size = len(test_data) / 2 self.make('boundary', config={'MAX_BODY_SIZE': size}) i = self.f.write(test_data) self.f.finalize() # Assert we processed the correct amount. self.assertEqual(i, len(test_data) / 2) def test_octet_stream_max_size(self): files = [] def on_file(f): files.append(f) on_field = Mock() on_end = Mock() f = FormParser('application/octet-stream', on_field, on_file, on_end=on_end, file_name=b'foo.txt', config={'MAX_BODY_SIZE': 10}) f.write(b'0123456789012345689') f.finalize() self.assert_file_data(files[0], b'0123456789') def test_invalid_max_size_multipart(self): with self.assertRaises(ValueError): q = MultipartParser(b'bound', max_size='foo') class TestHelperFunctions(unittest.TestCase): def test_create_form_parser(self): r = create_form_parser({'Content-Type': 'application/octet-stream'}, None, None) self.assertTrue(isinstance(r, FormParser)) def test_create_form_parser_error(self): headers = {} with self.assertRaises(ValueError): create_form_parser(headers, None, None) def test_parse_form(self): on_field = Mock() on_file = Mock() parse_form( {'Content-Type': 'application/octet-stream', }, BytesIO(b'123456789012345'), on_field, on_file ) on_file.assert_called_once() # Assert that the first argument of the call (a File object) has size # 15 - i.e. all data is written. self.assertEqual(on_file.call_args[0][0].size, 15) def test_parse_form_content_length(self): files = [] def on_file(file): files.append(file) parse_form( {'Content-Type': 'application/octet-stream', 'Content-Length': '10' }, BytesIO(b'123456789012345'), None, on_file ) self.assertEqual(len(files), 1) self.assertEqual(files[0].size, 10) def suite(): suite = unittest.TestSuite() suite.addTest(unittest.makeSuite(TestFile)) suite.addTest(unittest.makeSuite(TestParseOptionsHeader)) suite.addTest(unittest.makeSuite(TestBaseParser)) suite.addTest(unittest.makeSuite(TestQuerystringParser)) suite.addTest(unittest.makeSuite(TestOctetStreamParser)) suite.addTest(unittest.makeSuite(TestBase64Decoder)) suite.addTest(unittest.makeSuite(TestQuotedPrintableDecoder)) suite.addTest(unittest.makeSuite(TestFormParser)) suite.addTest(unittest.makeSuite(TestHelperFunctions)) return suite python-multipart-0.0.5/requirements.txt000066400000000000000000000002361336005506300203420ustar00rootroot00000000000000atomicwrites==1.2.1 attrs==18.2.0 coverage==4.5.1 mock==2.0.0 more-itertools==4.3.0 pbr==4.3.0 pluggy==0.7.1 py==1.6.0 pytest==3.8.2 PyYAML==3.13 six==1.11.0 python-multipart-0.0.5/setup.py000077500000000000000000000030651336005506300165760ustar00rootroot00000000000000#!/usr/bin/env python from __future__ import print_function import os import re import sys from setuptools import setup version_file = os.path.join('multipart', '_version.py') with open(version_file, 'rb') as f: version_data = f.read().strip() if sys.version_info[0] >= 3: version_data = version_data.decode('ascii') version_re = re.compile(r'((?:\d+)\.(?:\d+)\.(?:\d+))') version = version_re.search(version_data).group(0) setup(name='python-multipart', version=version, description='A streaming multipart parser for Python', author='Andrew Dunham', url='http://github.com/andrew-d/python-multipart', license='Apache', platforms='any', zip_safe=False, install_requires=[ 'six>=1.4.0', ], tests_require=[ 'pytest', 'pytest-cov', 'Mock', 'PyYAML' ], packages=[ 'multipart', 'multipart.tests', ], classifiers=[ 'Development Status :: 3 - Alpha', 'Environment :: Web Environment', 'Intended Audience :: Developers', 'License :: OSI Approved :: Apache Software License', 'Operating System :: OS Independent', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', 'Programming Language :: Python :: 3.6', 'Programming Language :: Python :: 3.3', 'Topic :: Software Development :: Libraries :: Python Modules' ], test_suite = 'multipart.tests.suite', ) python-multipart-0.0.5/tasks.py000066400000000000000000000043221336005506300165550ustar00rootroot00000000000000from __future__ import print_function import os import re import sys from invoke import task, run version_file = os.path.join('multipart', '_version.py') version_regex = re.compile(r'((?:\d+)\.(?:\d+)\.(?:\d+))') # Get around Python 2.X's lack of 'nonlocal' keyword class g(object): test_success = False @task def test(all=False): test_cmd = [ 'py.test', # Test command '--cov-report term-missing', # Print only uncovered lines to stdout '--cov-config .coveragerc', # Use this file for configuration '--cov multipart', # Test only this module '--timeout=30' # Each test should timeout after 30 sec ] # Default to not running the slow tests. if not all: test_cmd.append('-m "not slow_test"') # Test in this directory test_cmd.append(os.path.join("multipart", "tests")) # Run the command. # TODO: why does this fail with pty=True? res = run(' '.join(test_cmd), pty=False) g.test_success = res.ok @task def bump(type): # Read and parse version. with open(version_file, 'rb') as f: file_data = f.read().replace('\r\n', '\n') m = version_regex.search(file_data) if m is None: print("Could not find version in '{0}'!".format(version_file), file=sys.stderr) return version = m.group(0) before = file_data[0:m.start(0)] after = file_data[m.end(0):] # Bump properly. ver_nums = [int(x) for x in version.split('.')] if type == 'patch': ver_nums[2] += 1 elif type == 'minor': ver_nums[1] += 1 elif type == 'major': ver_nums[0] += 1 else: print("Invalid version type: '%s'" % (type,), file=sys.stderr) return # Construct new data and write to file. new_ver = ".".join(str(x) for x in ver_nums) new_data = before + new_ver + after with open(version_file, 'wb') as f: f.write(new_data) # Print information. print("Bumped version from: %s --> %s" % (version, new_ver)) @task(pre=['test']) def deploy(): if not g.test_success: print("Tests must pass before deploying!", file=sys.stderr) return run('python setup.py sdist upload') python-multipart-0.0.5/tox.ini000066400000000000000000000004661336005506300163760ustar00rootroot00000000000000[tox] envlist = py27,py31,py32,py33 [testenv] deps= pytest pytest-cov pytest-timeout mock PyYAML commands= py.test --cov-report term-missing --cov-config .coveragerc --cov multipart --timeout=30 multipart/tests [testenv:py31] basepython=/usr/local/Cellar/python31/3.1.5/bin/python3.1